Project

General

Profile

1
package eu.dnetlib.data.search.web.api;
2

    
3
import com.google.common.collect.Iterables;
4
import eu.dnetlib.api.data.SearchService;
5
import eu.dnetlib.api.data.SearchServiceException;
6
import eu.dnetlib.data.search.utils.cql.ParameterQueryEnhancer;
7
import eu.dnetlib.data.search.utils.vocabulary.VocabularyManager;
8
import eu.dnetlib.domain.data.FormattedSearchResult;
9
import io.micrometer.core.annotation.Timed;
10
import io.micrometer.prometheus.PrometheusMeterRegistry;
11
import org.apache.commons.lang.IncompleteArgumentException;
12
import org.apache.commons.lang.StringEscapeUtils;
13
import org.apache.log4j.Logger;
14
import org.springframework.beans.factory.annotation.Autowired;
15
import org.springframework.context.annotation.EnableAspectJAutoProxy;
16
import org.springframework.http.HttpStatus;
17
import org.springframework.http.MediaType;
18
import org.springframework.http.ResponseEntity;
19
import org.springframework.stereotype.Controller;
20
import org.springframework.ui.ModelMap;
21
import org.springframework.web.bind.annotation.*;
22

    
23
import javax.annotation.PostConstruct;
24
import javax.annotation.Resource;
25
import javax.servlet.http.HttpServletRequest;
26
import javax.servlet.http.HttpServletResponse;
27
import java.io.PrintWriter;
28
import java.text.SimpleDateFormat;
29
import java.util.*;
30

    
31
@Controller
32
@EnableAspectJAutoProxy
33
@Timed
34
public class SearchRequestController {
35

    
36
    @Autowired
37
    private SearchService searchService = null;
38
    @Autowired
39
    private VocabularyManager vocabularyManager = null;
40

    
41
    @Resource
42
    private String maxResults = null;
43

    
44
    @Resource
45
    private String maxSize = null;
46

    
47
    @Autowired
48
    private PrometheusMeterRegistry registry;
49

    
50
    private static Logger logger = Logger.getLogger(SearchRequestController.class);
51

    
52
    private static final String XML_CONTENT_TYPE = "application/xml;charset=UTF-8";
53
    private static final String JSON_CONTENT_TYPE = "application/json;charset=UTF-8;";
54
    private static final String CSV_CONTENT_TYPE = "text/csv;charset=UTF-8;";
55
    private static final String TSV_CONTENT_TYPE = "text/tab-separated-values;charset=UTF-8;";
56
    private static final String HTML_CONTENT_TYPE = "text/html;charset=UTF-8;";
57

    
58
    private static final String PUBLICATION_BASIC_QUERY = "(oaftype exact result) and (resulttypeid exact publication)";
59
    private static final String DATASET_BASIC_QUERY = "(oaftype exact result) and (resulttypeid exact dataset)";
60
    private static final String SOFTWARE_BASIC_QUERY = "(oaftype exact result) and (resulttypeid exact software)";
61
    private static final String OTHER_BASIC_QUERY = "(oaftype exact result) and (resulttypeid exact other)";
62
    private static final String PROJECT_BASIC_QUERY = "(oaftype exact project)";
63

    
64
    private static final HashSet<String> GLOBAL_PARAMETERS = new HashSet<>(Arrays.asList("page", "size", "format", "sortBy"));
65

    
66
    private static final HashSet<String> PUB_N_DATA_COMMON_PARAMETERS = new HashSet<>(Arrays.asList("author", "doi", "originalId",
67
            "community", "FP7ProjectID", "FP7scientificArea", "fromDateAccepted", "funder", "fundingStream", "hasECFunding", "hasProject",
68
            "hasWTFunding", "keywords", "model", "OA", "openaireProjectID", "openaireProviderID", "projectID", "title", "toDateAccepted",
69
            "country", "orcid"));
70

    
71
    private static final HashSet<String> PUB_PARAMETERS = new HashSet<>(Arrays.asList("openairePublicationID"));
72
    private static final HashSet<String> DATA_PARAMETERS = new HashSet<>(Arrays.asList("openaireDatasetID"));
73
    private static final HashSet<String> SOFTWARE_PARAMETERS = new HashSet<>(Arrays.asList("openaireSoftwareID"));
74
    private static final HashSet<String> OTHER_PARAMETERS = new HashSet<>(Arrays.asList("openaireOtherID"));
75

    
76
    private static final HashSet<String> PUB_N_DATASET_MODELS = new HashSet<>(Arrays.asList("dc", "openaire", "sygma"));
77
    private static final HashSet<String> PUB_N_DATASET_FORMATS = new HashSet<>(Arrays.asList("json", "rss", "xml", "csv", "tsv", "html"));
78

    
79
    private static final HashSet<String> PROJECT_PARAMETERS = new HashSet<>(Arrays.asList("acronym", "callID", "endYear", "FP7scientificArea",
80
            "funder", "fundingStream", "grantID", "hasECFunding", "hasWTFunding", "keywords", "name",
81
            "participantAcronyms", "participantCountries", "startYear", "sc39", "openaireParticipantID", "openaireProjectID"));
82
    private static final HashSet<String> PROJECT_FORMATS = new HashSet<>(Arrays.asList("xml", "json", "csv", "tsv", "html"));
83

    
84
    @PostConstruct
85
    public void init() {
86
        PUB_PARAMETERS.addAll(PUB_N_DATA_COMMON_PARAMETERS);
87
        DATA_PARAMETERS.addAll(PUB_N_DATA_COMMON_PARAMETERS);
88
        SOFTWARE_PARAMETERS.addAll(PUB_N_DATA_COMMON_PARAMETERS);
89
        OTHER_PARAMETERS.addAll(PUB_N_DATA_COMMON_PARAMETERS);
90
    }
91

    
92
    //TODO this is for joomla - to be removed soon
93
    @RequestMapping(value = "/search", method = RequestMethod.GET)
94
    @Timed(value = "search.joomla.requests", longTask = false)
95
    public void search(HttpServletRequest request, HttpServletResponse response) {
96
        PrintWriter writer = null;
97
        FormattedSearchResult formattedSearchResult = null;
98

    
99
        String action = readActionParameter(request);
100
        String query = readQueryParameter(request);
101
        String format = (request.getParameter("format") != null) ? request.getParameter("format") : "xml";
102
        createResponseMeta(response, format);
103

    
104
        String locale = request.getParameter("locale");
105

    
106
        int page = 0;
107
        int size = 0;
108
        //TODO check paging
109
        if (!action.equals("refine")) {
110
            page = readParameter(request, "page", 1);
111
            size = readParameter(request, "size", 10);
112
        }
113

    
114
        if (size > Integer.parseInt(maxSize)) {
115
            throw new IllegalArgumentException("Size argument have exceeded the maximum allowed number.");
116
        }
117

    
118
        String sTransformer = request.getParameter("sTransformer");
119
        String rTransformer = request.getParameter("rTransformer");
120
        Collection<String> fields = readParameter(request, "fields");
121

    
122
        checkTransformerParameters(action, sTransformer, rTransformer, fields);
123

    
124
        try {
125
            createResponseMeta(response, format);
126
            writer = response.getWriter();
127

    
128
            formattedSearchResult = searchService.searchNrefine(query,
129
                    sTransformer, rTransformer, format, locale, page, size,
130
                    fields);
131

    
132
            writer.append(formattedSearchResult.getFormattedResult());
133

    
134
        } catch (Exception e) {
135
            logger.error("Fail to execute search.", e);
136
            createXmlErrorPage(writer, e);
137

    
138
        } finally {
139
            if (writer != null) {
140
                writer.close();
141
            }
142
        }
143
    }
144

    
145
    private void checkTransformerParameters(String action, String sTransformer, String rTransformer, Collection<String> fields) {
146
        if (action.equals("search")) {
147
            if (sTransformer == null) {
148
                throw new IncompleteArgumentException("Undefined search transformer. Search request");
149
            }
150

    
151
        } else if (action.equals("refine")) {
152
            if (rTransformer == null) {
153
                throw new IncompleteArgumentException(
154
                        "Undefined refine transformer. Refine request");
155
            }
156

    
157
            if (fields == null) {
158
                throw new IncompleteArgumentException(
159
                        "Undefined refine fields. Refine request");
160
            }
161

    
162
        } else if (action.equals("searchNrefine")) {
163

    
164
            if (sTransformer == null) {
165
                throw new IncompleteArgumentException(
166
                        "Undefined search transformer. Search and Refine request");
167
            }
168

    
169
            if (rTransformer == null) {
170
                throw new IncompleteArgumentException(
171
                        "Undefined refine transformer. Search and Refine request");
172
            }
173

    
174
            if (fields == null) {
175
                throw new IncompleteArgumentException(
176
                        "Undefined refine fields. Search and Refine request");
177
            }
178

    
179
        } else {
180
            throw new UnsupportedOperationException("The action " + action
181
                    + " is not supported. Please try one of {search, refine, searchNrefine}.");
182
        }
183
    }
184

    
185
    private String readQueryParameter(HttpServletRequest request) {
186
        String query = request.getParameter("query");
187
        if (query == null) {
188
            throw new IncompleteArgumentException("Undefined query. Search request");
189
        }
190
        return query;
191
    }
192

    
193
    private String readActionParameter(HttpServletRequest request) {
194
        String action = request.getParameter("action");
195
        if (action == null) {
196
            throw new UnsupportedOperationException("Undefined action.");
197
        }
198
        return action;
199
    }
200

    
201

    
202
    @RequestMapping(value="/search/openSearchDescriptor", method = RequestMethod.GET)
203
    public String printOpenSearchDescriptor(ModelMap model) {
204
        return "openSearchDescriptor";
205
    }
206

    
207
    @RequestMapping(value = "/api/publications", method = RequestMethod.GET, produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE})
208
    @Timed(value = "http.server.request.duration", extraTags = {"referer", "api", "uri", "/api/publications"}, longTask = false)
209
    public void searchPublications(HttpServletRequest request, HttpServletResponse response) throws Exception {
210
        long time = System.currentTimeMillis();
211
        int page = readParameter(request, "page", 1);
212
        int size = readParameter(request, "size", 10);
213
        String format = (request.getParameter("format") != null) ? request.getParameter("format") : "xml";
214
        String model = request.getParameter("model");
215

    
216
        checkParameters(PUB_PARAMETERS,request.getParameterMap());
217
        checkRequestSize(page, size);
218
        checkFormatParameter(PUB_N_DATASET_FORMATS, format);
219
        createResponseMeta(response, format);
220
        checkModelParameter(PUB_N_DATASET_MODELS, model);
221

    
222
        String locale = request.getParameter("locale");
223
        String sTransformer = defineTransformer(model,format);
224

    
225
        Collection<String> referrers = readParameter(request,"referrer");
226
        String newFormat = defineFormatter(model, format, true, referrers);
227

    
228
        StringBuilder queryBuilder = new StringBuilder();
229
        queryBuilder.append(PUBLICATION_BASIC_QUERY);
230

    
231
        enhanceResearchOutcomesQuery(request, model, queryBuilder);
232
        FormattedSearchResult formattedSearchResult = null;
233

    
234
        try {
235
            formattedSearchResult = searchService.search(queryBuilder.toString(),sTransformer, (newFormat!=null)?newFormat:format, locale, page, size);
236

    
237
        } catch (Exception e) {
238
            logger.error("Fail to execute search.", e);
239
            throw new Exception("Fail to execute search", e);
240
        }
241

    
242
        PrintWriter writer = response.getWriter();
243
        writer.append(formattedSearchResult.getFormattedResult());
244

    
245
        writer.close();
246

    
247
        time = System.currentTimeMillis() - time;
248
        logger.debug("Answer old time " + time);
249
    }
250

    
251
    private void enhanceResearchOutcomesQuery(HttpServletRequest request, String model, StringBuilder queryBuilder) {
252
        ParameterQueryEnhancer.enhanceQueryWithFundingLevelParams(queryBuilder, request, vocabularyManager, isModelSygma(model));
253
        ParameterQueryEnhancer.enhanceQueryWithOpenAIREIds(queryBuilder, request);
254
        ParameterQueryEnhancer.enhanceQueryWithMetadataKeywords(queryBuilder, request);
255
        ParameterQueryEnhancer.enhanceQueryWithFundingParams(queryBuilder, request);
256
        ParameterQueryEnhancer.enhanceQueryWithCommunityParams(queryBuilder, request);
257
        ParameterQueryEnhancer.enhanceQueryWithRelProjectParams(queryBuilder, request);
258
        ParameterQueryEnhancer.enhanceQueryWithAccessRights(queryBuilder, request);
259
        ParameterQueryEnhancer.enhanceQueryWithDate(queryBuilder, request);
260
        ParameterQueryEnhancer.enhanceQueryWithDoi(queryBuilder, request);
261
        ParameterQueryEnhancer.enhanceQueryWithOrcid(queryBuilder, request);
262
        ParameterQueryEnhancer.enhanceQueryWithOriginalId(queryBuilder, request);
263

    
264
        ParameterQueryEnhancer.enhanceQueryWithResultsSortParameters(queryBuilder, request);
265
    }
266

    
267

    
268
    @RequestMapping(value = "/api/datasets", method = RequestMethod.GET, produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE})
269
    @Timed(value = "http.server.request.duration", extraTags = {"referer", "api", "uri", "/api/datasets"}, longTask = false)
270
    public void searchData(HttpServletRequest request, HttpServletResponse response) throws Exception {
271

    
272
        checkParameters(DATA_PARAMETERS,request.getParameterMap());
273

    
274
        int page = readParameter(request, "page", 1);
275
        int size = readParameter(request, "size", 10);
276
        checkRequestSize(page, size);
277

    
278
        String format = (request.getParameter("format") != null) ? request.getParameter("format") : "xml";
279
        createResponseMeta(response, format);
280

    
281
        checkFormatParameter(PUB_N_DATASET_FORMATS, format);
282

    
283
        String model = request.getParameter("model");
284
        checkModelParameter(PUB_N_DATASET_MODELS, model);
285
        String sTransformer = defineTransformer(model,format);
286

    
287
        Collection<String> referrers = readParameter(request,"referrer");
288
        String newFormat = defineFormatter(model, format, false, referrers);
289

    
290
        String locale = request.getParameter("locale");
291

    
292
        StringBuilder queryBuilder = new StringBuilder();
293
        queryBuilder.append(DATASET_BASIC_QUERY);
294

    
295
        enhanceResearchOutcomesQuery(request, model, queryBuilder);
296

    
297
        FormattedSearchResult formattedSearchResult =  null;
298
        try {
299
            formattedSearchResult = searchService.search(queryBuilder.toString(),sTransformer, (newFormat!=null)?newFormat:format, locale, page, size);
300

    
301
        } catch (Exception e) {
302
            logger.error("Fail to execute search.", e);
303
            throw new Exception("Fail to execute search.", e);
304
        }
305

    
306
        if (formattedSearchResult == null) {
307
            throw new Exception("Fail to execute search.");
308
        }
309

    
310
        PrintWriter writer = response.getWriter();
311
        writer.append(formattedSearchResult.getFormattedResult());
312
        writer.close();
313

    
314
    }
315

    
316
    @RequestMapping(value = "/api/software", method = RequestMethod.GET, produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE})
317
    @Timed(value = "http.server.request.duration", extraTags = {"referer", "api", "uri", "/api/software"}, longTask = false)
318
    public void searchSoftware(HttpServletRequest request, HttpServletResponse response) throws Exception {
319

    
320
        checkParameters(SOFTWARE_PARAMETERS,request.getParameterMap());
321

    
322
        int page = readParameter(request, "page", 1);
323
        int size = readParameter(request, "size", 10);
324
        checkRequestSize(page, size);
325

    
326
        String format = (request.getParameter("format") != null) ? request.getParameter("format") : "xml";
327
        createResponseMeta(response, format);
328

    
329
        checkFormatParameter(PUB_N_DATASET_FORMATS, format);
330

    
331
        String model = request.getParameter("model");
332
        checkModelParameter(PUB_N_DATASET_MODELS, model);
333
        String sTransformer = defineTransformer(model,format);
334

    
335
        Collection<String> referrers = readParameter(request,"referrer");
336
        String newFormat = defineFormatter(model, format, false, referrers);
337

    
338
        String locale = request.getParameter("locale");
339

    
340
        StringBuilder queryBuilder = new StringBuilder();
341
        queryBuilder.append(SOFTWARE_BASIC_QUERY);
342

    
343
        enhanceResearchOutcomesQuery(request, model, queryBuilder);
344

    
345
        FormattedSearchResult formattedSearchResult = null;
346

    
347
        try {
348
            formattedSearchResult =  searchService.search(queryBuilder.toString(),sTransformer, (newFormat!=null)?newFormat:format, locale, page, size);
349

    
350
        } catch (Exception e) {
351
            logger.error("Fail to execute search.", e);
352
            throw new Exception("Fail to execute search", e);
353
        }
354

    
355
        PrintWriter writer = response.getWriter();
356
        writer.append(formattedSearchResult.getFormattedResult());
357

    
358
    }
359

    
360
    @RequestMapping(value = "/api/other", method = RequestMethod.GET, produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE})
361
    @Timed(value = "http.server.request.duration", extraTags = {"referer", "api", "uri", "/api/other"}, longTask = false)
362
    public void searchOther(HttpServletRequest request, HttpServletResponse response) throws Exception {
363

    
364
        checkParameters(OTHER_PARAMETERS,request.getParameterMap());
365

    
366
        int page = readParameter(request, "page", 1);
367
        int size = readParameter(request, "size", 10);
368
        checkRequestSize(page, size);
369

    
370
        String format = (request.getParameter("format") != null) ? request.getParameter("format") : "xml";
371
        createResponseMeta(response, format);
372

    
373
        checkFormatParameter(PUB_N_DATASET_FORMATS, format);
374

    
375
        String model = request.getParameter("model");
376
        checkModelParameter(PUB_N_DATASET_MODELS, model);
377
        String sTransformer = defineTransformer(model,format);
378

    
379
        Collection<String> referrers = readParameter(request,"referrer");
380
        String newFormat = defineFormatter(model, format, false, referrers);
381

    
382
        String locale = request.getParameter("locale");
383

    
384
        StringBuilder queryBuilder = new StringBuilder();
385
        queryBuilder.append(OTHER_BASIC_QUERY);
386

    
387
        enhanceResearchOutcomesQuery(request, model, queryBuilder);
388

    
389
        FormattedSearchResult formattedSearchResult = null;
390

    
391
        //long start = System.currentTimeMillis();
392
        try {
393
            //Timer.Sample sample = Timer.start(metrics.getRegistry());
394
            formattedSearchResult =  searchService.search(queryBuilder.toString(),sTransformer, (newFormat!=null)?newFormat:format, locale, page, size);
395

    
396
        } catch (Exception e) {
397
            logger.error("Fail to execute search.", e);
398
            throw new Exception("Fail to execute search", e);
399
        }
400

    
401
        PrintWriter writer = response.getWriter();
402
        writer.append(formattedSearchResult.getFormattedResult());
403
    }
404

    
405
    @RequestMapping(value = "/api/projects", method = RequestMethod.GET, produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE})
406
    @Timed(value = "http.server.request.duration", extraTags = {"referer", "api", "uri", "/api/projects"}, longTask = false)
407
    public void searchProjects(HttpServletRequest request, HttpServletResponse response) throws Exception {
408

    
409
        checkParameters(PROJECT_PARAMETERS, request.getParameterMap());
410

    
411
        int page = readParameter(request, "page", 1);
412
        int size = readParameter(request, "size", 10);
413
        checkRequestSize(page, size);
414

    
415
        StringBuilder queryBuilder = new StringBuilder();
416
        queryBuilder.append(PROJECT_BASIC_QUERY);
417
        String locale = request.getParameter("locale");
418

    
419
        String format =  (request.getParameter("format") != null) ? request.getParameter("format") : "xml";
420
        checkFormatParameter(PROJECT_FORMATS, format);
421
        createResponseMeta(response, format);
422

    
423
        format = finalFormat(format);
424

    
425
        String sTransformer = request.getParameter("sTransformer");
426

    
427
        ParameterQueryEnhancer.enhanceProjectQueryWithOpenAIREIds(queryBuilder, request);
428
        ParameterQueryEnhancer.enhanceQueryWithProjectMetadataKeywords(queryBuilder, request);
429
        ParameterQueryEnhancer.enhanceQueryWithProjectFundingParams(queryBuilder, request);
430
        ParameterQueryEnhancer.enhanceProjectQueryWithFundingLevelParams(queryBuilder, request, vocabularyManager);
431
        ParameterQueryEnhancer.enhanceQueryWithParticipantsInfoParams(queryBuilder, request);
432
        ParameterQueryEnhancer.enhanceQueryWithYearParams(queryBuilder, request);
433
        ParameterQueryEnhancer.enhanceQueryWithSC39Params(queryBuilder, request);
434

    
435
        ParameterQueryEnhancer.enhanceQueryWithProjectSortParameters(queryBuilder, request);
436

    
437
        FormattedSearchResult formattedSearchResult = null;
438
        try {
439
            formattedSearchResult = searchService.search(queryBuilder.toString(),sTransformer, format, locale, page, size);
440

    
441
        } catch (SearchServiceException e) {
442
            throw new Exception("Fail to execute search", e);
443
        }
444

    
445
        PrintWriter writer = response.getWriter();
446
        writer.append(formattedSearchResult.getFormattedResult());
447
        writer.close();
448
    }
449

    
450

    
451
    @ExceptionHandler(IllegalArgumentException.class)
452
    public @ResponseBody ResponseEntity<Error> invalidInput(HttpServletRequest request, HttpServletResponse httpServletResponse, Exception ex) {
453
        Error response = new Error();
454
        response.setStatus("error");
455
        response.setCode("400");
456
        response.setMessage("400 - Illegal argument exception.");
457
        response.setException(ex.getMessage());
458

    
459
        String format = (request.getParameter("format") == null)? "xml": request.getParameter("format").toLowerCase();
460

    
461
        registry.counter("http.status.400", "400", "uri").increment();
462

    
463
        return new ResponseEntity<Error>(response, HttpStatus.BAD_REQUEST);
464
    }
465

    
466
    private String finalFormat(String format) {
467
        if (format.equals("tsv")){
468
            return "project_tsv";
469

    
470
        } else if (format.equals("csv")) {
471
            return "project_csv";
472

    
473
        } else if (format.equals("html")) {
474
            return "project_html";
475
        }
476

    
477
        return format;
478
    }
479

    
480
    private String finalFormat(String format, String referrer) {
481
        if (referrer == null || referrer.isEmpty() || !referrer.equals("joomla")) {
482
            return finalFormat(format);
483
        }
484

    
485
        if (format.equals("tsv")){
486
            return "publication_tsv_notitle";
487

    
488
        } else if (format.equals("csv")) {
489
            return "publication_csv_notitle";
490

    
491
        }
492

    
493
        return format;
494
    }
495

    
496
    /** TODO: check if needed
497
     * Based on the given model the transformer to be used is defined
498
     * @param model
499
     * @return
500

    
501
    private String defineTransformer(String model) {
502
    if (model!=null && !model.trim().isEmpty()) {
503
    if (model.equals("openaire")) {
504
    return null;
505

    
506
    } else if (model.equals("sygma")) {
507
    return "results_openaire";
508
    }
509
    else if (model.equals("dc")) {
510
    return "dc";
511
    }
512

    
513
    throw new IllegalArgumentException("model '" + model + "' is not supported.");
514

    
515
    } else {
516
    return null;
517
    }
518
    }*/
519

    
520
    //TODO: check if needed
521
    private String defineTransformer(String model, String format) {
522
        if (model != null && !model.trim().isEmpty() && format != null && (format.equals("json")||format.equals("xml"))) {
523
            if (model.equals("openaire")) {
524
                return null;
525

    
526
            } else if (model.equals("sygma")) {
527
                return "results_openaire";
528
            }
529
            else if (model.equals("dc")) {
530
                return "dc";
531
            }
532

    
533
            throw new IllegalArgumentException("model '" + model + "' is not supported.");
534

    
535
        } else if (format != null && !format.trim().isEmpty()) {
536
            if (format.equals("rss") || format.equals("csv") || format.equals("tsv") || format.equals("html")) {
537
                return "results_openaire";
538
            }
539
        }
540
        return null;
541

    
542
    }
543

    
544
    private String defineFormatter(String model, String format, boolean isPublications, Collection<String> referrers) {
545
        if( model != null && !model.trim().isEmpty() ) {
546
            if (model.equals("sygma")) {
547

    
548
                if (isPublications) {
549
                    return "sygma_publication";
550
                }
551
                return "sygma_dataset";
552
            }
553
        } else {
554
            if (referrers != null && !referrers.isEmpty() && Iterables.get(referrers, 0) != null && !Iterables.get(referrers, 0).isEmpty()) {
555
                return finalFormat(format, Iterables.get(referrers, 0));
556
            } else {
557
                format = finalFormat(format);
558
            }
559
        }
560

    
561
        return null;
562
    }
563

    
564
    @Deprecated
565
    private void createXmlErrorPage(PrintWriter writer, Exception e) {
566
        writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
567
        writer.append("<error>");
568
        writer.append("<exception>")
569
                .append(StringEscapeUtils.escapeXml(e.getClass().getName()))
570
                .append("</exception>");
571
        if (e.getMessage() != null) {
572
            writer.append("<message>")
573
                    .append(StringEscapeUtils.escapeXml(e.getMessage()))
574
                    .append("</message>");
575
        }
576
        if (e.getCause() != null) {
577
            writer.append("<cause>")
578
                    .append(StringEscapeUtils.escapeXml(e.getCause()
579
                            .toString())).append("</cause>");
580
        }
581

    
582
        StackTraceElement[] trace = e.getStackTrace();
583
        writer.append("<trace>");
584
        for (int i = 0; i < trace.length; i++) {
585
            writer.append(StringEscapeUtils.escapeXml(trace[i].toString()))
586
                    .append("\n");
587
        }
588
        writer.append("</trace>");
589

    
590
        writer.append("</error>");
591
    }
592

    
593
    // Reading parameters from url and adding default values
594
    public int readParameter(HttpServletRequest request, String parameterName, int defaultValue) {
595
        String param = request.getParameter(parameterName);
596
        return (param != null && !param.isEmpty()) ? Integer.parseInt(param) : defaultValue;
597
    }
598

    
599
    private Collection<String> readParameter(HttpServletRequest request, String parameterName) {
600
        Collection<String> fields = null;
601
        String[] paramfields = request.getParameterValues(parameterName);
602
        if (paramfields != null) {
603
            fields = new ArrayList<String>();
604
            for (int i = 0; i < paramfields.length; i++) {
605
                fields.add(paramfields[i]);
606
            }
607
        }
608
        return fields;
609
    }
610

    
611
    /**
612
     * Checks if the requested result size exceeds the maximum allowed numbers of returned results
613
     * @param page the page parameter
614
     * @param size the size parameter
615
     */
616
    private void checkRequestSize(int page, int size) {
617
        int total = page*size;
618
        if (total > Integer.parseInt(maxResults)) {
619
            throw new IllegalArgumentException("Size and page arguments have exceeded the maximum number of returned results.");
620
        }
621
    }
622

    
623
    private String defineContentType(String format) {
624
        if (format != null) {
625
            if (format.equalsIgnoreCase("xml")) {
626
                return XML_CONTENT_TYPE;
627
            } else if (format.equalsIgnoreCase("json")) {
628
                return JSON_CONTENT_TYPE;
629

    
630
            } else if (format.equalsIgnoreCase("csv")) {
631
                return CSV_CONTENT_TYPE;
632

    
633
            } else if (format.equalsIgnoreCase("tsv")) {
634
                return TSV_CONTENT_TYPE;
635

    
636
            } else if (format.equalsIgnoreCase("html")){
637
                return HTML_CONTENT_TYPE;
638
            }
639
        }
640

    
641
        return XML_CONTENT_TYPE;
642
    }
643
    /**
644
     * Checks if the parameters given are allowed. The given parameters are checked against the allowed parameter
645
     * and the GLOBAL_PARAMETERS.
646
     * @param allowedParameters the allowed parameters
647
     * @param currentParameters the given parameters
648
     */
649
    private void checkParameters(HashSet<String> allowedParameters, Map<String, String[]> currentParameters){
650
        if(currentParameters != null) {
651
            for (String parameter : currentParameters.keySet()) {
652
                if (!allowedParameters.contains(parameter) && !GLOBAL_PARAMETERS.contains(parameter) && !parameter.equals("referrer")) {
653
                    throw new IllegalArgumentException("Parameter " + parameter + " is not supported. The supported parameters are: " +
654
                            allowedParameters.toString().replace("[","").replace("]", ", ") + GLOBAL_PARAMETERS.toString().substring(1,GLOBAL_PARAMETERS.toString().length()-1));
655
                }
656
            }
657
        }
658
    }
659

    
660
    private void checkFormatParameter(HashSet<String> allowedFormats, String requestedFormat) {
661
        if (requestedFormat!= null && !allowedFormats.contains(requestedFormat)) {
662
            throw new IllegalArgumentException("The requested format \'"+ requestedFormat +"\' is not supported. The supported formats are: " + allowedFormats);
663
        }
664
    }
665

    
666
    private static void checkModelParameter(HashSet<String> allowedModels, String requestedModel) {
667
        if (requestedModel!= null && !allowedModels.contains(requestedModel)) {
668
            throw new IllegalArgumentException("The requested model \'"+ allowedModels +"\' is not supported. The supported formats are: " + allowedModels);
669
        }
670
    }
671

    
672
    private static boolean isModelSygma(String model) {
673
        if (model == null || model.isEmpty()) { return false; }
674

    
675
        if (!model.isEmpty() && !model.equals("sygma")) {
676
            return  false;
677
        }
678

    
679
        return true;
680
    }
681

    
682
    private void createResponseMeta( HttpServletResponse response, String format) {
683
        response.setContentType(defineContentType(format));
684
        response.setCharacterEncoding("UTF-8");
685

    
686
        if (!format.equals("xml") || !format.equals("json")) {
687

    
688
            SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
689
            String date = sdf.format(new Date());
690

    
691
            if (format.equals("csv")) {
692
                response.setHeader("Content-Disposition", "filename="+date+".csv");
693

    
694
            } else if (format.equals("csv")) {
695
                response.setHeader("Content-Disposition", "filename="+date+".tsv");
696

    
697
            } else if (format.equals("html")) {
698
                response.setHeader("Content-Disposition", "filename="+date+".html");
699
            }
700
        }
701
    }
702

    
703

    
704
    /* TODO: enable if we decide to use ACCEPT Header as a priority to format parameter
705
    private String getFormat(HttpServletRequest request) {
706
        if (request.getParameter("format") == null && request.getHeader("Accept")!=null) {
707
            if (request.getHeader("Accept").equals(MediaType.APPLICATION_XML_VALUE) ||
708
                    request.getHeader("Accept").contains(MediaType.APPLICATION_XML_VALUE)){
709
                return "xml";
710
            }
711

    
712
            if (request.getHeader("Accept").equals(MediaType.APPLICATION_JSON_VALUE)){
713
                return "json";
714
            }
715
        }
716

    
717
        if (request.getParameter("format") == null && (request.getHeader("Accept")== null ||
718
                request.getHeader("Accept").equals(MediaType.ALL_VALUE))) {
719
            return "xml";
720
        }
721

    
722
        return request.getParameter("format");
723
    } */
724

    
725
    /*public static void main() throws IOException, SolrServerException {
726

    
727
        long time = System.currentTimeMillis();
728

    
729
        CloudSolrClient solrClient = new CloudSolrClient.Builder().
730
                withZkHost(Arrays.asList(new String[]{"quorum0.t.hadoop.research-infrastructures.eu:2182",
731
                        "quorum1.t.hadoop.research-infrastructures.eu:2182",
732
                        "quorum2.t.hadoop.research-infrastructures.eu:2182",
733
                        "quorum3.t.hadoop.research-infrastructures.eu:2182",
734
                        "quorum4.t.hadoop.research-infrastructures.eu:2182/solr-dev-openaire"})).build();
735
        solrClient.setDefaultCollection("DMF-index-openaire");
736

    
737
       // response.setContentType("text/html");
738
       // ServletOutputStream out=response.getOutputStream();
739

    
740
        NamedList<String> queryOpts = new NamedList<String>();
741

    
742
        //q=*:*&start=0&rows=10&cursorMark=*&sort=dateofcollection asc
743
        try {
744
            queryOpts.add("q", new CqlTranslatorImpl().getTranslatedQuery("(oaftype exact result) and (resulttypeid exact publication) and (relfundershortname exact \"nhmrc_______::NHMRC||National Health and Medical Research Council (NHMRC)||NHMRC\")").asLucene());
745

    
746
        } catch (CQLParseException e) {
747
            logger.error(e);
748
        }
749
        queryOpts.add("start", "0");
750
        queryOpts.add("rows", "500");
751
        queryOpts.add("fl", "__result");
752
        queryOpts.add("shards.tolerant","true");
753
        queryOpts.add("cursorMark", "*");
754
        queryOpts.add("sort", "__indexrecordidentifier asc");
755

    
756

    
757
        //queryOpts.add("q", new CqlTranslatorImpl().getTranslatedQuery("oaftype exact project").asLucene());
758
        NamedList<String> extraOpts = new NamedList<String>();
759

    
760
        QueryResponse resp = null;
761

    
762
        String cursorMark = "*";
763
        String nextCursorMark = "";
764

    
765
        //QueryResponse resp = solrClient.query(SolrParams.toSolrParams(queryOpts));
766

    
767
        int curs = 0;
768
        while (!cursorMark.equals(nextCursorMark)) {
769
            logger.debug("QUERY OPTS: " + queryOpts.get("cursorMark"));
770
            resp = solrClient.query(SolrParams.toSolrParams(queryOpts));
771
            logger.debug("TOTAL number " + resp.getResults().getNumFound());
772
            logger.debug(resp.getNextCursorMark());
773

    
774
            System.out.println("BEGIN");
775
            System.out.println("cursor " + cursorMark);
776
            System.out.println("next cursor " + nextCursorMark);
777

    
778
            cursorMark = nextCursorMark;
779
            nextCursorMark = resp.getNextCursorMark();
780

    
781
            for (int i = 0; i < resp.getResults().size(); i++) {
782
                String result = ((ArrayList<String>) resp.getResults().get(i).get("__result")).get(0);
783
             //   out.write(result.getBytes());
784
             //   out.flush();
785
            }
786

    
787
            System.out.println("END");
788
            System.out.println("cursor " + cursorMark);
789
            System.out.println("next cursor " + nextCursorMark);
790
            queryOpts.remove("cursorMark");
791
            queryOpts.add("cursorMark", nextCursorMark);
792

    
793
            System.out.println("CURS " + curs);
794
            curs ++;
795

    
796
        }
797

    
798
      //  out.close();
799

    
800
        time = System.currentTimeMillis() - time;
801
        System.out.println("Answer time " + time);
802
    }*/
803

    
804
}
(9-9/11)