1
|
package eu.dnetlib.openaire.exporter.project;
|
2
|
|
3
|
import java.io.BufferedOutputStream;
|
4
|
import java.io.IOException;
|
5
|
import java.io.OutputStream;
|
6
|
import java.sql.SQLException;
|
7
|
import java.text.SimpleDateFormat;
|
8
|
import java.util.Arrays;
|
9
|
import java.util.Date;
|
10
|
import java.util.Map;
|
11
|
import java.util.concurrent.atomic.AtomicInteger;
|
12
|
import java.util.zip.GZIPOutputStream;
|
13
|
import java.util.zip.ZipEntry;
|
14
|
import java.util.zip.ZipOutputStream;
|
15
|
import javax.servlet.ServletOutputStream;
|
16
|
import javax.servlet.ServletResponse;
|
17
|
import javax.servlet.http.HttpServletRequest;
|
18
|
import javax.servlet.http.HttpServletResponse;
|
19
|
|
20
|
import com.google.common.base.Joiner;
|
21
|
import com.google.common.collect.Maps;
|
22
|
import com.google.common.xml.XmlEscapers;
|
23
|
import eu.dnetlib.common.rmi.DNetRestDocumentation;
|
24
|
import eu.dnetlib.openaire.exporter.datasource.ApiException;
|
25
|
import eu.dnetlib.openaire.exporter.model.project.ProjectTsv;
|
26
|
import eu.dnetlib.openaire.exporter.project.repository.ProjectDetailsRepository;
|
27
|
import eu.dnetlib.openaire.exporter.project.repository.ProjectTsvRepository;
|
28
|
import org.antlr.stringtemplate.StringTemplate;
|
29
|
import org.apache.commons.io.IOUtils;
|
30
|
import org.apache.commons.lang3.StringUtils;
|
31
|
import org.apache.commons.lang3.exception.ExceptionUtils;
|
32
|
import org.apache.commons.logging.Log;
|
33
|
import org.apache.commons.logging.LogFactory;
|
34
|
import org.springframework.beans.factory.annotation.Autowired;
|
35
|
import org.springframework.beans.factory.annotation.Value;
|
36
|
import org.springframework.core.io.Resource;
|
37
|
import org.springframework.http.HttpStatus;
|
38
|
import org.springframework.stereotype.Controller;
|
39
|
import org.springframework.web.bind.annotation.*;
|
40
|
|
41
|
@Controller
|
42
|
@DNetRestDocumentation
|
43
|
public class ProjectsController {
|
44
|
|
45
|
private static final Log log = LogFactory.getLog(ProjectsController.class); // NOPMD by marko on 11/24/08 5:02 PM
|
46
|
|
47
|
public final static String UTF8 = "UTF-8";
|
48
|
|
49
|
@Value("${openaire.project.exporter.projectsfundings.sql.template}")
|
50
|
private Resource projectsFundingQueryTemplate;
|
51
|
|
52
|
@Value("${openaire.project.exporter.projects2tsv.sql.template}")
|
53
|
private Resource projects2tsvQueryTemplate;
|
54
|
|
55
|
@Value("${openaire.project.exporter.dspace.template.project}")
|
56
|
private Resource dspaceTemplate;
|
57
|
|
58
|
@Value("${openaire.project.exporter.dspace.template.head}")
|
59
|
private Resource dspaceHeadTemplate;
|
60
|
|
61
|
@Value("${openaire.project.exporter.dspace.template.tail}")
|
62
|
private Resource dspaceTailTemplate;
|
63
|
|
64
|
@Value("${openaire.project.exporter.eprints.template}")
|
65
|
private Resource eprintsTemplate;
|
66
|
|
67
|
@Value("${openaire.project.exporter.projectdetails.sql}")
|
68
|
private Resource projectDetailsSql;
|
69
|
|
70
|
@Value("${openaire.project.exporter.projectdetails.flushsize}")
|
71
|
private int gzipFlushSize;
|
72
|
|
73
|
@Autowired
|
74
|
private JdbcApiDao dao;
|
75
|
|
76
|
@Autowired
|
77
|
private ProjectQueryParamsFactory projectQueryParamsFactory;
|
78
|
|
79
|
@Autowired
|
80
|
private ProjectDetailsRepository projectDetailsRepository;
|
81
|
|
82
|
@Autowired
|
83
|
private ProjectTsvRepository projectTsvRepository;
|
84
|
|
85
|
@Deprecated
|
86
|
/**
|
87
|
* @deprecated we should use the codes returned by the yet to come service
|
88
|
*/
|
89
|
public enum Funding {
|
90
|
FP7, WT, FCT, H2020, NHMRC, ARC, SFI, MZOS, HRZZ, NWO, MESTD, FWF, SNSF, RCUK
|
91
|
}
|
92
|
|
93
|
@RequestMapping(value = "/openaire/export/**/project/dspace.do", method = RequestMethod.GET)
|
94
|
void processDspace(final HttpServletRequest request,
|
95
|
final ServletResponse response,
|
96
|
@RequestParam(value = "startFrom", required = false) final String startFrom,
|
97
|
@RequestParam(value = "startUntil", required = false) final String startUntil,
|
98
|
@RequestParam(value = "endFrom", required = false) final String endFrom,
|
99
|
@RequestParam(value = "endUntil", required = false) final String endUntil) throws Exception {
|
100
|
|
101
|
|
102
|
final ProjectQueryParams params = projectQueryParamsFactory.generateParams(request, startFrom, startUntil, endFrom, endUntil);
|
103
|
final StringTemplate headSt = new StringTemplate(IOUtils.toString(dspaceHeadTemplate.getInputStream(), UTF8 ));
|
104
|
|
105
|
headSt.setAttribute("fundingProgramme", params.getFundingProgramme());
|
106
|
|
107
|
final StringTemplate tailSt = new StringTemplate(IOUtils.toString(dspaceTailTemplate.getInputStream(), UTF8));
|
108
|
|
109
|
response.setContentType("text/xml");
|
110
|
doProcess(response, params, headSt.toString(), dspaceTemplate, tailSt.toString(), s -> XmlEscapers.xmlContentEscaper().escape(oneLiner(s)));
|
111
|
}
|
112
|
|
113
|
@RequestMapping(value = "/openaire/export/**/project/eprints.do", method = RequestMethod.GET)
|
114
|
void processEprints(final HttpServletRequest request,
|
115
|
final ServletResponse response,
|
116
|
@RequestParam(value = "startFrom", required = false) final String startFrom,
|
117
|
@RequestParam(value = "startUntil", required = false) final String startUntil,
|
118
|
@RequestParam(value = "endFrom", required = false) final String endFrom,
|
119
|
@RequestParam(value = "endUntil", required = false) final String endUntil) throws Exception {
|
120
|
|
121
|
final ProjectQueryParams params = projectQueryParamsFactory.generateParams(request, startFrom, startUntil, endFrom, endUntil);
|
122
|
response.setContentType("text/html");
|
123
|
doProcess(response, params, null, eprintsTemplate, null, s -> oneLiner(s));
|
124
|
}
|
125
|
|
126
|
private String oneLiner(final String s) {
|
127
|
return StringUtils.isNotBlank(s) ? s.replaceAll("\\n", " ").trim() : "";
|
128
|
}
|
129
|
|
130
|
private void doProcess(
|
131
|
final ServletResponse response,
|
132
|
final ProjectQueryParams params,
|
133
|
final String head, final Resource projectTemplate, final String tail,
|
134
|
final ValueCleaner cleaner) throws IOException, SQLException {
|
135
|
|
136
|
final StringTemplate st = new StringTemplate(IOUtils.toString(projectTemplate.getInputStream(), UTF8));
|
137
|
dao.streamProjects(obtainQuery(params), response.getOutputStream(), head, st, tail, cleaner);
|
138
|
}
|
139
|
|
140
|
@RequestMapping(value = "/openaire/export/project2tsv.do", method = RequestMethod.GET)
|
141
|
void processTsv(final HttpServletRequest request, final HttpServletResponse response,
|
142
|
@RequestParam(value = "funding", required = true) final String funding,
|
143
|
@RequestParam(value = "article293", required = false) final Boolean article293) throws Exception {
|
144
|
|
145
|
final String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
|
146
|
final String filename = "projects_" + funding + "_" + date + ".tsv";
|
147
|
response.setContentType("text/tab-separated-values");
|
148
|
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".zip\"");
|
149
|
|
150
|
final StringTemplate st = new StringTemplate(IOUtils.toString(projects2tsvQueryTemplate.getInputStream(), UTF8));
|
151
|
Funding requestedFunding = Funding.valueOf(funding.toUpperCase());
|
152
|
String fundingPrefix = getFundingPrefix(requestedFunding, null);
|
153
|
log.debug("Setting fundingprefix to " + fundingPrefix);
|
154
|
st.setAttribute("fundingprefix", fundingPrefix);
|
155
|
st.setAttribute("filters", expandFilters(article293));
|
156
|
|
157
|
final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
|
158
|
out.putNextEntry(new ZipEntry(filename));
|
159
|
dao.streamProjectsTSV(st.toString(), out);
|
160
|
}
|
161
|
|
162
|
@RequestMapping(value = "/openaire/export/project2tsv2.do", method = RequestMethod.GET)
|
163
|
void processTsv2(final HttpServletRequest request, final HttpServletResponse response,
|
164
|
@RequestParam(value = "funding", required = true) final String funding,
|
165
|
@RequestParam(value = "article293", required = false) final Boolean article293) throws Exception {
|
166
|
|
167
|
final Funding requestedFunding = Funding.valueOf(funding.toUpperCase());
|
168
|
final String fundingPrefix = getFundingPrefix(requestedFunding, null);
|
169
|
|
170
|
final String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
|
171
|
final String filename = "projects_" + funding + "_" + date + ".tsv";
|
172
|
response.setContentType("text/tab-separated-values");
|
173
|
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".zip\"");
|
174
|
|
175
|
try(final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()))) {
|
176
|
out.putNextEntry(new ZipEntry(filename));
|
177
|
queryForTsv(fundingPrefix, article293).forEach(p -> {
|
178
|
try {
|
179
|
out.write(Joiner.on('\t').useForNull("").join(p.asList()).getBytes(UTF8));
|
180
|
out.write('\n');
|
181
|
} catch (IOException e) {
|
182
|
throw new RuntimeException(e);
|
183
|
}
|
184
|
});
|
185
|
} catch (Throwable e) {
|
186
|
throw new ApiException(org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error processing the request", e);
|
187
|
}
|
188
|
}
|
189
|
|
190
|
private Iterable<ProjectTsv> queryForTsv(final String fundingPrefix, final Boolean article293) {
|
191
|
log.debug(String.format("fundingPrefix:'%s' and article293:'%s'", fundingPrefix, article293));
|
192
|
if (article293 != null) {
|
193
|
return projectTsvRepository.findByFundingpathidStartingWithAndOaMandateForDatasetsOrderByAcronym(fundingPrefix, article293);
|
194
|
} else {
|
195
|
return projectTsvRepository.findByFundingpathidStartingWithOrderByAcronym(fundingPrefix);
|
196
|
}
|
197
|
}
|
198
|
|
199
|
@RequestMapping(value = "/openaire/export/streamProjectDetails.do", method = RequestMethod.GET)
|
200
|
void streamProjectDetails(final HttpServletResponse response,
|
201
|
@RequestParam(value = "format", required = true) final String format,
|
202
|
@RequestParam(value = "compress", required = false) final Boolean compress) throws IOException, SQLException {
|
203
|
|
204
|
if (compress != null && compress) {
|
205
|
response.setHeader("Content-Encoding", "gzip");
|
206
|
}
|
207
|
switch (format) {
|
208
|
case "csv":
|
209
|
response.setContentType("text/csv");
|
210
|
break;
|
211
|
case "json":
|
212
|
response.setContentType("text/plain");
|
213
|
break;
|
214
|
default: throw new IllegalArgumentException("unsupported format: " + format);
|
215
|
}
|
216
|
|
217
|
final OutputStream out = getOutputStream(response.getOutputStream(), compress);
|
218
|
try {
|
219
|
final AtomicInteger i = new AtomicInteger(0);
|
220
|
projectDetailsRepository.findAll().forEach(p -> {
|
221
|
try {
|
222
|
switch (format) {
|
223
|
case "csv":
|
224
|
out.write(p.asCSV().getBytes(UTF8));
|
225
|
break;
|
226
|
case "json":
|
227
|
out.write(p.asJson().getBytes(UTF8));
|
228
|
break;
|
229
|
}
|
230
|
i.incrementAndGet();
|
231
|
if (i.intValue() % gzipFlushSize == 0) {
|
232
|
log.debug("flushing output stream");
|
233
|
out.flush();
|
234
|
}
|
235
|
} catch (IOException e) {
|
236
|
throw new RuntimeException(e);
|
237
|
}
|
238
|
}
|
239
|
);
|
240
|
} finally {
|
241
|
if (out instanceof GZIPOutputStream) {
|
242
|
((GZIPOutputStream) out).finish();
|
243
|
}
|
244
|
out.close();
|
245
|
}
|
246
|
}
|
247
|
|
248
|
private OutputStream getOutputStream(final ServletOutputStream outputStream, final Boolean compress) throws IOException {
|
249
|
if (compress != null && compress) {
|
250
|
return new GZIPOutputStream(outputStream);
|
251
|
}
|
252
|
return outputStream;
|
253
|
}
|
254
|
|
255
|
@ExceptionHandler({Exception.class, Throwable.class})
|
256
|
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
|
257
|
public @ResponseBody ErrorMessage handleSqlException(final Exception e) {
|
258
|
log.debug(e.getMessage(), e);
|
259
|
if (StringUtils.containsIgnoreCase(ExceptionUtils.getRootCauseMessage(e), "Broken pipe")) {
|
260
|
return null; //socket is closed, cannot return any response
|
261
|
} else {
|
262
|
return new ErrorMessage(e);
|
263
|
}
|
264
|
}
|
265
|
|
266
|
public class ErrorMessage {
|
267
|
|
268
|
private final String message;
|
269
|
private final String stacktrace;
|
270
|
|
271
|
public ErrorMessage(final Exception e) {
|
272
|
this(e.getMessage(), ExceptionUtils.getStackTrace(e));
|
273
|
}
|
274
|
|
275
|
public ErrorMessage(final String message, final String stacktrace) {
|
276
|
this.message = message;
|
277
|
this.stacktrace = stacktrace;
|
278
|
}
|
279
|
|
280
|
public String getMessage() {
|
281
|
return this.message;
|
282
|
}
|
283
|
|
284
|
public String getStacktrace() {
|
285
|
return this.stacktrace;
|
286
|
}
|
287
|
}
|
288
|
|
289
|
|
290
|
private Map<String, String> expandFilters(final Boolean article293) {
|
291
|
final Map<String, String> res = Maps.newHashMap();
|
292
|
|
293
|
if (article293 != null) {
|
294
|
res.put("ec_article29_3", String.valueOf(article293));
|
295
|
}
|
296
|
|
297
|
return res;
|
298
|
}
|
299
|
|
300
|
/**
|
301
|
* Creates the query on the fundingProgramme specified in the given parameters.
|
302
|
*
|
303
|
* @param params
|
304
|
* request parameters
|
305
|
* @return the query string
|
306
|
* @throws IllegalArgumentException
|
307
|
* if the funding program is not recognized
|
308
|
* @throws IOException
|
309
|
* if there are problem loading the query temlate
|
310
|
* @throws IllegalArgumentException
|
311
|
* if the funding program is not recognized
|
312
|
*/
|
313
|
protected String obtainQuery(final ProjectQueryParams params) throws IllegalArgumentException, IOException {
|
314
|
String funding = params.getFundingProgramme();
|
315
|
String suffix = params.getFundingPath();
|
316
|
String fundingPrefix = getFundingPrefix(Funding.valueOf(funding.toUpperCase()), suffix);
|
317
|
final StringTemplate st = new StringTemplate(IOUtils.toString(projectsFundingQueryTemplate.getInputStream(), UTF8));
|
318
|
st.setAttribute("fundingprefix", fundingPrefix);
|
319
|
String theQuery = setDateParameters(st.toString(), params);
|
320
|
log.debug("Generated query: " + theQuery);
|
321
|
return theQuery;
|
322
|
}
|
323
|
|
324
|
/**
|
325
|
* @deprecated call the yet to come service that returns the funding prefix given a funding code
|
326
|
*/
|
327
|
@Deprecated
|
328
|
private String getFundingPrefix(final Funding funding, final String suffix) throws IllegalArgumentException {
|
329
|
switch (funding) {
|
330
|
case FCT:
|
331
|
if (StringUtils.isBlank(suffix)) return "fct_________::FCT";
|
332
|
else return "fct_________::FCT::" + suffix;
|
333
|
case WT:
|
334
|
if (StringUtils.isBlank(suffix)) return "wt__________::WT";
|
335
|
else return "wt__________::WT::" + suffix;
|
336
|
case FP7:
|
337
|
if (StringUtils.isBlank(suffix)) return "ec__________::EC::FP7";
|
338
|
else return "ec__________::EC::FP7::" + suffix;
|
339
|
case H2020:
|
340
|
if (StringUtils.isBlank(suffix)) return "ec__________::EC::H2020";
|
341
|
else return "ec__________::EC::H2020" + suffix;
|
342
|
case NHMRC:
|
343
|
if (StringUtils.isBlank(suffix)) return "nhmrc_______::NHMRC";
|
344
|
else return "nhmrc_______::NHMRC::" + suffix;
|
345
|
case ARC:
|
346
|
if (StringUtils.isBlank(suffix)) return "arc_________::ARC";
|
347
|
else return "arc_________::ARC::" + suffix;
|
348
|
case SFI:
|
349
|
if (StringUtils.isBlank(suffix)) return "sfi_________::SFI";
|
350
|
else return "sfi_________::SFI::" + suffix;
|
351
|
case MZOS:
|
352
|
if (StringUtils.isBlank(suffix)) return "irb_hr______::MZOS";
|
353
|
else return "irb_hr______::MZOS::" + suffix;
|
354
|
case HRZZ:
|
355
|
if (StringUtils.isBlank(suffix)) return "irb_hr______::HRZZ";
|
356
|
else return "irb_hr______::HRZZ::" + suffix;
|
357
|
case NWO:
|
358
|
if (StringUtils.isBlank(suffix)) return "nwo_________::NWO";
|
359
|
else return "nwo_________::NWO::" + suffix;
|
360
|
case MESTD:
|
361
|
if (StringUtils.isBlank(suffix)) return "mestd_______::MESTD";
|
362
|
else return "mestd_______::MESTD::" + suffix;
|
363
|
case FWF:
|
364
|
if (StringUtils.isBlank(suffix)) return "fwf_________::FWF";
|
365
|
else return "fwf_________::FWF::" + suffix;
|
366
|
case SNSF:
|
367
|
if (StringUtils.isBlank(suffix)) return "snsf________::SNSF";
|
368
|
else return "snsf________::SNSF::" + suffix;
|
369
|
case RCUK:
|
370
|
if (StringUtils.isBlank(suffix)) return "rcuk________::RCUK";
|
371
|
else return "rcuk________::RCUK::" + suffix;
|
372
|
default:
|
373
|
throw new IllegalArgumentException("Invalid funding " + funding + " (valid are: " + Arrays.asList(Funding.values()) + ") ");
|
374
|
}
|
375
|
}
|
376
|
|
377
|
private String setDateParameters(final String query, final ProjectQueryParams params) {
|
378
|
String queryWithDates = query;
|
379
|
if (params.getStartFrom() != null) {
|
380
|
queryWithDates += " AND startdate >= '" + params.getStartFrom() + "'";
|
381
|
}
|
382
|
if (params.getStartUntil() != null) {
|
383
|
queryWithDates += " AND startdate <= '" + params.getStartUntil() + "'";
|
384
|
}
|
385
|
if (params.getEndFrom() != null) {
|
386
|
queryWithDates += " AND enddate >= '" + params.getEndFrom() + "'";
|
387
|
}
|
388
|
if (params.getEndUntil() != null) {
|
389
|
queryWithDates += " AND enddate <= '" + params.getEndUntil() + "'";
|
390
|
}
|
391
|
return queryWithDates;
|
392
|
}
|
393
|
|
394
|
public void setProjectsFundingQueryTemplate(final Resource projectsFundingQueryTemplate) {
|
395
|
this.projectsFundingQueryTemplate = projectsFundingQueryTemplate;
|
396
|
}
|
397
|
|
398
|
}
|