View Javadoc

1   /*
2    * Copyright 2004-2006 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.tuigwaa.controller;
17  
18  import java.io.ByteArrayOutputStream;
19  import java.util.ArrayList;
20  import java.util.Date;
21  import java.util.Iterator;
22  import java.util.List;
23  
24  import javax.servlet.http.HttpServletRequest;
25  import javax.servlet.http.HttpServletResponse;
26  
27  import org.apache.commons.beanutils.PropertyUtils;
28  import org.apache.poi.hssf.usermodel.HSSFCell;
29  import org.apache.poi.hssf.usermodel.HSSFCellStyle;
30  import org.apache.poi.hssf.usermodel.HSSFRow;
31  import org.apache.poi.hssf.usermodel.HSSFSheet;
32  import org.apache.poi.hssf.usermodel.HSSFWorkbook;
33  import org.apache.struts.action.ActionForm;
34  import org.apache.struts.action.ActionForward;
35  import org.apache.struts.action.ActionMapping;
36  import org.apache.struts.actions.MappingDispatchAction;
37  import org.seasar.tuigwaa.cms.ContentsService;
38  import org.seasar.tuigwaa.cms.ContentsStoreService;
39  import org.seasar.tuigwaa.cms.core.CmsConstants;
40  import org.seasar.tuigwaa.cms.core.Resource;
41  import org.seasar.tuigwaa.database.DataRow;
42  import org.seasar.tuigwaa.database.DataTable;
43  import org.seasar.tuigwaa.database.util.FileData;
44  import org.seasar.tuigwaa.database.util.FileDataManager.FileDataCriteria;
45  import org.seasar.tuigwaa.model.DAOService;
46  import org.seasar.tuigwaa.model.DataService;
47  import org.seasar.tuigwaa.model.ModelService;
48  import org.seasar.tuigwaa.model.common.EntityUtils;
49  import org.seasar.tuigwaa.model.core.TgwEntity;
50  import org.seasar.tuigwaa.plugin.TgwPluginUtils;
51  import org.seasar.tuigwaa.system.Constants;
52  import org.seasar.tuigwaa.util.TgwContext;
53  
54  import com.isenshi.util.CharUtil;
55  import com.isenshi.util.HttpUtils;
56  import com.isenshi.util.SimpleFile;
57  import com.isenshi.util.extlib.StrutsUtil;
58  import com.sun.syndication.feed.synd.SyndContent;
59  import com.sun.syndication.feed.synd.SyndContentImpl;
60  import com.sun.syndication.feed.synd.SyndEntry;
61  import com.sun.syndication.feed.synd.SyndEntryImpl;
62  import com.sun.syndication.feed.synd.SyndFeed;
63  import com.sun.syndication.feed.synd.SyndFeedImpl;
64  import com.sun.syndication.io.SyndFeedOutput;
65  
66  /***
67   * Generates various output stream of content type other text/html.
68   * 
69   * @author someda
70   */
71  public class ByteArrayOutputAction extends MappingDispatchAction {
72  
73  	private ContentsStoreService slideService_;
74  
75  	private ContentsService wikiService_;
76  
77  	private ModelService entityService_;
78  
79  	private DAOService daoService_;
80  
81  	private DataService dataService_;
82  
83  	private static final String CONTENT_TYPE_XML = "text/xml;charset=UTF-8";
84  
85  	private static final String CONTENT_TYPE_PDF = "application/pdf";
86  
87  	private static final String CONTENT_TYPE_RTF = "text/rtf";
88  
89  	private static final String CONTENT_TYPE_XLS = "application/vnd.ms-excel";
90  
91  	//
92  	// The filename in specified in content-dispostion, is not allowed to
93  	// use multibyte character, and should follows RFC2231 style.
94  	// http://www.ietf.org/rfc/rfc2231.txt
95  	//
96  	// also IE has the following problem
97  	// http://support.microsoft.com/default.aspx?scid=kb;ja;436616
98  	// private static final String CONTENT_DISPOSITION_PREFIX =
99  	// "attachment;filename";
100 
101 	private static final String DEFAULT_FEEDVERSION = "rss_2.0";
102 
103 	private static final String FEED_TITLE = Constants.PRODUCT_NAME
104 			+ " feed for ";
105 
106 	private static final String FEED_DESCRIPTION = "generated by "
107 			+ Constants.PRODUCT_NAME;
108 
109 	public ByteArrayOutputAction(ContentsStoreService slideService,
110 			ContentsService wikiService, ModelService entityService,
111 			DAOService daoService, DataService dataService) {
112 		this.slideService_ = slideService;
113 		this.wikiService_ = wikiService;
114 		this.entityService_ = entityService;
115 		this.daoService_ = daoService;
116 		this.dataService_ = dataService;
117 	}
118 
119 	public ActionForward generatePDF(ActionMapping mapping, ActionForm form,
120 			HttpServletRequest request, HttpServletResponse response)
121 			throws Exception {
122 		return doGenerateBinaryPage(request, response,
123 				CmsConstants.OUTPUTTYPE_PDF, CONTENT_TYPE_PDF, "pdf");
124 	}
125 
126 	public ActionForward generateRTF(ActionMapping mapping, ActionForm form,
127 			HttpServletRequest request, HttpServletResponse response)
128 			throws Exception {
129 		return doGenerateBinaryPage(request, response,
130 				CmsConstants.OUTPUTTYPE_RTF, CONTENT_TYPE_RTF, "rtf");
131 	}
132 
133 	public ActionForward generateFeed(ActionMapping mapping, ActionForm form,
134 			HttpServletRequest request, HttpServletResponse response)
135 			throws Exception {
136 
137 		String url = request.getRequestURL().toString();
138 		int index = url.lastIndexOf("/");
139 		String base = url.substring(0, index);
140 		String siteName = TgwContext.getSiteName();
141 
142 		response.setContentType(CONTENT_TYPE_XML);
143 
144 		String feedversion = request.getParameter(Constants.PARAM_FEEDVERSION);
145 		if (feedversion == null)
146 			feedversion = DEFAULT_FEEDVERSION;
147 
148 		SyndFeed feed = new SyndFeedImpl();
149 		feed.setFeedType(feedversion);
150 		feed.setTitle(FEED_TITLE + siteName);
151 		feed.setAuthor(Constants.PRODUCT_NAME);
152 		feed.setLink(Constants.PRODUCT_URL);
153 		feed.setDescription(FEED_DESCRIPTION);
154 		feed.setLanguage("ja");
155 		SyndEntry entry;
156 		SyndContent content;
157 
158 		List list = slideService_.getLatestContents(siteName, 10);
159 		List entries = new ArrayList();
160 		for (Iterator i = list.iterator(); i.hasNext();) {
161 			Resource resource = (Resource) i.next();
162 			entry = new SyndEntryImpl();
163 			content = new SyndContentImpl();
164 			content.setType("text/plain");
165 			String link = base + "/" + CharUtil.urlEncode(resource.getPath());
166 			entry.setTitle(resource.getPath());
167 			entry.setLink(link);
168 			entry.setPublishedDate(resource.getModificationDateAsDate());
169 			content.setValue("updated contents, click here " + link);
170 			entry.setDescription(content);
171 			entries.add(entry);
172 		}
173 		feed.setEntries(entries);
174 
175 		SyndFeedOutput output = new SyndFeedOutput();
176 		output.output(feed, response.getWriter());
177 		response.getWriter().close();
178 
179 		/*
180 		 * The following way resulted in character encoding problem
181 		 * ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter
182 		 * writer = new PrintWriter(baos); output.output(feed,writer); byte[] b =
183 		 * baos.toByteArray(); baos.close(); writer.close();
184 		 * doWrite(response,b);
185 		 */
186 		return null;
187 	}
188 
189 	public ActionForward generateTableFeed(ActionMapping mapping,
190 			ActionForm form, HttpServletRequest request,
191 			HttpServletResponse response) throws Exception {
192 
193 		String url = request.getRequestURL().toString();
194 		int index = url.lastIndexOf("/");
195 		String base = url.substring(0, index);
196 		String siteName = TgwContext.getSiteName();
197 		String pageName = TgwContext.getPageName();
198 
199 		response.setContentType(CONTENT_TYPE_XML);
200 
201 		String feedversion = request.getParameter(Constants.PARAM_FEEDVERSION);
202 		if (feedversion == null)
203 			feedversion = DEFAULT_FEEDVERSION;
204 
205 		String entityName = request.getParameter(Constants.PARAM_ENTITY_NAME);
206 		String filterName = StrutsUtil.getURLDecodedParameter(request,
207 				Constants.PARAM_ENTITY_FILTER);
208 
209 		SyndFeed feed = new SyndFeedImpl();
210 		feed.setFeedType(feedversion);
211 		feed.setTitle(FEED_TITLE + siteName);
212 		feed.setAuthor(Constants.PRODUCT_NAME);
213 		feed.setLink(Constants.PRODUCT_URL);
214 		feed.setDescription(FEED_DESCRIPTION);
215 		feed.setLanguage("ja");
216 		SyndEntry entry;
217 		SyndContent content;
218 
219 		TgwEntity entity = entityService_.getEntity(siteName, entityName);
220 		// DaoMethod daoMethod =
221 		// daoService_.getDAO(entity).getMethod(filterName);
222 		// DataTable dataTable = (DataTable) daoMethod.evaluate();
223 		DataTable dataTable = dataService_.find(entity, filterName);
224 
225 		List entries = new ArrayList();
226 		while (dataTable.hasNext()) {
227 			DataRow dataRow = dataTable.nextRow();
228 			Object bean = dataRow.getDataObject();
229 
230 			Long id = EntityUtils.getId(bean);
231 
232 			entry = new SyndEntryImpl();
233 			content = new SyndContentImpl();
234 			content.setType("text/plain");
235 			String link = base + "/" + CharUtil.urlEncode(pageName) + "?"
236 					+ TgwPluginUtils.createEntityBindingName(entityName) + "="
237 					+ id;
238 			entry.setTitle(entity.getDisplayName() + "-" + filterName + "("
239 					+ id + ")");
240 			entry.setLink(link);
241 
242 			Object data = EntityUtils.getProperty(bean,
243 					Constants.ENTITY_BUILTIN_CREATIONDATE);
244 			Date creationDate = (Date) data;
245 			if (creationDate == null) {
246 				creationDate = new Date();
247 			}
248 			entry.setPublishedDate(creationDate);
249 			content.setValue("updated contents, click here " + link);
250 			entry.setDescription(content);
251 			entries.add(entry);
252 		}
253 		feed.setEntries(entries);
254 
255 		SyndFeedOutput output = new SyndFeedOutput();
256 		output.output(feed, response.getWriter());
257 		return null;
258 	}
259 
260 	public ActionForward generateXLS(ActionMapping mapping, ActionForm form,
261 			HttpServletRequest request, HttpServletResponse response)
262 			throws Exception {
263 
264 		HSSFWorkbook workbook = new HSSFWorkbook();
265 		HSSFSheet sheet = workbook.createSheet("new sheet");
266 		HSSFRow row = sheet.createRow(0);
267 		HSSFCell cell = row.createCell((short) 0);
268 		cell.setCellValue("hoge");
269 		HSSFCellStyle style = workbook.createCellStyle();
270 		style.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);
271 		cell.setCellStyle(style);
272 
273 		ByteArrayOutputStream baos = new ByteArrayOutputStream();
274 		workbook.write(baos);
275 		byte[] b = baos.toByteArray();
276 		baos.close();
277 
278 		HttpUtils.write(request, response, CONTENT_TYPE_XLS, b, "test.xls");
279 
280 		return null;
281 	}
282 
283 	public ActionForward fileDownload(ActionMapping mapping, ActionForm form,
284 			HttpServletRequest request, HttpServletResponse response)
285 			throws Exception {
286 
287 		String schema = TgwContext.getSiteName();
288 		String entityName = request.getParameter(Constants.PARAM_ENTITY_NAME);
289 		String fieldName = request
290 				.getParameter(Constants.PARAM_ENTITY_FIELDNAME);
291 		Long id = Long.valueOf(request.getParameter(Constants.PARAM_ENTITY_ID));
292 
293 		TgwEntity entity = entityService_.getEntity(schema, entityName);
294 		Object obj = daoService_.getDAO(entity).load(id);
295 		byte[] bytes = (byte[]) PropertyUtils.getProperty(obj, fieldName);
296 		SimpleFile file = (SimpleFile) CharUtil.toObject(bytes);
297 
298 		String filedataEntityName = TgwPluginUtils
299 				.toPluginEntityName(FileData.class);
300 		TgwEntity filedataEntity = entityService_.getEntity(schema,
301 				filedataEntityName);
302 
303 		DataTable dataTable = (DataTable) dataService_.find(filedataEntity,
304 				null, new FileDataCriteria(entityName, fieldName, "" + id));
305 		byte[] outputBytes = null;
306 		if (dataTable.hasNext()) {
307 			FileData filedata = (FileData) dataTable.nextRow().getDataObject();
308 			outputBytes = filedata.getBytes();
309 		}
310 		if(outputBytes == null){
311 			return null;
312 		}
313 		HttpUtils.write(request, response, file.getContentType(), outputBytes,
314 				file.getFileName());
315 		return null;
316 	} 
317 	
318 	
319 	// [Start] ----- Private Method ------
320 
321 	private ActionForward doGenerateBinaryPage(HttpServletRequest request,
322 			HttpServletResponse response, int targetType, String contentType,
323 			String extension) throws Exception {
324 
325 		TgwContext.relayToCmsParameter(new String[] {
326 				Constants.PARAM_PREFIX_ENTITY, Constants.PARAM_PREFIX_PLUGIN });
327 
328 		TgwContext.initPageName();
329 		String pageName = TgwContext.getPageName();
330 		String siteName = TgwContext.getSiteName();
331 
332 		byte[] content = (byte[]) wikiService_.getPage(siteName, pageName,
333 				targetType).getContent();
334 
335 		HttpUtils.write(request, response, contentType, content, pageName + "."
336 				+ extension);
337 
338 		return null;
339 	}
340 }