Project

General

Profile

1
package eu.dnetlib.openaire.exporter;
2

    
3
import java.io.IOException;
4
import java.io.OutputStream;
5
import java.io.StringReader;
6
import java.text.SimpleDateFormat;
7
import java.util.Date;
8
import java.util.List;
9
import java.util.Map;
10

    
11
import javax.servlet.ServletOutputStream;
12
import javax.servlet.ServletResponse;
13
import javax.servlet.http.HttpServletRequest;
14
import javax.servlet.http.HttpServletResponse;
15
import javax.xml.ws.wsaddressing.W3CEndpointReference;
16

    
17
import org.antlr.stringtemplate.StringTemplate;
18
import org.apache.commons.io.IOUtils;
19
import org.apache.commons.lang.StringUtils;
20
import org.apache.commons.logging.Log;
21
import org.apache.commons.logging.LogFactory;
22
import org.dom4j.Document;
23
import org.dom4j.io.SAXReader;
24
import org.springframework.beans.factory.annotation.Autowired;
25
import org.springframework.beans.factory.annotation.Value;
26
import org.springframework.core.io.Resource;
27
import org.springframework.stereotype.Controller;
28
import org.springframework.web.bind.annotation.RequestMapping;
29
import org.springframework.web.bind.annotation.RequestParam;
30

    
31
import com.google.common.base.Joiner;
32
import com.google.common.base.Splitter;
33
import com.google.common.collect.Lists;
34
import com.google.common.collect.Maps;
35

    
36
import eu.dnetlib.enabling.database.rmi.DatabaseService;
37
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
38
import eu.dnetlib.enabling.resultset.client.IterableResultSetClient;
39
import eu.dnetlib.enabling.resultset.client.ResultSetClientFactory;
40
import eu.dnetlib.miscutils.collections.MappedCollection;
41
import eu.dnetlib.miscutils.functional.xml.ApplyXslt;
42

    
43
@Controller
44
public class ProjectsController {
45

    
46
	private enum Funding {
47
		FP7, WT, FCT, H2020, NHMRC, ARC
48
	}
49

    
50
	@javax.annotation.Resource
51
	private UniqueServiceLocator serviceLocator;
52

    
53
	@Value("${dnet.openaire.db.name}")
54
	private String dbName;
55
	@Value("${openaire.exporter.dspace.xslt}")
56
	private Resource dspaceXslt;
57
	@Value("${openaire.exporter.eprints.xslt}")
58
	private Resource eprintsXslt;
59
	@Value("${openaire.exporter.projectsfundings.sql.template}")
60
	private Resource projectsFundingQueryTemplate;
61
	@Value("${openaire.exporter.projects2tsv.sql.template}")
62
	private Resource projects2tsvQueryTemplate;
63
	@Value("${openaire.exporter.projects2tsv.fields}")
64
	private String tsvFields;
65

    
66
	@Autowired
67
	private ResultSetClientFactory resultSetClientFactory;
68
	@Autowired
69
	private ProjectQueryParamsFactory projectQueryParamsFactory;
70

    
71
	private static final Log log = LogFactory.getLog(ProjectsController.class); // NOPMD by marko on 11/24/08 5:02 PM
72

    
73
	@RequestMapping(value = "/openaire/export/**/project/dspace.do")
74
	void processDspace(final HttpServletRequest request,
75
			final ServletResponse response,
76
			@RequestParam(value = "startFrom", required = false) final String startFrom,
77
			@RequestParam(value = "startUntil", required = false) final String startUntil,
78
			@RequestParam(value = "endFrom", required = false) final String endFrom,
79
			@RequestParam(value = "endUntil", required = false) final String endUntil) throws Exception {
80

    
81
		response.setContentType("text/xml");
82

    
83
		ProjectQueryParams params = projectQueryParamsFactory.generateParams(request, startFrom, startUntil, endFrom, endUntil);
84

    
85
		ServletOutputStream out = response.getOutputStream();
86

    
87
		String head = "<?xml version='1.0' encoding='UTF-8'?>\n\n" + "<form-value-pairs>\n" + "	<value-pairs value-pairs-name='" + params.getFundingProgramme()
88
				+ "projects' dc-term='relation'>\n";
89

    
90
		String tail = "	</value-pairs>\n" + "</form-value-pairs>\n";
91

    
92
		IOUtils.copy(new StringReader(head), out);
93
		emit(out, dspaceXslt, obtainQuery(params));
94
		IOUtils.copy(new StringReader(tail), out);
95
	}
96

    
97
	@RequestMapping(value = "/openaire/export/**/project/eprints.do")
98
	void processEprints(final HttpServletRequest request,
99
			final ServletResponse response,
100
			@RequestParam(value = "startFrom", required = false) final String startFrom,
101
			@RequestParam(value = "startUntil", required = false) final String startUntil,
102
			@RequestParam(value = "endFrom", required = false) final String endFrom,
103
			@RequestParam(value = "endUntil", required = false) final String endUntil) throws Exception {
104

    
105
		response.setContentType("text/html");
106
		emit(response.getOutputStream(), eprintsXslt, obtainQuery(projectQueryParamsFactory.generateParams(request, startFrom, startUntil, endFrom, endUntil)));
107
	}
108

    
109
	@RequestMapping(value = "/openaire/export/project2tsv.do")
110
	void processTsv(final HttpServletRequest request, final HttpServletResponse response,
111
			@RequestParam(value = "funding", required = true) final String funding,
112
			@RequestParam(value = "article293", required = false) final Boolean article293) throws Exception {
113

    
114
		final String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
115
		response.setContentType("text/tab-separated-values");
116
		response.setHeader("Content-Disposition", "attachment; filename=\"projects_" + funding + "_" + date + ".tsv\"");
117

    
118
		final StringTemplate st = new StringTemplate(IOUtils.toString(projects2tsvQueryTemplate.getInputStream()));
119
		Funding requestedFunding = Funding.valueOf(funding.toUpperCase());
120
		String fundingPrefix = getFundingPrefix(requestedFunding, null);
121
		log.debug("Setting fundingprefix to " + fundingPrefix);
122
		st.setAttribute("fundingprefix", fundingPrefix);
123
		st.setAttribute("filters", expandFilters(article293));
124
		emitAsTsv(response.getOutputStream(), st.toString());
125
	}
126

    
127
	private Map<String, String> expandFilters(final Boolean article293) {
128
		final Map<String, String> res = Maps.newHashMap();
129

    
130
		if (article293 != null) {
131
			res.put("pr.ec_article29_3", String.valueOf(article293));
132
		}
133

    
134
		return res;
135
	}
136

    
137
	/**
138
	 * Creates the query on the fundingProgramme specified in the given parameters.
139
	 *
140
	 * @param params
141
	 *            request parameters
142
	 * @return the query string
143
	 * @throws IllegalArgumentException
144
	 *             if the funding program is not recognized
145
	 * @throws IOException
146
	 *             if there are problem loading the query temlate
147
	 * @throws IllegalArgumentException
148
	 *             if the funding program is not recognized
149
	 */
150
	protected String obtainQuery(final ProjectQueryParams params) throws IllegalArgumentException, IOException {
151
		String funding = params.getFundingProgramme();
152
		String suffix = params.getFundingPath();
153
		String fundingPrefix = getFundingPrefix(Funding.valueOf(funding.toUpperCase()), suffix);
154
		final StringTemplate st = new StringTemplate(IOUtils.toString(projectsFundingQueryTemplate.getInputStream()));
155
		st.setAttribute("fundingprefix", fundingPrefix);
156
		String theQuery = setDateParameters(st.toString(), params);
157
		log.debug("Generated query: " + theQuery);
158
		return theQuery;
159
	}
160

    
161
	private String getFundingPrefix(final Funding funding, final String suffix) throws IllegalArgumentException {
162
		switch (funding) {
163
		case FCT:
164
			if (StringUtils.isBlank(suffix)) return "fct_________::FCT::";
165
			else return "fct_________::FCT::" + suffix;
166
		case WT:
167
			if (StringUtils.isBlank(suffix)) return "wt__________::WT::";
168
			else return "wt__________::WT::" + suffix;
169
		case FP7:
170
			if (StringUtils.isBlank(suffix)) return "ec__________::EC::FP7::";
171
			else return "ec__________::EC::FP7::" + suffix;
172
		case H2020:
173
			if (StringUtils.isBlank(suffix)) return "ec__________::EC::H2020";
174
			else return "ec__________::EC::H2020" + suffix;
175
		case NHMRC:
176
			if (StringUtils.isBlank(suffix)) return "nhmrc_______::NHMRC::";
177
			else return "nhmrc_______::NHMRC::" + suffix;
178
		case ARC:
179
			if (StringUtils.isBlank(suffix)) return "arc_________::ARC::";
180
			else return "arc_________::ARC::" + suffix;
181
		default:
182
			throw new IllegalArgumentException("Invalid funding " + funding + " (valid are: FP7, H2020, WT, FCT, NHMRC, ARC)");
183
		}
184
	}
185

    
186
	void emit(final OutputStream out, final Resource xslt, final String query) throws IOException {
187
		W3CEndpointReference epr = serviceLocator.getService(DatabaseService.class).searchSQL(dbName, query);
188

    
189
		IterableResultSetClient iter = resultSetClientFactory.getClient(epr);
190

    
191
		for (String s : new MappedCollection<String, String>(iter, new ApplyXslt(xslt))) {
192
			out.write(s.getBytes());
193
		}
194
	}
195

    
196
	void emitAsTsv(final OutputStream out, final String query) throws Exception {
197
		W3CEndpointReference epr = serviceLocator.getService(DatabaseService.class).searchSQL(dbName, query);
198

    
199
		final List<String> fields = Lists.newArrayList(Splitter.on(",").omitEmptyStrings().trimResults().split(tsvFields));
200
		writeCSVLine(out, fields);
201

    
202
		final SAXReader reader = new SAXReader();
203
		for (String s : resultSetClientFactory.getClient(epr)) {
204
			final Document doc = reader.read(new StringReader(s));
205
			final List<String> list = Lists.newArrayList();
206
			for (String f : fields) {
207
				list.add(doc.valueOf("//FIELD[@name='" + f + "']").replaceAll("\\n|\\t", " ").replaceAll("\\s+", " ").trim());
208
			}
209
			writeCSVLine(out, list);
210
		}
211
		out.flush();
212
	}
213

    
214
	private void writeCSVLine(final OutputStream out, final List<String> list) throws Exception {
215
		out.write(Joiner.on('\t').useForNull("").join(list).getBytes());
216
		out.write('\n');
217
	}
218

    
219
	private String setDateParameters(final String query, final ProjectQueryParams params) {
220
		String queryWithDates = query;
221
		if (params.getStartFrom() != null) {
222
			queryWithDates += " AND p.startdate >= '" + params.getStartFrom() + "'";
223
		}
224
		if (params.getStartUntil() != null) {
225
			queryWithDates += " AND p.startdate <= '" + params.getStartUntil() + "'";
226
		}
227
		if (params.getEndFrom() != null) {
228
			queryWithDates += " AND p.enddate >= '" + params.getEndFrom() + "'";
229
		}
230
		if (params.getEndUntil() != null) {
231
			queryWithDates += " AND p.enddate <= '" + params.getEndUntil() + "'";
232
		}
233
		return queryWithDates;
234
	}
235

    
236
	public String getDbName() {
237
		return dbName;
238
	}
239

    
240
	public void setDbName(final String dbName) {
241
		this.dbName = dbName;
242
	}
243

    
244
	public Resource getDspaceXslt() {
245
		return dspaceXslt;
246
	}
247

    
248
	public void setDspaceXslt(final Resource dspaceXslt) {
249
		this.dspaceXslt = dspaceXslt;
250
	}
251

    
252
	public Resource getEprintsXslt() {
253
		return eprintsXslt;
254
	}
255

    
256
	public void setEprintsXslt(final Resource eprintsXslt) {
257
		this.eprintsXslt = eprintsXslt;
258
	}
259

    
260
	public ProjectQueryParamsFactory getProjectQueryParamsFactory() {
261
		return projectQueryParamsFactory;
262
	}
263

    
264
	public void setProjectQueryParamsFactory(final ProjectQueryParamsFactory projectQueryParamsFactory) {
265
		this.projectQueryParamsFactory = projectQueryParamsFactory;
266
	}
267

    
268
	public Resource getProjectsFundingQueryTemplate() {
269
		return projectsFundingQueryTemplate;
270
	}
271

    
272
	public void setProjectsFundingQueryTemplate(final Resource projectsFundingQueryTemplate) {
273
		this.projectsFundingQueryTemplate = projectsFundingQueryTemplate;
274
	}
275

    
276
	public Resource getProjects2tsvQueryTemplate() {
277
		return projects2tsvQueryTemplate;
278
	}
279

    
280
	public void setProjects2tsvQueryTemplate(final Resource projects2tsvQueryTemplate) {
281
		this.projects2tsvQueryTemplate = projects2tsvQueryTemplate;
282
	}
283
}
(3-3/3)