Project

General

Profile

« Previous | Next » 

Revision c4e0c8dd

Added by Patrick Plitzner over 7 years ago

name

View differences:

cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/controller/checklist/CsvExportController.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.InputStreamReader;
15
import java.io.PrintWriter;
16
import java.util.ArrayList;
17
import java.util.Arrays;
18
import java.util.Collections;
19
import java.util.List;
20
import java.util.Set;
21
import java.util.UUID;
22

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

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

  
38
import eu.etaxonomy.cdm.api.service.IClassificationService;
39
import eu.etaxonomy.cdm.api.service.IService;
40
import eu.etaxonomy.cdm.api.service.ITaxonNodeService;
41
import eu.etaxonomy.cdm.api.service.ITaxonService;
42
import eu.etaxonomy.cdm.api.service.ITermService;
43
import eu.etaxonomy.cdm.common.CdmUtils;
44
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
45
import eu.etaxonomy.cdm.io.common.CdmApplicationAwareDefaultExport;
46
import eu.etaxonomy.cdm.io.csv.redlist.out.CsvTaxExportConfiguratorRedlist;
47
import eu.etaxonomy.cdm.model.description.Feature;
48
import eu.etaxonomy.cdm.model.location.NamedArea;
49
import eu.etaxonomy.cdm.model.taxon.Classification;
50
import eu.etaxonomy.cdm.model.taxon.Taxon;
51
import eu.etaxonomy.cdm.remote.controller.AbstractController;
52
import eu.etaxonomy.cdm.remote.controller.ProgressMonitorController;
53
import eu.etaxonomy.cdm.remote.editor.UUIDListPropertyEditor;
54
import eu.etaxonomy.cdm.remote.editor.UuidList;
55

  
56
/**
57
 * @author a.oppermann
58
 * @created 20.09.2012
59
 * 
60
 */
61
@Controller
62
@RequestMapping(value = { "/csv" })
63
public class CsvExportController extends AbstractController{
64

  
65
	/**
66
	 * 
67
	 */
68
	@Autowired
69
	private ApplicationContext appContext;
70
	
71
	@Autowired 
72
	private ITermService termService;
73

  
74
	@Autowired 
75
	private IClassificationService classificationService;
76

  
77
	@Autowired 
78
	private ITaxonNodeService taxonNodeService;
79

  
80
	@Autowired 
81
	private ITaxonService taxonService;
82
	
83
	@Autowired
84
	public ProgressMonitorController progressMonitorController;
85
	
86
	private static final Logger logger = Logger.getLogger(CsvExportController.class);
87
	
88
	/**
89
	 * Helper method, which allows to convert strings directly into uuids.
90
	 * 
91
	 * @param binder Special DataBinder for data binding from web request parameters to JavaBean objects.
92
	 */
93
    @InitBinder
94
    public void initBinder(WebDataBinder binder) {
95
        binder.registerCustomEditor(UuidList.class, new UUIDListPropertyEditor());
96
//        binder.registerCustomEditor(NamedArea.class, new NamedAreaPropertyEditor());
97
        binder.registerCustomEditor(UUID.class, new UUIDEditor());
98
    }
99

  
100
    /**
101
     * Fetches data from the application context and forwards the stream to the HttpServletResponse, which offers a file download.
102
     *
103
     * @param featureUuids List of uuids to download/select {@link Feature feature}features
104
     * @param taxonUuid Selected {@link Classification classification} to iterate the {@link Taxon}
105
     * @param response HttpServletResponse which returns the ByteArrayOutputStream
106
     */
107
	@RequestMapping(value = { "exportRedlist" }, method = { RequestMethod.POST })
108
	public void doExportRedlist(
109
			@RequestParam(value = "features", required = false) UuidList featureUuids,
110
			@RequestParam(value = "classificationUuid", required = false) String classificationUuid,
111
			@RequestParam(value = "taxonUuid", required = false) String taxonUuid,
112
            @RequestParam(value = "area", required = false) UuidList areas,
113
			@RequestParam(value = "downloadTokenValueId", required = false) String downloadTokenValueId,
114
			HttpServletResponse response,
115
			HttpServletRequest request) {
116
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
117
		UUID taxonNodeUuid = null;
118
		Classification classification = classificationService.load(UUID.fromString(classificationUuid));
119
		if(CdmUtils.isNotBlank(taxonUuid)){
120
			Taxon taxon = HibernateProxyHelper.deproxy(taxonService.load(UUID.fromString(taxonUuid), Arrays.asList(new String[]{"taxonNodes.classification"})), Taxon.class);
121
			taxonNodeUuid = classification.getNode(taxon).getUuid();
122
		}
123
		else{
124
			taxonNodeUuid = classification.getRootNode().getUuid();
125
		}
126
		CsvTaxExportConfiguratorRedlist config = setTaxExportConfigurator(taxonNodeUuid, featureUuids, areas, byteArrayOutputStream);
127
		CdmApplicationAwareDefaultExport<?> defaultExport = (CdmApplicationAwareDefaultExport<?>) appContext.getBean("defaultExport");
128
		logger.info("Start export...");
129
		logger.info("doExportRedlist()" + requestPathAndQuery(request));
130
		defaultExport.invoke(config);
131
		try {
132
			/*
133
			 *  Fetch data from the appContext and forward stream to HttpServleResponse
134
			 *  
135
			 *  FIXME: Large Data could be out of memory
136
			 *  
137
			 *  HTPP Error Break
138
			 */
139
			ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());//byteArrayOutputStream.toByteArray()
140
			InputStreamReader isr = new InputStreamReader(bais);
141
			Cookie progressCookie = new Cookie("fileDownloadToken", downloadTokenValueId);
142
			progressCookie.setPath("/");
143
			progressCookie.setMaxAge(60);
144
			response.addCookie(progressCookie);
145
			response.setContentType("text/csv; charset=utf-8");
146
			response.setHeader("Content-Disposition", "attachment; filename=\""+config.getClassificationTitleCache()+".txt\"");
147
			PrintWriter printWriter = response.getWriter();
148

  
149
			int i;
150
			while((i = isr.read())!= -1){
151
				printWriter.write(i);
152
			}
153
			byteArrayOutputStream.flush();
154
			isr.close();
155
			byteArrayOutputStream.close();
156
			printWriter.flush();
157
			printWriter.close();
158
		} catch (Exception e) {
159
			logger.error("error generating feed", e);
160
		}
161
	}
162

  
163
	/**
164
	 * Cofiguration method to set the configuration details for the defaultExport in the application context.
165
	 * 
166
	 * @param taxonNodeUuid pass-through the selected {@link Classification classification}
167
	 * @param featureUuids pass-through the selected {@link Feature feature} of a {@link Taxon}, in order to fetch it.
168
	 * @param areas 
169
	 * @param byteArrayOutputStream pass-through the stream to write out the data later.
170
	 * @return the CsvTaxExportConfiguratorRedlist config
171
	 */
172
	private CsvTaxExportConfiguratorRedlist setTaxExportConfigurator(UUID taxonNodeUuid, UuidList featureUuids, UuidList areas, ByteArrayOutputStream byteArrayOutputStream) {
173

  
174
		@SuppressWarnings({ "unchecked", "rawtypes" })
175
		Set<UUID> taxonNodeUuids = Collections.singleton(taxonNodeUuid); 
176
		String destination = System.getProperty("java.io.tmpdir");
177
		List<Feature> features = new ArrayList<Feature>();
178
		if(featureUuids != null){
179
			for(UUID uuid : featureUuids) {
180
				features.add((Feature) termService.find(uuid));
181
			}
182
		}
183
		List<NamedArea> selectedAreas = new ArrayList<NamedArea>();
184
		if(areas != null){
185
			for(UUID area:areas){
186
				logger.info(area);
187
				selectedAreas.add((NamedArea)termService.find(area));
188
			}
189
		}
190

  
191
		CsvTaxExportConfiguratorRedlist config = CsvTaxExportConfiguratorRedlist.NewInstance(null, new File(destination));
192
		config.setHasHeaderLines(true);
193
		config.setFieldsTerminatedBy("\t");
194
		config.setTaxonNodeUuids(taxonNodeUuids);
195
		config.setByteArrayOutputStream(byteArrayOutputStream);
196
		if(features != null)config.setFeatures(features);
197
        config.setNamedAreas(selectedAreas);
198
		return config;
199
	}
200
	
201
	/* (non-Javadoc)
202
	 * @see eu.etaxonomy.cdm.remote.controller.AbstractController#setService(eu.etaxonomy.cdm.api.service.IService)
203
	 */
204
	@Override
205
	public void setService(IService service) {
206
		// TODO Auto-generated method stub
207
		
208
	}
209
	
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.Arrays;
18
import java.util.Collections;
19
import java.util.List;
20
import java.util.Set;
21
import java.util.UUID;
22

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

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

  
38
import eu.etaxonomy.cdm.api.service.IClassificationService;
39
import eu.etaxonomy.cdm.api.service.IService;
40
import eu.etaxonomy.cdm.api.service.ITaxonNodeService;
41
import eu.etaxonomy.cdm.api.service.ITaxonService;
42
import eu.etaxonomy.cdm.api.service.ITermService;
43
import eu.etaxonomy.cdm.api.service.config.MatchingTaxonConfigurator;
44
import eu.etaxonomy.cdm.common.CdmUtils;
45
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
46
import eu.etaxonomy.cdm.io.common.CdmApplicationAwareDefaultExport;
47
import eu.etaxonomy.cdm.io.csv.redlist.out.CsvTaxExportConfiguratorRedlist;
48
import eu.etaxonomy.cdm.model.description.Feature;
49
import eu.etaxonomy.cdm.model.location.NamedArea;
50
import eu.etaxonomy.cdm.model.taxon.Classification;
51
import eu.etaxonomy.cdm.model.taxon.Taxon;
52
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
53
import eu.etaxonomy.cdm.remote.controller.AbstractController;
54
import eu.etaxonomy.cdm.remote.controller.ProgressMonitorController;
55
import eu.etaxonomy.cdm.remote.editor.UUIDListPropertyEditor;
56
import eu.etaxonomy.cdm.remote.editor.UuidList;
57

  
58
/**
59
 * @author a.oppermann
60
 * @created 20.09.2012
61
 * 
62
 */
63
@Controller
64
@RequestMapping(value = { "/csv" })
65
public class CsvExportController extends AbstractController{
66

  
67
	/**
68
	 * 
69
	 */
70
	@Autowired
71
	private ApplicationContext appContext;
72
	
73
	@Autowired 
74
	private ITermService termService;
75

  
76
	@Autowired 
77
	private IClassificationService classificationService;
78

  
79
	@Autowired 
80
	private ITaxonNodeService taxonNodeService;
81

  
82
	@Autowired 
83
	private ITaxonService taxonService;
84
	
85
	@Autowired
86
	public ProgressMonitorController progressMonitorController;
87
	
88
	private static final Logger logger = Logger.getLogger(CsvExportController.class);
89
	
90
	/**
91
	 * Helper method, which allows to convert strings directly into uuids.
92
	 * 
93
	 * @param binder Special DataBinder for data binding from web request parameters to JavaBean objects.
94
	 */
95
    @InitBinder
96
    public void initBinder(WebDataBinder binder) {
97
        binder.registerCustomEditor(UuidList.class, new UUIDListPropertyEditor());
98
//        binder.registerCustomEditor(NamedArea.class, new NamedAreaPropertyEditor());
99
        binder.registerCustomEditor(UUID.class, new UUIDEditor());
100
    }
101

  
102
    /**
103
     * Fetches data from the application context and forwards the stream to the HttpServletResponse, which offers a file download.
104
     *
105
     * @param featureUuids List of uuids to download/select {@link Feature feature}features
106
     * @param taxonName the selected taxon name
107
     * @param classificationUuid the uuid of the selected classification
108
     * @param response HttpServletResponse which returns the ByteArrayOutputStream
109
     */
110
	@RequestMapping(value = { "exportRedlist" }, method = { RequestMethod.POST })
111
	public void doExportRedlist(
112
			@RequestParam(value = "features", required = false) UuidList featureUuids,
113
			@RequestParam(value = "classificationUuid", required = false) String classificationUuid,
114
			@RequestParam(value = "taxonName", required = false) String taxonName,
115
            @RequestParam(value = "area", required = false) UuidList areas,
116
			@RequestParam(value = "downloadTokenValueId", required = false) String downloadTokenValueId,
117
			HttpServletResponse response,
118
			HttpServletRequest request) {
119
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
120
		UUID taxonNodeUuid = null;
121
		Classification classification = classificationService.load(UUID.fromString(classificationUuid));
122
		if(CdmUtils.isNotBlank(taxonName)){
123
			MatchingTaxonConfigurator config = new MatchingTaxonConfigurator();
124
			config.setClassificationUuid(UUID.fromString(classificationUuid));
125
			config.setTaxonNameTitle(taxonName);
126
			List<TaxonBase> taxaByName = taxonService.findTaxaByName(config);
127
			if(taxaByName.isEmpty()){
128
				logger.warn("No taxon found with name: "+taxonName+". Using only classification.");
129
			}
130
			else if(taxaByName.size()>1){
131
				logger.warn("More than one taxon found for name: "+taxonName+". Using the first insance.");
132
			}
133
			else{
134
				UUID uuid = taxaByName.iterator().next().getUuid();
135
				Taxon taxon = HibernateProxyHelper.deproxy(taxonService.load(uuid, Arrays.asList(new String[]{"taxonNodes.classification"})), Taxon.class);
136
				taxonNodeUuid = classification.getNode(taxon).getUuid();
137
			}
138
		}
139
		else{
140
			taxonNodeUuid = classification.getRootNode().getUuid();
141
		}
142
		CsvTaxExportConfiguratorRedlist config = setTaxExportConfigurator(taxonNodeUuid, featureUuids, areas, byteArrayOutputStream);
143
		CdmApplicationAwareDefaultExport<?> defaultExport = (CdmApplicationAwareDefaultExport<?>) appContext.getBean("defaultExport");
144
		logger.info("Start export...");
145
		logger.info("doExportRedlist()" + requestPathAndQuery(request));
146
		defaultExport.invoke(config);
147
		try {
148
			/*
149
			 *  Fetch data from the appContext and forward stream to HttpServleResponse
150
			 *  
151
			 *  FIXME: Large Data could be out of memory
152
			 *  
153
			 *  HTPP Error Break
154
			 */
155
			ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());//byteArrayOutputStream.toByteArray()
156
			InputStreamReader isr = new InputStreamReader(bais);
157
			Cookie progressCookie = new Cookie("fileDownloadToken", downloadTokenValueId);
158
			progressCookie.setPath("/");
159
			progressCookie.setMaxAge(60);
160
			response.addCookie(progressCookie);
161
			response.setContentType("text/csv; charset=utf-8");
162
			response.setHeader("Content-Disposition", "attachment; filename=\""+config.getClassificationTitleCache()+".txt\"");
163
			PrintWriter printWriter = response.getWriter();
164

  
165
			int i;
166
			while((i = isr.read())!= -1){
167
				printWriter.write(i);
168
			}
169
			byteArrayOutputStream.flush();
170
			isr.close();
171
			byteArrayOutputStream.close();
172
			printWriter.flush();
173
			printWriter.close();
174
		} catch (Exception e) {
175
			logger.error("error generating feed", e);
176
		}
177
	}
178

  
179
	/**
180
	 * Cofiguration method to set the configuration details for the defaultExport in the application context.
181
	 * 
182
	 * @param taxonNodeUuid pass-through the selected {@link Classification classification}
183
	 * @param featureUuids pass-through the selected {@link Feature feature} of a {@link Taxon}, in order to fetch it.
184
	 * @param areas 
185
	 * @param byteArrayOutputStream pass-through the stream to write out the data later.
186
	 * @return the CsvTaxExportConfiguratorRedlist config
187
	 */
188
	private CsvTaxExportConfiguratorRedlist setTaxExportConfigurator(UUID taxonNodeUuid, UuidList featureUuids, UuidList areas, ByteArrayOutputStream byteArrayOutputStream) {
189

  
190
		@SuppressWarnings({ "unchecked", "rawtypes" })
191
		Set<UUID> taxonNodeUuids = Collections.singleton(taxonNodeUuid); 
192
		String destination = System.getProperty("java.io.tmpdir");
193
		List<Feature> features = new ArrayList<Feature>();
194
		if(featureUuids != null){
195
			for(UUID uuid : featureUuids) {
196
				features.add((Feature) termService.find(uuid));
197
			}
198
		}
199
		List<NamedArea> selectedAreas = new ArrayList<NamedArea>();
200
		if(areas != null){
201
			for(UUID area:areas){
202
				logger.info(area);
203
				selectedAreas.add((NamedArea)termService.find(area));
204
			}
205
		}
206

  
207
		CsvTaxExportConfiguratorRedlist config = CsvTaxExportConfiguratorRedlist.NewInstance(null, new File(destination));
208
		config.setHasHeaderLines(true);
209
		config.setFieldsTerminatedBy("\t");
210
		config.setTaxonNodeUuids(taxonNodeUuids);
211
		config.setByteArrayOutputStream(byteArrayOutputStream);
212
		if(features != null)config.setFeatures(features);
213
        config.setNamedAreas(selectedAreas);
214
		return config;
215
	}
216
	
217
	/* (non-Javadoc)
218
	 * @see eu.etaxonomy.cdm.remote.controller.AbstractController#setService(eu.etaxonomy.cdm.api.service.IService)
219
	 */
220
	@Override
221
	public void setService(IService service) {
222
		// TODO Auto-generated method stub
223
		
224
	}
225
	
210 226
}

Also available in: Unified diff