redlist WS export added .json and .xml functionality
[cdmlib.git] / cdmlib-remote / src / main / java / eu / etaxonomy / cdm / remote / controller / checklist / ChecklistDemoController.java
1 /**
2 * Copyright (C) 2009 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
8 */
9 package eu.etaxonomy.cdm.remote.controller.checklist;
10
11 import java.io.ByteArrayInputStream;
12 import java.io.ByteArrayOutputStream;
13 import java.io.File;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.InputStreamReader;
17 import java.io.PrintWriter;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25 import java.util.UUID;
26
27 import javax.servlet.http.Cookie;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30
31 import org.apache.log4j.Logger;
32 import org.springframework.beans.factory.annotation.Autowired;
33 import org.springframework.beans.propertyeditors.UUIDEditor;
34 import org.springframework.context.ApplicationContext;
35 import org.springframework.context.ResourceLoaderAware;
36 import org.springframework.core.io.Resource;
37 import org.springframework.core.io.ResourceLoader;
38 import org.springframework.stereotype.Controller;
39 import org.springframework.web.bind.WebDataBinder;
40 import org.springframework.web.bind.annotation.InitBinder;
41 import org.springframework.web.bind.annotation.RequestMapping;
42 import org.springframework.web.bind.annotation.RequestMethod;
43 import org.springframework.web.bind.annotation.RequestParam;
44 import org.springframework.web.servlet.ModelAndView;
45
46 import eu.etaxonomy.cdm.api.service.IService;
47 import eu.etaxonomy.cdm.api.service.ITermService;
48 import eu.etaxonomy.cdm.common.DocUtils;
49 import eu.etaxonomy.cdm.io.common.CdmApplicationAwareDefaultExport;
50 import eu.etaxonomy.cdm.io.csv.redlist.demo.CsvDemoExportConfigurator;
51 import eu.etaxonomy.cdm.io.csv.redlist.demo.CsvDemoRecord;
52 import eu.etaxonomy.cdm.model.description.Feature;
53 import eu.etaxonomy.cdm.model.location.NamedArea;
54 import eu.etaxonomy.cdm.model.taxon.Classification;
55 import eu.etaxonomy.cdm.model.taxon.Taxon;
56 import eu.etaxonomy.cdm.remote.controller.AbstractController;
57 import eu.etaxonomy.cdm.remote.controller.ProgressMonitorController;
58 import eu.etaxonomy.cdm.remote.controller.util.PagerParameters;
59 import eu.etaxonomy.cdm.remote.editor.TermBaseListPropertyEditor;
60 import eu.etaxonomy.cdm.remote.editor.UUIDListPropertyEditor;
61 import eu.etaxonomy.cdm.remote.editor.UuidList;
62 import eu.etaxonomy.cdm.remote.view.HtmlView;
63
64 /**
65 * @author a.oppermann
66 * @created 20.09.2012
67 *
68 */
69 @Controller
70 @RequestMapping(value = { "/checklist" })
71 public class ChecklistDemoController extends AbstractController implements ResourceLoaderAware{
72
73 /**
74 *
75 */
76 @Autowired
77 private ApplicationContext appContext;
78
79 @Autowired
80 private ITermService termService;
81
82 @Autowired
83 public ProgressMonitorController progressMonitorController;
84
85 private ResourceLoader resourceLoader;
86
87 private static final Logger logger = Logger.getLogger(ChecklistDemoController.class);
88
89 /**
90 * Helper method, which allows to convert strings directly into uuids.
91 *
92 * @param binder Special DataBinder for data binding from web request parameters to JavaBean objects.
93 */
94 @InitBinder
95 public void initBinder(WebDataBinder binder) {
96 binder.registerCustomEditor(UuidList.class, new UUIDListPropertyEditor());
97 binder.registerCustomEditor(NamedArea.class, new TermBaseListPropertyEditor<NamedArea>(termService));
98 binder.registerCustomEditor(UUID.class, new UUIDEditor());
99 }
100
101 @RequestMapping(value = {""}, method = { RequestMethod.GET })
102 public ModelAndView exportGetExplanation(HttpServletResponse response,
103 HttpServletRequest request) throws IOException{
104 ModelAndView mv = new ModelAndView();
105 // Read apt documentation file.
106 Resource resource = resourceLoader.getResource("classpath:eu/etaxonomy/cdm/doc/remote/apt/checklist-catalogue-default.apt");
107 // using input stream as this works for both files in the classes directory
108 // as well as files inside jars
109 InputStream aptInputStream = resource.getInputStream();
110 // Build Html View
111 Map<String, String> modelMap = new HashMap<String, String>();
112 // Convert Apt to Html
113 modelMap.put("html", DocUtils.convertAptToHtml(aptInputStream));
114 mv.addAllObjects(modelMap);
115
116 HtmlView hv = new HtmlView();
117 mv.setView(hv);
118 return mv;
119 }
120
121 @RequestMapping(value = { "export" }, method = { RequestMethod.GET })
122 public ModelAndView doGeneralExport(
123 @RequestParam(value = "features", required = false) UuidList featureUuids,
124 @RequestParam(value = "demoExport", required = false) boolean demoExport,
125 @RequestParam(value = "conceptExport", required = false) boolean conceptExport,
126 @RequestParam(value = "classification", required = false) String classificationUUID,
127 @RequestParam(value = "area", required = false) UuidList areas,
128 @RequestParam(value = "downloadTokenValueId", required = false) String downloadTokenValueId,
129 @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
130 @RequestParam(value = "pageSize", required = false) Integer pageSize,
131 HttpServletResponse response,
132 HttpServletRequest request) throws IOException {
133
134 try{
135
136 PagerParameters pagerParams = new PagerParameters(pageSize, pageNumber);
137 pagerParams.normalizeAndValidate(response);
138
139
140 List<CsvDemoRecord> recordList = new ArrayList<CsvDemoRecord>();
141
142 CsvDemoExportConfigurator config = setTaxExportConfigurator(classificationUUID, featureUuids, areas, null);
143 config.setRecordList(recordList);
144
145 CdmApplicationAwareDefaultExport<?> defaultExport = (CdmApplicationAwareDefaultExport<?>) appContext.getBean("defaultExport");
146 defaultExport.invoke(config);
147
148 // DefaultPagerImpl<CsvDemoRecord> dpi = new DefaultPagerImpl<CsvDemoRecord>(pagerParams.getPageIndex(), recordList.size(), pagerParams.getPageSize(), recordList);
149 ModelAndView mv = new ModelAndView();
150 mv.addObject(recordList);
151 // mv.addObject(dpi);
152 return mv;
153 }catch(Exception e){
154 return exportGetExplanation(response, request);
155 }
156
157 }
158
159
160
161
162 /**
163 * Fetches data from the application context and forwards the stream to the HttpServletResponse, which offers a file download.
164 *
165 * @param featureUuids List of uuids to download/select {@link Feature feature}features
166 * @param classificationUUID Selected {@link Classification classification} to iterate the {@link Taxon}
167 * @param response HttpServletResponse which returns the ByteArrayOutputStream
168 */
169 @RequestMapping(value = { "exportCSV" }, method = { RequestMethod.GET })
170 public void doExportRedlist(
171 @RequestParam(value = "features", required = false) UuidList featureUuids,
172 @RequestParam(value = "demoExport", required = false) boolean demoExport,
173 @RequestParam(value = "conceptExport", required = false) boolean conceptExport,
174 @RequestParam(value = "classification", required = true) String classificationUUID,
175 @RequestParam(value = "area", required = false) UuidList areas,
176 @RequestParam(value = "downloadTokenValueId", required = false) String downloadTokenValueId,
177 HttpServletResponse response,
178 HttpServletRequest request) {
179
180 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
181 CsvDemoExportConfigurator config = setTaxExportConfigurator(classificationUUID, featureUuids, areas, byteArrayOutputStream);
182 CdmApplicationAwareDefaultExport<?> defaultExport = (CdmApplicationAwareDefaultExport<?>) appContext.getBean("defaultExport");
183 logger.info("Start export...");
184 logger.info("doExportRedlist()" + requestPathAndQuery(request));
185 defaultExport.invoke(config);
186 try {
187 /*
188 * Fetch data from the appContext and forward stream to HttpServleResponse
189 *
190 * FIXME: Large Data could be out of memory
191 *
192 * HTPP Error Break
193 */
194 ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());//byteArrayOutputStream.toByteArray()
195 InputStreamReader isr = new InputStreamReader(bais);
196 Cookie progressCookie = new Cookie("fileDownloadToken", downloadTokenValueId);
197 progressCookie.setPath("/");
198 progressCookie.setMaxAge(60);
199 response.addCookie(progressCookie);
200 response.setContentType("text/csv; charset=utf-8");
201 response.setHeader("Content-Disposition", "attachment; filename=\""+config.getClassificationTitleCache()+".txt\"");
202 PrintWriter printWriter = response.getWriter();
203
204 int i;
205 while((i = isr.read())!= -1){
206 printWriter.write(i);
207 }
208 byteArrayOutputStream.flush();
209 isr.close();
210 byteArrayOutputStream.close();
211 printWriter.flush();
212 printWriter.close();
213 } catch (Exception e) {
214 logger.error("error generating feed", e);
215 }
216 }
217
218 /**
219 * Cofiguration method to set the configuration details for the defaultExport in the application context.
220 *
221 * @param classificationUUID pass-through the selected {@link Classification classification}
222 * @param featureUuids pass-through the selected {@link Feature feature} of a {@link Taxon}, in order to fetch it.
223 * @param areas
224 * @param byteArrayOutputStream pass-through the stream to write out the data later.
225 * @return the CsvTaxExportConfiguratorRedlist config
226 */
227 private CsvDemoExportConfigurator setTaxExportConfigurator(String classificationUUID, UuidList featureUuids, UuidList areas, ByteArrayOutputStream byteArrayOutputStream) {
228
229 @SuppressWarnings({ "unchecked", "rawtypes" })
230 Set<UUID> classificationUUIDS = new HashSet
231 (Arrays.asList(new UUID[] {UUID.fromString(classificationUUID)}));
232 String destination = System.getProperty("java.io.tmpdir");
233 List<Feature> features = new ArrayList<Feature>();
234 if(featureUuids != null){
235 for(UUID uuid : featureUuids) {
236 features.add((Feature) termService.find(uuid));
237 }
238 }
239 List<NamedArea> selectedAreas = new ArrayList<NamedArea>();
240 if(areas != null){
241 for(UUID area:areas){
242 logger.info(area);
243 selectedAreas.add((NamedArea)termService.find(area));
244 }
245 }
246
247 CsvDemoExportConfigurator config = CsvDemoExportConfigurator.NewInstance(null, new File(destination));
248 config.setHasHeaderLines(true);
249 config.setFieldsTerminatedBy("\t");
250 config.setClassificationUuids(classificationUUIDS);
251 config.setByteArrayOutputStream(byteArrayOutputStream);
252 config.createPreSelectedExport(false, true);
253 if(features != null) {
254 config.setFeatures(features);
255 }
256 config.setNamedAreas(selectedAreas);
257 return config;
258 }
259
260 /* (non-Javadoc)
261 * @see eu.etaxonomy.cdm.remote.controller.AbstractController#setService(eu.etaxonomy.cdm.api.service.IService)
262 */
263 @Override
264 public void setService(IService service) {
265 // TODO Auto-generated method stub
266
267 }
268
269 /* (non-Javadoc)
270 * @see org.springframework.context.ResourceLoaderAware#setResourceLoader(org.springframework.core.io.ResourceLoader)
271 */
272 @Override
273 public void setResourceLoader(ResourceLoader resourceLoader) {
274 this.resourceLoader = resourceLoader;
275 }
276
277 }