001: /*
002: * (C) Copyright 2000 - 2005 Nabh Information Systems, Inc.
003: *
004: * This program is free software; you can redistribute it and/or
005: * modify it under the terms of the GNU General Public License
006: * as published by the Free Software Foundation; either version 2
007: * of the License, or (at your option) any later version.
008: *
009: * This program is distributed in the hope that it will be useful,
010: * but WITHOUT ANY WARRANTY; without even the implied warranty of
011: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
012: * GNU General Public License for more details.
013: *
014: * You should have received a copy of the GNU General Public License
015: * along with this program; if not, write to the Free Software
016: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
017: *
018: */
019: package com.nabhinc.portlet.fileupload;
020:
021: import java.io.File;
022: import java.io.FileOutputStream;
023: import java.io.InputStream;
024: import java.io.PrintWriter;
025: import java.io.StringWriter;
026: import java.util.List;
027:
028: import javax.portlet.ActionRequest;
029: import javax.portlet.ActionResponse;
030: import javax.portlet.PortletConfig;
031: import javax.portlet.PortletException;
032:
033: import com.nabhinc.portlet.base.BasePortlet;
034:
035: import org.apache.commons.fileupload.disk.DiskFileItemFactory;
036: import org.apache.commons.fileupload.portlet.PortletFileUpload;
037: import org.apache.commons.fileupload.FileItem;
038:
039: /**
040: * Sample portlet demonstrating how files can be uploaded from a portlet. The
041: * portlet can be configured using the following init parameters in the
042: * portlet definition given in portlet.xml file.
043: * <ul>
044: * <li>
045: * repositoryPath - Path relative to the Web app root that specifies the
046: * directory used for temporarily store large uploaded files. Default is
047: * "/WEB-INF/file_upload/temp".
048: * </li>
049: * <li>
050: * uploadDirectory - Directory for storing uploaded files. Default is
051: * "/WEB-INF/file_upload/uploads".
052: * </li>
053: * <li>
054: * threshold - Threshold file size beyond which uploaded files will be
055: * temporarily stored in the directory specified by repositoryPath param.
056: * Default is 1000.
057: * </li>
058: * <li>maxUploadSize - Maximum size (in bytes) of upload files. Default
059: * is 10000 Bytes.
060: * </li>
061: * </ul>
062: *
063: * @author Padmanabh Dabke
064: * (c) 2005 Nabh Information Systems, Inc. All Rights Reserved.
065: */
066: public class FileUploadPortlet extends BasePortlet {
067: private String fupRepositoryPath = null;
068: private String fupUploadDir = null;
069: private int fupThresholdSize = 1000;
070: private long fupMaxUploadSize = 10000;
071:
072: public void init(PortletConfig config) throws PortletException {
073: super .init(config);
074:
075: String uploadTempDir = config
076: .getInitParameter("repositoryPath");
077: if (uploadTempDir == null) {
078: File tempFile = (File) config.getPortletContext()
079: .getAttribute("javax.servlet.context.tempdir");
080: if (tempFile == null) {
081: setTempDirectoryFromRelativePath(
082: "/WEB-INF/file_upload/temp", config);
083: } else {
084: fupRepositoryPath = tempFile.getAbsolutePath();
085: }
086:
087: } else {
088: // Check if this is an absolute path
089: if (new File(uploadTempDir).exists()) {
090: fupRepositoryPath = uploadTempDir;
091: } else {
092: if (!uploadTempDir.startsWith("/"))
093: uploadTempDir = "/" + uploadTempDir;
094: setTempDirectoryFromRelativePath(uploadTempDir, config);
095: }
096: }
097:
098: String temp = config.getInitParameter("uploadDirectory");
099: if (temp == null)
100: temp = "/WEB-INF/file_upload/uploads";
101: fupUploadDir = getRealPath(config.getPortletContext(), temp);
102:
103: temp = config.getInitParameter("threshold");
104: if (temp != null) {
105: fupThresholdSize = Integer.parseInt(temp);
106: }
107:
108: temp = config.getInitParameter("maxUploadSize");
109: if (temp != null) {
110: fupMaxUploadSize = Long.parseLong(temp);
111: }
112:
113: // Make sure the directories exist
114: new File(fupRepositoryPath).mkdirs();
115: new File(fupUploadDir).mkdirs();
116:
117: }
118:
119: public void processAction(ActionRequest aReq, ActionResponse aRes)
120: throws PortletException {
121:
122: // Parses the multi-part file content and save uploaded files.
123:
124: String message = "<div class=\"portlet-msg-success\">File upload successful.</div.";
125: try {
126: DiskFileItemFactory factory = new DiskFileItemFactory();
127: factory.setRepository(new File(fupRepositoryPath));
128: factory.setSizeThreshold(fupThresholdSize);
129: PortletFileUpload fileUpload = new PortletFileUpload(
130: factory);
131: fileUpload.setSizeMax(fupMaxUploadSize);
132: List itemList = fileUpload.parseRequest(aReq);
133: for (int i = 0; i < itemList.size(); i++) {
134: FileItem item = (FileItem) itemList.get(i);
135: if (!item.isFormField()) {
136: // Set attribute corresponding the uploaded file item
137: String fileName = item.getName();
138: if (fileName == null || fileName.equals("")) {
139: message = "<div class=\"portlet-msg-error\">Please select a file to upload.</div>";
140: break;
141: }
142: int slashIndex = fileName.lastIndexOf("/");
143: if (slashIndex > -1) {
144: fileName = fileName.substring(slashIndex + 1);
145: }
146: slashIndex = fileName.lastIndexOf("\\");
147: if (slashIndex > -1) {
148: fileName = fileName.substring(slashIndex + 1);
149: }
150:
151: File uploadFile = new File(fupUploadDir, fileName);
152: InputStream is = item.getInputStream();
153: FileOutputStream out = new FileOutputStream(
154: uploadFile);
155: byte[] content = new byte[1000];
156: int bufSize = -1;
157: while ((bufSize = is.read(content)) > 0) {
158: out.write(content, 0, bufSize);
159: }
160: out.flush();
161: out.close();
162: }
163: }
164: } catch (Exception e) {
165: StringWriter writer = new StringWriter();
166: PrintWriter pWriter = new PrintWriter(writer);
167: pWriter.write("<div class=\"portlet-msg-error\">");
168: pWriter.write("Failed to upload file(s).<br/>");
169: pWriter.write(e.getLocalizedMessage());
170: pWriter.write("</div>");
171: pWriter.flush();
172: pWriter.close();
173: message = writer.toString();
174: }
175: aRes.setRenderParameter("message", message);
176:
177: }
178:
179: private void setTempDirectoryFromRelativePath(String uploadTempDir,
180: PortletConfig config) throws PortletException {
181: fupRepositoryPath = getRealPath(config.getPortletContext(),
182: uploadTempDir);
183: if (fupRepositoryPath == null) {
184: bpLogger
185: .warning("Could not figure out temp upload directory. This happens when the app server does not explode your war files.");
186: } else {
187: try {
188: File uploadDir = new File(fupRepositoryPath);
189: uploadDir.mkdirs();
190: } catch (Exception ex) {
191: throw new PortletException(
192: "Failed to create upload temp directory.", ex);
193: }
194: }
195:
196: }
197:
198: }
|