Project

General

Profile

Download (7.28 KB) Statistics
| Branch: | Tag: | Revision:
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.InputStreamReader;
15
import java.io.PrintWriter;
16
import java.util.ArrayList;
17
import java.util.Collections;
18
import java.util.List;
19
import java.util.Set;
20
import java.util.UUID;
21

    
22
import javax.servlet.http.Cookie;
23
import javax.servlet.http.HttpServletRequest;
24
import javax.servlet.http.HttpServletResponse;
25

    
26
import org.apache.log4j.Logger;
27
import org.springframework.beans.factory.annotation.Autowired;
28
import org.springframework.beans.propertyeditors.UUIDEditor;
29
import org.springframework.context.ApplicationContext;
30
import org.springframework.stereotype.Controller;
31
import org.springframework.web.bind.WebDataBinder;
32
import org.springframework.web.bind.annotation.InitBinder;
33
import org.springframework.web.bind.annotation.RequestMapping;
34
import org.springframework.web.bind.annotation.RequestMethod;
35
import org.springframework.web.bind.annotation.RequestParam;
36

    
37
import eu.etaxonomy.cdm.api.service.IService;
38
import eu.etaxonomy.cdm.api.service.ITermService;
39
import eu.etaxonomy.cdm.io.common.CdmApplicationAwareDefaultExport;
40
import eu.etaxonomy.cdm.io.csv.redlist.out.CsvTaxExportConfiguratorRedlist;
41
import eu.etaxonomy.cdm.model.description.Feature;
42
import eu.etaxonomy.cdm.model.location.NamedArea;
43
import eu.etaxonomy.cdm.model.taxon.Classification;
44
import eu.etaxonomy.cdm.model.taxon.Taxon;
45
import eu.etaxonomy.cdm.remote.controller.AbstractController;
46
import eu.etaxonomy.cdm.remote.controller.ProgressMonitorController;
47
import eu.etaxonomy.cdm.remote.editor.UUIDListPropertyEditor;
48
import eu.etaxonomy.cdm.remote.editor.UuidList;
49

    
50
/**
51
 * @author a.oppermann
52
 * @created 20.09.2012
53
 * 
54
 */
55
@Controller
56
@RequestMapping(value = { "/csv" })
57
public class CsvExportController extends AbstractController{
58

    
59
	/**
60
	 * 
61
	 */
62
	@Autowired
63
	private ApplicationContext appContext;
64
	
65
	@Autowired 
66
	private ITermService termService;
67
	
68
	@Autowired
69
	public ProgressMonitorController progressMonitorController;
70
	
71
	private static final Logger logger = Logger.getLogger(CsvExportController.class);
72
	
73
	/**
74
	 * Helper method, which allows to convert strings directly into uuids.
75
	 * 
76
	 * @param binder Special DataBinder for data binding from web request parameters to JavaBean objects.
77
	 */
78
    @InitBinder
79
    public void initBinder(WebDataBinder binder) {
80
        binder.registerCustomEditor(UuidList.class, new UUIDListPropertyEditor());
81
//        binder.registerCustomEditor(NamedArea.class, new NamedAreaPropertyEditor());
82
        binder.registerCustomEditor(UUID.class, new UUIDEditor());
83
    }
84

    
85
    /**
86
     * Fetches data from the application context and forwards the stream to the HttpServletResponse, which offers a file download.
87
     *
88
     * @param featureUuids List of uuids to download/select {@link Feature feature}features
89
     * @param taxonNodeUuid Selected {@link Classification classification} to iterate the {@link Taxon}
90
     * @param response HttpServletResponse which returns the ByteArrayOutputStream
91
     */
92
	@RequestMapping(value = { "exportRedlist" }, method = { RequestMethod.POST })
93
	public void doExportRedlist(
94
			@RequestParam(value = "features", required = false) UuidList featureUuids,
95
			@RequestParam(value = "taxonNode", required = false) String taxonNodeUuid,
96
            @RequestParam(value = "area", required = false) UuidList areas,
97
			@RequestParam(value = "downloadTokenValueId", required = false) String downloadTokenValueId,
98
			HttpServletResponse response,
99
			HttpServletRequest request) {
100
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
101
		CsvTaxExportConfiguratorRedlist config = setTaxExportConfigurator(taxonNodeUuid, featureUuids, areas, byteArrayOutputStream);
102
		CdmApplicationAwareDefaultExport<?> defaultExport = (CdmApplicationAwareDefaultExport<?>) appContext.getBean("defaultExport");
103
		logger.info("Start export...");
104
		logger.info("doExportRedlist()" + requestPathAndQuery(request));
105
		defaultExport.invoke(config);
106
		try {
107
			/*
108
			 *  Fetch data from the appContext and forward stream to HttpServleResponse
109
			 *  
110
			 *  FIXME: Large Data could be out of memory
111
			 *  
112
			 *  HTPP Error Break
113
			 */
114
			ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());//byteArrayOutputStream.toByteArray()
115
			InputStreamReader isr = new InputStreamReader(bais);
116
			Cookie progressCookie = new Cookie("fileDownloadToken", downloadTokenValueId);
117
			progressCookie.setPath("/");
118
			progressCookie.setMaxAge(60);
119
			response.addCookie(progressCookie);
120
			response.setContentType("text/csv; charset=utf-8");
121
			response.setHeader("Content-Disposition", "attachment; filename=\""+config.getClassificationTitleCache()+".txt\"");
122
			PrintWriter printWriter = response.getWriter();
123

    
124
			int i;
125
			while((i = isr.read())!= -1){
126
				printWriter.write(i);
127
			}
128
			byteArrayOutputStream.flush();
129
			isr.close();
130
			byteArrayOutputStream.close();
131
			printWriter.flush();
132
			printWriter.close();
133
		} catch (Exception e) {
134
			logger.error("error generating feed", e);
135
		}
136
	}
137

    
138
	/**
139
	 * Cofiguration method to set the configuration details for the defaultExport in the application context.
140
	 * 
141
	 * @param taxonNodeUuid pass-through the selected {@link Classification classification}
142
	 * @param featureUuids pass-through the selected {@link Feature feature} of a {@link Taxon}, in order to fetch it.
143
	 * @param areas 
144
	 * @param byteArrayOutputStream pass-through the stream to write out the data later.
145
	 * @return the CsvTaxExportConfiguratorRedlist config
146
	 */
147
	private CsvTaxExportConfiguratorRedlist setTaxExportConfigurator(String taxonNodeUuid, UuidList featureUuids, UuidList areas, ByteArrayOutputStream byteArrayOutputStream) {
148

    
149
		@SuppressWarnings({ "unchecked", "rawtypes" })
150
		Set<UUID> taxonNodeUuids = Collections.singleton(UUID.fromString(taxonNodeUuid)); 
151
		String destination = System.getProperty("java.io.tmpdir");
152
		List<Feature> features = new ArrayList<Feature>();
153
		if(featureUuids != null){
154
			for(UUID uuid : featureUuids) {
155
				features.add((Feature) termService.find(uuid));
156
			}
157
		}
158
		List<NamedArea> selectedAreas = new ArrayList<NamedArea>();
159
		if(areas != null){
160
			for(UUID area:areas){
161
				logger.info(area);
162
				selectedAreas.add((NamedArea)termService.find(area));
163
			}
164
		}
165

    
166
		CsvTaxExportConfiguratorRedlist config = CsvTaxExportConfiguratorRedlist.NewInstance(null, new File(destination));
167
		config.setHasHeaderLines(true);
168
		config.setFieldsTerminatedBy("\t");
169
		config.setTaxonNodeUuids(taxonNodeUuids);
170
		config.setByteArrayOutputStream(byteArrayOutputStream);
171
		if(features != null)config.setFeatures(features);
172
        config.setNamedAreas(selectedAreas);
173
		return config;
174
	}
175
	
176
	/* (non-Javadoc)
177
	 * @see eu.etaxonomy.cdm.remote.controller.AbstractController#setService(eu.etaxonomy.cdm.api.service.IService)
178
	 */
179
	@Override
180
	public void setService(IService service) {
181
		// TODO Auto-generated method stub
182
		
183
	}
184
	
185
}
(2-2/2)