Project

General

Profile

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

    
3
import eu.dnetlib.api.data.SearchServiceException;
4
import eu.dnetlib.data.search.app.SearchServiceImpl;
5
import eu.dnetlib.data.search.utils.SolrResultsFormatter;
6
import eu.dnetlib.data.search.web.utils.RequestResponseHandler;
7
import eu.dnetlib.domain.data.SearchResult;
8
import eu.dnetlib.functionality.index.cql.CqlTranslator;
9
import eu.dnetlib.functionality.index.cql.CqlTranslatorImpl;
10
import org.apache.log4j.Logger;
11
import org.json.XML;
12
import org.springframework.beans.factory.annotation.Autowired;
13
import org.springframework.stereotype.Component;
14
import org.z3950.zing.cql.CQLParseException;
15

    
16
import javax.servlet.http.HttpServletRequest;
17
import javax.ws.rs.*;
18
import javax.ws.rs.core.Context;
19
import javax.ws.rs.core.MediaType;
20
import javax.ws.rs.core.Response;
21
import java.io.IOException;
22
import java.util.Arrays;
23
import java.util.List;
24
import java.util.Locale;
25
import java.util.Map;
26

    
27
/**
28
 * Created by kiatrop on 2/6/2016.
29
 */
30

    
31
@Component
32
@Path("/v2")
33
public class SearchApiService {
34

    
35
    private static final Logger logger = Logger.getLogger(SearchApiService.class);
36

    
37
    @Autowired
38
    private SearchServiceImpl searchService = null;
39

    
40
    @GET
41
    @Path("/api/resources")
42
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
43
    public Response fetchResources(@QueryParam("query") String query,
44
                                      @DefaultValue("1") @QueryParam("page") final int offset,
45
                                      @DefaultValue("10") @QueryParam("size") final int limit,
46
                                      @QueryParam("refine") @DefaultValue("false") final boolean refine,
47
                                      @QueryParam("fields") final List<String> fields,
48
                                      @QueryParam("fq") final List<String> fieldQueries,
49
                                      @QueryParam("format") final String format,
50
                                      @Context final HttpServletRequest request) {
51
        String type = null;
52
        if (format != null && !format.isEmpty() && format.equalsIgnoreCase("json")) {
53
            type = MediaType.APPLICATION_JSON;
54
            
55
        } else {
56
            type = MediaType.APPLICATION_XML;
57
        }
58

    
59
        if(query == null || query.isEmpty()) {
60
            return Response.status(Response.Status.BAD_REQUEST).
61
                    entity(APIResponseFormatter.compose400Message(type, "The 'query' parameter is required")).
62
                    type(type).build();
63
        }
64
        
65
        return getResponseByEntity(query, RequestResponseHandler.Entity.PUBLICATION, offset, limit, format, request, refine, fields, fieldQueries);
66
    }
67
/*
68
    @GET
69
    @Path("/api/publications")
70
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
71
    public Response fetchPublications(@QueryParam("q") String keywords,
72
                                      @DefaultValue("1") @QueryParam("page") final int offset,
73
                                      @DefaultValue("10") @QueryParam("size") final int limit,
74
                                      @QueryParam("refine") @DefaultValue("false") final boolean refine,
75
                                      @QueryParam("fields") final List<String> fields,
76
                                      @QueryParam("format") final String format,
77
                                      @Context final HttpServletRequest request) {
78
        
79
            String simpleQuery = createSimpleSearchQuery(RequestResponseHandler.Entity.PUBLICATION, keywords);
80
            return getResponseByEntity(simpleQuery, RequestResponseHandler.Entity.PUBLICATION, offset, limit, format, request, refine, fields);
81

    
82
    }
83

    
84
    private String createSimpleSearchQuery(RequestResponseHandler.Entity entity, String keywords) {
85
        StringBuilder queryBuilder = new StringBuilder();
86
        enhanceQueryWithEntityType(queryBuilder,entity);
87
        enhanceQueryWithKeywords(queryBuilder, keywords);
88
        return queryBuilder.toString();
89
    }
90

    
91
    private void enhanceQueryWithKeywords(StringBuilder queryBuilder, String keywords) {
92
        queryBuilder.append(' ').append(CQLQueryGeneration.Operator.AND).append(' ').append(keywords);
93
    }
94

    
95
    private String builtFullQuery(List<String> keywords, List<String> keywordOperators, RequestResponseHandler.Entity entity, HttpServletRequest request) {
96
        Map<String, String[]> parameterMap = request.getParameterMap();
97

    
98
        Map<String, String[]> operators = new HashMap<String, String[]>();
99
        Map<String, String[]> parameters = new HashMap<String, String[]>();
100
        extractParameterNOperatorsValues(parameterMap, operators, parameters, entity);
101

    
102
        return enhanceQuery(keywords, keywordOperators, operators, parameters, entity);
103
    }
104

    
105
/*    public static void buildFq(RequestResponseHandler.Entity entity, HttpServletRequest request, List<String> fields, List<FieldQuery> fieldQueries) {
106
        Map<String, String[]> parameterMap = request.getParameterMap();
107

    
108
        Map<String, String> indexParameterMap = entity.geIndexParameterMap();
109
        Map<String, String> parameterOperatorMap = entity.getParameterOperatorMap();
110
        //logger.debug(parameterOperatorMap.keySet());
111

    
112
        for (String field:fields) {
113
            logger.debug("field: " + field);
114
            String parameter = indexParameterMap.get(field);
115
            logger.debug("parameter: " + parameter);
116
            if (indexParameterMap.get(field) != null  ) {
117
                String[] refineValues = request.getParameterValues(parameter);
118
                String operatorParameter = parameterOperatorMap.get(parameter);
119
                String operatorValue = null;
120
                if (operatorParameter != null && !operatorParameter.trim().isEmpty()) {
121
                    operatorValue = request.getParameter(operatorParameter);
122
                    if (operatorValue == null || operatorValue.trim().isEmpty()) {
123
                        operatorValue = "AND";
124
                    }
125
                    fieldQueries.add(new FieldQuery(field, operatorValue, refineValues));
126

    
127
                } else {
128
                    //TODO throw exception?
129
                }
130
            }
131
        }
132
    }
133
*/
134

    
135
    /*
136

    
137
    public static String createFqParameter(List<FieldQuery> fieldQueries) {
138
        StringBuilder fq = new StringBuilder();
139
        for (FieldQuery fieldQuery:fieldQueries) {
140
            fq.append(fieldQuery.getIndexField());
141
            if(fieldQuery.getValues() != null && fieldQuery.getValues().length == 0) {
142
                for(int i=0; i< fieldQuery.getValues().length; i++) {
143
                    fq.append(":").append(fieldQuery.getValues()[i] + " ");
144
                    if(i < fieldQuery.getValues().length-1) {
145
                        fq.append(" " + fieldQuery.getOperator() + " ");
146
                    }
147
                }
148
            }
149
        }
150
        return fq.toString();
151
    }
152

    
153
    @GET
154
    @Path("/api/publications/count")
155
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
156
    public Response fetchPublicationsCount(@QueryParam("q") String query) {
157
        String fullQuery = builtQueryByEntity(query, RequestResponseHandler.Entity.PUBLICATION);
158
        return getCount(fullQuery);
159
    }
160

    
161

    
162
    @GET
163
    @Path("/api/publications/{publicationid}")
164
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
165
    public Response fetchPublicationsById(@PathParam("publicationid") String publicationid) {
166
        return getResponseByEntityId(RequestResponseHandler.Entity.PUBLICATION, publicationid);
167
    }
168

    
169

    
170
    @GET
171
    @Path("/api/datasets")
172
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
173
    public Response fetchDatasets(@QueryParam("q") List<String> keywords,
174
                                  @QueryParam("op") final List<String> keywordOperators,
175
                                  @DefaultValue("1") @QueryParam("page") int offset,
176
                                  @DefaultValue("10") @QueryParam("size") int limit,
177
                                  @QueryParam("refine") @DefaultValue("false") boolean refine,
178
                                  @QueryParam("fields") final List<String> fields,
179
                                  @QueryParam("format") final String format,
180
                                  @Context HttpServletRequest request) {
181

    
182
        String fullQuery = builtFullQuery(keywords, keywordOperators, RequestResponseHandler.Entity.PUBLICATION, request);
183
        return getResponseByEntity(fullQuery, RequestResponseHandler.Entity.DATASET, offset, limit, format, request, refine, fields);
184
    }
185

    
186
    @GET
187
    @Path("/api/datasets/count")
188
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
189
    public Response fetchDatesetsCount(@QueryParam("q") String query) {
190
        String fullQuery = builtQueryByEntity(query, RequestResponseHandler.Entity.DATASET);
191
        return getCount(fullQuery);
192
    }
193

    
194
    @GET
195
    @Path("/api/datasets/{datasetid}")
196
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
197
    public Response fetchDatasets(@PathParam("datasetid") String datasetid) {
198
        return getResponseByEntityId(RequestResponseHandler.Entity.DATASET, datasetid);
199
    }
200

    
201

    
202
    @GET
203
    @Path("/api/projects")
204
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
205
    public Response fetchProjects(@QueryParam("q") List<String> keywords,
206
                                  @QueryParam("op") final List<String> keywordOperators,
207
                                  @DefaultValue("1") @QueryParam("page") final int offset,
208
                                  @DefaultValue("10") @QueryParam("size") final int limit,
209
                                  @QueryParam("refine") @DefaultValue("false") final boolean refine,
210
                                  @QueryParam("format") final String format,
211
                                  @QueryParam("fields") final List<String> fields,
212
                                  @Context final HttpServletRequest request)  {
213

    
214
        String fullQuery = builtFullQuery(keywords, keywordOperators, RequestResponseHandler.Entity.PROJECT, request);
215
        return getResponseByEntity(fullQuery, RequestResponseHandler.Entity.PROJECT, offset, limit, format, request, refine, fields);
216
    }
217

    
218

    
219
    @GET
220
    @Path("/api/projects/count")
221
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
222
    public Response fetchProjectsCount(@QueryParam("q") String query){
223
        String fullQuery = builtQueryByEntity(query, RequestResponseHandler.Entity.PROJECT);
224
        return getCount(fullQuery);
225
    }
226

    
227
    @GET
228
    @Path("/api/projects/{projectid}")
229
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
230
    public Response fetchProjects(@PathParam("projectid") String projectid) {
231
        return getResponseByEntityId(RequestResponseHandler.Entity.PROJECT, projectid);
232
    }
233

    
234
    @GET
235
    @Path("/api/projects/{projectId}/publications")
236
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
237
    public Response fetchProjectPublications(@PathParam("projectId") String projectId,
238
                                             @DefaultValue("1") @QueryParam("page") int offset,
239
                                             @DefaultValue("10") @QueryParam("size") int limit,
240
                                             @QueryParam("format") final String format,
241
                                             @Context HttpServletRequest request)  {
242

    
243
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.PUBLICATION, "relprojectid", projectId);
244
        return getResponseByEntity(fullQuery, RequestResponseHandler.Entity.PUBLICATION, offset, limit, format, request, false, null);
245
    }
246

    
247
    @GET
248
    @Path("/api/projects/{projectId}/publications/count")
249
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
250
    public Response fetchProjectPublicationsCount(@PathParam("projectId") String projectId) {
251
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.PUBLICATION, "relprojectid", projectId);
252
        return getCount(fullQuery);
253
    }
254

    
255
    @GET
256
    @Path("/api/projects/{projectId}/datasets")
257
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
258
    public Response fetchProjectDatasets(@PathParam("projectId") String projectId,
259
                                             @DefaultValue("1") @QueryParam("page") int offset,
260
                                             @DefaultValue("10") @QueryParam("size") int limit,
261
                                             @QueryParam("format") final String format,
262
                                             @Context HttpServletRequest request)  {
263

    
264
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.DATASET, "relprojectid", projectId);
265
        return getResponseByEntity(fullQuery, RequestResponseHandler.Entity.DATASET, offset, limit, format, request, false, null);
266
    }
267

    
268
    @GET
269
    @Path("/api/projects/{projectId}/datasets/count")
270
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
271
    public Response fetchProjectDatasetsCount(@PathParam("projectId") String projectId,
272
                                         @DefaultValue("1") @QueryParam("page") int offset,
273
                                         @DefaultValue("10") @QueryParam("size") int limit,
274
                                         @Context HttpServletRequest request)  {
275
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.DATASET, "relprojectid", projectId);
276
        return getCount(fullQuery);
277
    }
278

    
279

    
280

    
281
    @GET
282
    @Path("/api/datasources")
283
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
284
    public Response fetchDatasources(@QueryParam("q") List<String> keywords,
285
                                     @QueryParam("op") final List<String> keywordOperators,
286
                                     @DefaultValue("1") @QueryParam("page") final int offset,
287
                                     @DefaultValue("10") @QueryParam("size") final int limit,
288
                                     @QueryParam("refine") @DefaultValue("false") final boolean refine,
289
                                     @QueryParam("fields") final List<String> fields,
290
                                     @QueryParam("format") final String format,
291
                                     @Context final HttpServletRequest request)  {
292

    
293
        String fullQuery = builtFullQuery(keywords, keywordOperators, RequestResponseHandler.Entity.DATASOURCE, request);
294
        return getResponseByEntity(fullQuery, RequestResponseHandler.Entity.DATASOURCE, offset, limit, format, request, refine, fields);
295
    }
296

    
297
    @GET
298
    @Path("/api/datasources/count")
299
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
300
    public Response fetchDatasourcesCount(@QueryParam("q") String query){
301
        String fullQuery = builtQueryByEntity(query, RequestResponseHandler.Entity.DATASOURCE);
302
        return getCount(fullQuery);
303
    }
304

    
305
    @GET
306
    @Path("/api/datasources/{datasourceid}")
307
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
308
    public Response fetchDatasources(@PathParam("datasourceid") String datasourceid)  {
309
        return getResponseByEntityId(RequestResponseHandler.Entity.DATASOURCE, datasourceid);
310
    }
311
*/
312
    /*
313
    @Path("/api/datasources/{datasourceid}/publications")
314
    @Path("/api/datasources/{datasourceid}/publications/count")
315
    Same for datasets.
316

    
317
    NOT supported by schema. No such field as *reldatasourceid*.
318
    To oercomethis collectedFrom and hostedBy are added in the other paths when needed
319

    
320
    */
321

    
322
/*
323
    @GET
324
    @Path("/api/organizations")
325
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
326
    public Response fetchOrganisations(@QueryParam("q") List<String> keywords,
327
                                       @QueryParam("op") final List<String> keywordOperators,
328
                                       @DefaultValue("1") @QueryParam("page") final int offset,
329
                                       @DefaultValue("10") @QueryParam("size") final int limit,
330
                                       @QueryParam("refine") @DefaultValue("false") final boolean refine,
331
                                       @QueryParam("fields") final List<String> fields,
332
                                       @QueryParam("format") final String format,
333
                                       @Context final HttpServletRequest request) {
334

    
335
        String fullQuery = builtFullQuery(keywords, keywordOperators, RequestResponseHandler.Entity.ORGANIZATION, request);
336
        return getResponseByEntity(fullQuery, RequestResponseHandler.Entity.ORGANIZATION, offset, limit, format, request, refine, fields);
337
    }
338

    
339

    
340
    @GET
341
    @Path("/api/organizations/count")
342
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
343
    public Response fetchOrganizationsCount(@QueryParam("q") String query){
344
        String fullQuery = builtQueryByEntity(query, RequestResponseHandler.Entity.ORGANIZATION);
345
        return getCount(fullQuery);
346
    }
347

    
348
    @GET
349
    @Path("/api/organizations/{organizationid}")
350
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
351
    public Response fetchOrganizations(@PathParam("organizationid") String organizationid) {
352
        return getResponseByEntityId(RequestResponseHandler.Entity.ORGANIZATION, organizationid);
353
    }
354

    
355
    @GET
356
    @Path("/api/organizations/{organizationid}/datasources")
357
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
358
    public Response fetchOrganizationDatasources(@PathParam("organizationid") String organizationid,
359
                                                 @DefaultValue("1") @QueryParam("page") int offset,
360
                                                 @DefaultValue("10") @QueryParam("size") int limit,
361
                                                 @QueryParam("format") final String format,
362
                                                 @Context HttpServletRequest request)  {
363
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.DATASOURCE, "relorganizationid", organizationid);
364
        return getResponseByEntity(fullQuery, RequestResponseHandler.Entity.DATASOURCE, offset, limit, format, request, false, null);
365
    }
366

    
367
    @GET
368
    @Path("/api/organizations/{organizationid}/datasources/count")
369
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
370
    public Response fetchOrganizationDatasources(@PathParam("organizationid") String organizationid)  {
371
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.DATASOURCE, "relorganizationid", organizationid);
372
        return getCount(fullQuery);
373
    }
374

    
375

    
376
    @GET
377
    @Path("/api/organizations/{organizationid}/projects")
378
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
379
    public Response fetchOrganizationProjects(@PathParam("organizationid") String organizationid,
380
                                                 @DefaultValue("1") @QueryParam("page") int offset,
381
                                                 @DefaultValue("10") @QueryParam("size") int limit,
382
                                                 @QueryParam("format") final String format,
383
                                                 @Context HttpServletRequest request)  {
384
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.PROJECT, "relprojectid", organizationid);
385
        return getResponseByEntity(fullQuery, RequestResponseHandler.Entity.PROJECT, offset, limit, format, request, false, null);
386
    }
387

    
388
    @GET
389
    @Path("/api/organizations/{organizationid}/projects/count")
390
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
391
    public Response fetchOrganizationProjectsCount(@PathParam("organizationid") String organizationid)  {
392
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.PROJECT, "relprojectid", organizationid);
393
        return getCount(fullQuery);
394
    }
395

    
396

    
397

    
398
    @GET
399
    @Path("/api/people")
400
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
401
    public Response fetchPeople(@QueryParam("q") List<String> keywords,
402
                                @QueryParam("op") final List<String> keywordOperators,
403
                                @DefaultValue("1") @QueryParam("page") final int offset,
404
                                @DefaultValue("10") @QueryParam("size") final int limit,
405
                                @QueryParam("refine") @DefaultValue("false") final boolean refine,
406
                                @QueryParam("fields") final List<String> fields,
407
                                @QueryParam("format") final String format,
408
                                @Context final HttpServletRequest request) {
409

    
410
        String fullQuery = builtFullQuery(keywords, keywordOperators, RequestResponseHandler.Entity.PERSON, request);
411
        return getResponseByEntity(fullQuery, RequestResponseHandler.Entity.PERSON, offset, limit, format, request, refine, fields);
412
    }
413

    
414

    
415
    @GET
416
    @Path("/api/people/count")
417
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
418
    public Response fetchPeopleCount(@QueryParam("q") String query){
419
        String fullQuery = builtQueryByEntity(query, RequestResponseHandler.Entity.PERSON);
420
        return getCount(fullQuery);
421
    }
422

    
423
    @GET
424
    @Path("/api/people/{personid}")
425
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
426
    public Response fetchPeople(@PathParam("personid") String personid) {
427
        return getResponseByEntityId(RequestResponseHandler.Entity.PERSON, personid);
428
    }
429

    
430
    @GET
431
    @Path("/api/people/{personid}/publications")
432
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
433
    public Response fetchPeoplePublications(@PathParam("personid") String personid,
434
                                            @DefaultValue("1") @QueryParam("page") final int offset,
435
                                            @DefaultValue("10") @QueryParam("size") final int limit,
436
                                            @QueryParam("format") final String format,
437
                                            @Context final HttpServletRequest request) {
438
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.PUBLICATION, "relpersonid", personid);
439
        return getResponseByEntity(fullQuery, RequestResponseHandler.Entity.PUBLICATION, offset, limit, format, request, false, null);
440
    }
441

    
442
    @GET
443
    @Path("/api/people/{personid}/publications/count")
444
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
445
    public Response fetchPeoplePublicationsCount(@PathParam("personid") String personid) {
446
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.PUBLICATION, "relpersonid", personid);
447
        return getCount(fullQuery);
448
    }
449

    
450

    
451
    @GET
452
    @Path("/api/people/{personid}/datasets")
453
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
454
    public Response fetchPeopleDatasets(@PathParam("personid") String personid,
455
                                        @DefaultValue("1") @QueryParam("page") final int offset,
456
                                        @DefaultValue("10") @QueryParam("size") final int limit,
457
                                        @QueryParam("format") final String format,
458
                                        @Context final HttpServletRequest request) {
459
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.DATASET, "relpersonid", personid);
460
        return getResponseByEntity(fullQuery, RequestResponseHandler.Entity.DATASET, offset, limit, format, request, false, null);
461
    }
462

    
463
    @GET
464
    @Path("/api/people/{personid}/datasets/count")
465
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
466
    public Response fetchPeopleDatasetsCount(@PathParam("personid") String personid) {
467
        String fullQuery = builtEntity2EntityRelationQuery(RequestResponseHandler.Entity.DATASET, "relpersonid", personid);
468
        return getCount(fullQuery);
469
    }
470

    
471
    private String enhanceQuery(List<String> keywords, List<String> keywordOperators, Map<String, String[]> operatorTypeValues, Map<String, String[]> parameterTypeValues, RequestResponseHandler.Entity entity) {
472
        StringBuilder queryBuilder = new StringBuilder();
473

    
474
        //There is always an entity
475
        enhanceQueryWithEntityType(queryBuilder, entity);
476

    
477
        enhanceQueryWithKeywords(queryBuilder, keywordOperators, keywords);
478

    
479
        Map<String, String> parameterIndexMap = entity.getParameterIndexMap();
480
        Map<String, String> parameterOperatorMap = entity.getParameterOperatorMap();
481
        enhanceQueryWithParameters(queryBuilder, operatorTypeValues, parameterTypeValues, parameterIndexMap, parameterOperatorMap);
482

    
483
        return queryBuilder.toString();
484
    }
485
*/
486
    @Deprecated
487
    private void enhanceQueryWithKeywords(StringBuilder queryBuilder, List<String> keywordOperators, List<String> keywords) {
488
        if (keywordOperators != null && !keywordOperators.isEmpty()) {
489
            if (keywords != null && !keywords.isEmpty()) {
490
                if (keywordOperators.size() != keywords.size()) {
491
                    throw new IllegalArgumentException("Keywords and Operators are not matched");
492
                }
493
            } else {
494
                throw new IllegalArgumentException("Keywords and Operators are not matched");
495
            }
496
        }
497

    
498
        for(int i = 0; i < keywords.size(); i++) {
499
            queryBuilder.append(' ').append(keywordOperators.get(i)).append(' ').append('(').append(keywords.get(i)).append(")");
500
        }
501
    }
502

    
503
    private void enhanceQueryWithParameters(StringBuilder queryBuilder, Map<String, String[]> operators, Map<String, String[]> parameters, Map<String, String> parameterIndexMap, Map<String, String> parameterOperatorMap) {
504
        if (parameterIndexMap != null && !parameterIndexMap.isEmpty()) {
505
            if (parameterOperatorMap != null && !parameterOperatorMap.isEmpty()) {
506
                for(String operatorType:operators.keySet()) {
507
                    //enhance messages with >, < ?? or maybe move all checks in the beginning?
508
                    if (operators.get(operatorType).length != parameters.get(parameterOperatorMap.get(operatorType)).length ) {
509
                        throw new IllegalArgumentException("Parameters and Operators are not matched");
510
                    }
511

    
512
                    String parameterName = parameterOperatorMap.get(operatorType);
513

    
514
                    for(int i = 0; i < operators.get(operatorType).length; i++) {
515
                        String indexField = parameterIndexMap.get(parameterOperatorMap.get(operatorType));
516

    
517
                        /*logger.debug("operator " + operatorType);
518
                        logger.debug("operator map get" + parameterOperatorMap.get(operatorType));
519

    
520
                        logger.debug("index map" + parameterIndexMap.keySet());
521
                        logger.debug("index map values" + parameterIndexMap.values());
522

    
523
                        logger.debug("index field " + indexField);*/
524

    
525
                        if (indexField != null) {
526
/*                          logger.debug(indexField + " " + operators.get(operatorType)[i] + " " + parameters.get(parameterName)[i]);*/
527
                            queryBuilder.append(' ').append(operators.get(operatorType)[i]).append('(').append(indexField).append(" = ").append(parameters.get(parameterName)[i]).append(")");
528

    
529
                        } else { //TODO check if needed
530
                            logger.debug("and here!");
531
                            logger.debug(" " + operators.get(operatorType)[i] + " " + parameters.get(operatorType)[i]);
532
                            queryBuilder.append(" " + operators.get(operatorType)[i] + " " + parameters.get(operatorType)[i]);
533
                        }
534
                    }
535
                }
536
            } else  {
537
                throw new IllegalArgumentException("Keywords and Operators are not matched");
538
            }
539

    
540
        }
541
    }
542

    
543
    /*
544
    private boolean isFirstTerm(StringBuilder queryBuilder) {
545
        return queryBuilder.toString().trim().equals("");
546
    }*/
547

    
548
    public void builtEntityIdQuery(StringBuilder queryBuilder, RequestResponseHandler.Entity entity, String entityId){
549
        enhanceQueryWithEntityType(queryBuilder, entity);
550
        enhanceQueryWithEntityId(queryBuilder, entityId);
551
    }
552

    
553
    public String builtEntity2EntityRelationQuery(RequestResponseHandler.Entity entity, String relationfield, String entityId){
554
        StringBuilder queryBuilder = new StringBuilder();
555
        enhanceQueryWithEntityType(queryBuilder, entity);
556
        enhanceQueryWithEntity2EntityId(queryBuilder, relationfield, entityId);
557
        return queryBuilder.toString();
558
    }
559

    
560
    private void enhanceQueryWithEntity2EntityId(StringBuilder queryBuilder, String relationfield, String entityId) {
561
        CQLQueryGeneration.appendTerm(queryBuilder, CQLQueryGeneration.Operator.AND, " " + relationfield + " ", CQLQueryGeneration.Operator.EXACT, entityId);
562
    }
563

    
564

    
565
    public void enhanceQueryWithEntityType(StringBuilder queryBuilder, RequestResponseHandler.Entity entity) {
566
        queryBuilder.append(entity.getQueryPrefix());
567
    }
568

    
569
    public void enhanceQueryWithEntityId(StringBuilder queryBuilder, String entityId) {
570
        CQLQueryGeneration.appendTerm(queryBuilder, CQLQueryGeneration.Operator.AND, "objidentifier", CQLQueryGeneration.Operator.EXACT, entityId);
571
    }
572

    
573
    public String builtQueryByEntity(String query, RequestResponseHandler.Entity entity) {
574
        StringBuilder queryBuilder = new StringBuilder();
575
        queryBuilder.append(entity.getQueryPrefix());
576

    
577
        if (query != null && !query.trim().isEmpty()) {
578
            CQLQueryGeneration.appendSimpleTerm(queryBuilder, CQLQueryGeneration.Operator.AND, "(" + query + ")");
579
        }
580

    
581
        return queryBuilder.toString();
582
    }
583

    
584
    public void extractParameterNOperatorsValues(Map<String, String[]> parameterMap, Map<String, String[]> operatorTypeValues, Map<String, String[]> parameterTypeValues, RequestResponseHandler.Entity entity) {
585
        for (String parameter:parameterMap.keySet()) {
586
            Map<String, String> parameterIndexMap = entity.getParameterIndexMap();
587
            Map<String, String> parameterOperatorMap = entity.getParameterOperatorMap();
588

    
589
            if (parameterOperatorMap.get(parameter) != null) {
590
                operatorTypeValues.put(parameter, parameterMap.get(parameter));
591

    
592
            } else if (parameterIndexMap.get(parameter) != null) {
593
                parameterTypeValues.put(parameter, parameterMap.get(parameter));
594

    
595
            } else if (!parameter.equals("q") && !parameter.equals("op") && !parameter.equals("size") && !parameter.equals("page") && !parameter.equals("fields") && !parameter.equals("refine")){
596
                throw new IllegalArgumentException("The parameter " + parameter + " is not supported.");
597
            }
598

    
599
            if (parameterTypeValues.get(parameter) == null) {
600
                logger.debug("parameterTypeValues is null");
601
            } else {
602
                logger.debug("parameterTypeValues " + Arrays.asList(parameterTypeValues.get(parameter)));
603
            }
604

    
605
        }
606

    
607
        //TODO make checks per type????
608
        if (operatorTypeValues.size() != parameterTypeValues.size()) {
609
            throw new IllegalArgumentException("Parameters and Operators do not match.");
610
        }
611
    }
612
/*
613
    *//* For each parameter get the values and the operators *//*
614
    public void extractParameterOperatorsNValues(Map<String, String[]> requestParameterMap, Map<String, String[]> keywordOperatorValueMap, Map<String, String[]> keywordValuesMap,
615
                                                 Map<String, String[]> operatorValueMap, Map<String, String[]> parameterValuesMap, RequestResponseHandler.Entity entity) {
616

    
617
        for (String parameter:requestParameterMap.keySet()) {
618
            Map<String, String> parameterIndexMap = entity.getParameterIndexMap();
619
            Map<String, String> parameterOperatoMap = entity.getParameterOperatorMap();
620

    
621
            if (parameterOperatoMap.get(parameter) != null) {
622
                operatorValueMap.put(parameter, requestParameterMap.get(parameter));
623

    
624
            } else if (parameterIndexMap.get(parameter) != null) {
625
                parameterValuesMap.put(parameter, requestParameterMap.get(parameter));
626

    
627
            } else if (parameter.equals("q")) {
628
                keywordValuesMap.put("q", requestParameterMap.get("q"));
629

    
630
            } else if (parameter.equals("op")) {
631
                keywordOperatorValueMap.put("op", requestParameterMap.get("op"));
632

    
633
            } else if (!parameter.equals("size") && !parameter.equals("page") && !parameter.equals("fields") && !parameter.equals("refine")){
634
                throw new IllegalArgumentException("The parameter " + parameter + " is not supported.");
635
            }
636

    
637
            if (parameterValuesMap.get(parameter) == null) {
638
                logger.debug("parameterTypeValues is null");
639
            } else {
640
                logger.debug("parameterTypeValues " + Arrays.asList(parameterValuesMap.get(parameter)));
641
            }
642
        }
643

    
644
        if ((operatorValueMap.size() != parameterValuesMap.size()) || (keywordOperatorValueMap.size() != keywordValuesMap.size())) {
645
            throw new IllegalArgumentException("Operators do not match parameters.");
646
        }
647
    }*/
648

    
649
    private Response getCount(String query) {
650
        try {
651
            SearchResult searchResult = searchService.search(query, null, Locale.getDefault().toString(), 0, 0);
652
            return Response.status(Response.Status.OK).entity(ResponseFormatter.createCountMeta(query.replace("\"", "\\\""), searchResult.getTotal())).build();
653

    
654
        } catch (SearchServiceException sse) {
655
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ResponseFormatter.compose500Message("Fail to fetch count for query " + query.replace("\"", "\\\"") + ".", sse.getMessage())).build();
656
        }
657
    }
658

    
659
    /* TODO remove?
660
    private Response getCountByEntity2EntityRelation(String query, RequestResponseHandler.Entity entity, String relationfield, String entityId) {
661
        String fullQuery =  builtEntity2EntityRelationQuery(entity, relationfield, entityId);
662

    
663
        try {
664
            SearchResult searchResult = searchService.search(fullQuery, null, Locale.getDefault().toString(), 0, 0);
665
            return Response.status(Response.Status.OK).entity(ResponseFormatter.createCountMeta(fullQuery.replace("\"", "\\\""), searchResult.getTotal())).build();
666

    
667
        } catch (SearchServiceException sse) {
668
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ResponseFormatter.compose500Message("Fail to fetch count for query " + fullQuery.replace("\"", "\\\"") + ".", sse.getMessage())).build();
669
        }
670
    } */
671

    
672
    private Response getResponseByEntityId(RequestResponseHandler.Entity entity, String entityId) {
673
        try {
674
            StringBuilder queryBuilder = new StringBuilder();
675
            builtEntityIdQuery(queryBuilder, entity, entityId);
676
            String fullQuery = queryBuilder.toString();
677

    
678
            SearchResult searchResult = searchService.search(fullQuery, null, Locale.getDefault().toString(), 1, 1);
679

    
680
            if (searchResult.getSearchResults() == null || searchResult.getSearchResults().isEmpty() ||
681
                    searchResult.getSearchResults().size() == 0 || searchResult.getSearchResults().get(0) == null) {
682
                return Response.status(Response.Status.NOT_FOUND).entity(
683
                        ResponseFormatter.compose404Message("404 - " + entity +" with id "
684
                                + entityId + " not found.")).type(MediaType.APPLICATION_JSON).build();
685
            }
686

    
687
            return Response.status(Response.Status.OK).entity(ResponseFormatter.createEntityResponse(entity, XML.toJSONObject(searchResult.getSearchResults().get(0)).toString())).type(MediaType.APPLICATION_JSON).build();
688

    
689
        } catch (SearchServiceException sse) {
690
            logger.error("Fail to fetch "+ entity + " with id " + entityId, sse);
691
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ResponseFormatter.compose500Message("Fail to fetch " + entity + " with id " + entityId, sse.getMessage())).build();
692
        }
693
    }
694

    
695
    private Response getResponseByEntity(String fullQuery, RequestResponseHandler.Entity entity, int offset, int limit, String format, HttpServletRequest request, boolean refine, List<String> refineFields, List<String> fieldQueries) {
696
        try {
697

    
698
            SearchResult solrResults = searchService.newSearch(fullQuery, Locale.getDefault().toString(), refineFields, fieldQueries, offset, limit, format);
699

    
700
            return Response.status(Response.Status.OK).entity(ResponseFormatter.createEntitiesResponse(request, entity, fullQuery.replace("\"", "\\\""),
701
                    solrResults.getSearchResults().toString(), solrResults.getTotal()+"", offset+"", limit+"", refine, SolrResultsFormatter.jsonList2Json(solrResults.getBrowseResults()))).type(MediaType.APPLICATION_JSON).build();
702

    
703
        } catch (SearchServiceException sse) {
704
            logger.error("Fail to get " + entity.getPlural() , sse);
705
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).
706
                    entity(ResponseFormatter.compose500Message("Fail to fetch " + entity.getPlural(), sse.getMessage())).type(MediaType.APPLICATION_JSON).build();
707
        }
708
    }
709

    
710
    private void formatRefineResults(StringBuilder refineBuilder, SearchResult refineResults) {
711
        int i = 0;
712
        for (String json: refineResults.getBrowseResults()) {
713
            if (i == (refineResults.getBrowseResults().size() - 1)) {
714
                refineBuilder.append(json);
715
            } else {
716
                refineBuilder.append(json).append(",");
717
            }
718
            i++;
719
        }
720
    }
721

    
722

    
723
/*
724
    public static void main(String[] args) {
725
        String json = " {\"result\":{\"xmlns:oaf\":\"http://namespace.openaire.eu/oaf\",\"xmlns:xsi\":\"http://www.w3.o" +
726
                "rg/2001/XMLSchema-instance\",\"header\":{\"dri:dateOfCollection\":\"2016-05-20T03:34:07Z\",\"dri:dateOfTransformation\":\"\",\"counters\":{\"counter_dedup\":{\"value\":2},\"counter_doi\":{\"value\":2},\"counter_authorship\":{\"va" +
727
                "lue\":1},\"counter_authorship_inferred\":{\"value\":1}},\"dri:objIdentifier\":\"dedup_wf_001::0f5604702b32f59d9789573113279e69\"},\"metadata\":{\"oaf:entity\":{\"oaf:result\":{\"datainfo\":{\"provenanceaction\":{\"schemename\"" +
728
                ":\"dnet:provenanceActions\",\"classname\":\"sysimport:dedup\",\"schemeid\":\"dnet:provenanceActions\",\"classid\":\"sysimport:dedup\"},\"trust\":0.9,\"inferenceprovenance\":\"dedup-similarity-result\",\"deletedbyinference\":fal" +
729
                "se,\"inferred\":true},\"rels\":{\"rel\":{\"to\":{\"content\":\"dedup_wf_001::884d8c367553a8de98ec90ece1b1be4a\",\"scheme\":\"dnet:person_result_relations\",\"class\":\"hasAuthor\",\"type\":\"person\"},\"provenanceaction\":\"sysimpor" +
730
                "t:crosswalk:repository\",\"trust\":0.9,\"inferenceprovenance\":\"\",\"ranking\":1,\"inferred\":true,\"fullname\":\"Krafft, Alexander\"}},\"subject\":[{\"content\":\"Clinic for Obstetrics\",\"schemename\":\"dnet:result_subject\",\"c" +
731
                "lassname\":\"keyword\",\"schemeid\":\"dnet:result_subject\",\"classid\":\"keyword\"},{\"content\":\"610 Medicine & health\",\"schemename\":\"dnet:result_subject\",\"classname\":\"keyword\",\"schemeid\":\"dnet:result_subject\",\"class" +
732
                "id\":\"keyword\"},{\"content\":\"News\",\"schemename\":\"dnet:result_subject\",\"classname\":\"keyword\",\"schemeid\":\"dnet:result_subject\",\"classid\":\"keyword\"}],\"collectedfrom\":[{\"id\":\"opendoar____::0efe32849d230d7f53049d" +
733
                "dc4a4b0c60\",\"name\":\"Zurich Open Repository and Archive\"},{\"id\":\"opendoar____::8b6dd7db9af49e67306feb59a8bdc52c\",\"name\":\"Europe PubMed Central\"}],\"children\":{\"result\":[{\"title\":{\"content\":\"Iron supplementat" +
734
                "ion in pregnancy\",\"schemename\":\"dnet:dataCite_title\",\"classname\":\"main title\",\"schemeid\":\"dnet:dataCite_title\",\"classid\":\"main title\"},\"resulttype\":{\"schemename\":\"dnet:result_typologies\",\"classname\":\"publi" +
735
                "cation\",\"schemeid\":\"dnet:result_typologies\",\"classid\":\"publication\"},\"dateofacceptance\":\"1981-09-01\",\"objidentifier\":\"od_______908::f27f9e68f0b9f510ebf572ba295344e1\"},{\"title\":{\"content\":\"Iron supplementat" +
736
                "ion in pregnancy\",\"schemename\":\"dnet:dataCite_title\",\"classname\":\"main title\",\"schemeid\":\"dnet:dataCite_title\",\"classid\":\"main title\"},\"resulttype\":{\"schemename\":\"dnet:result_typologies\",\"classname\":\"publi" +
737
                "cation\",\"schemeid\":\"dnet:result_typologies\",\"classid\":\"publication\"},\"dateofacceptance\":\"2013-01-01\",\"publisher\":\"BMJ Publishing Group\",\"objidentifier\":\"od_______885::0f5604702b32f59d9789573113279e69\"}],\"i" +
738
                "nstance\":[{\"webresource\":{\"url\":\"http://europepmc.org/articles/PMC2306130\"},\"id\":\"opendoar____::8b6dd7db9af49e67306feb59a8bdc52c\",\"licence\":{\"schemename\":\"dnet:access_modes\",\"classname\":\"Open Access\",\"sche" +
739
                "meid\":\"dnet:access_modes\",\"classid\":\"OPEN\"},\"hostedby\":{\"id\":\"opendoar____::8b6dd7db9af49e67306feb59a8bdc52c\",\"name\":\"Europe PubMed Central\"},\"instancetype\":{\"schemename\":\"dnet:publication_resource\",\"class" +
740
                "name\":\"Article\",\"schemeid\":\"dnet:publication_resource\",\"classid\":\"0001\"}},{\"webresource\":{\"url\":\"http://www.zora.uzh.ch/87059/1/30_13_Krafft_2013bmj_f4399_full.pdf\"},\"id\":\"opendoar____::0efe32849d230d7f530" +
741
                "49ddc4a4b0c60\",\"licence\":{\"schemename\":\"dnet:access_modes\",\"classname\":\"Open Access\",\"schemeid\":\"dnet:access_modes\",\"classid\":\"OPEN\"},\"hostedby\":{\"id\":\"opendoar____::0efe32849d230d7f53049ddc4a4b0c60\",\"name" +
742
                "\":\"Zurich Open Repository and Archive\"},\"instancetype\":{\"schemename\":\"dnet:publication_resource\",\"classname\":\"Article\",\"schemeid\":\"dnet:publication_resource\",\"classid\":\"0001\"}}]},\"pid\":[{\"content\":\"10.5167" +
743
                "/uzh-87059\",\"schemename\":\"dnet:pid_types\",\"classname\":\"doi\",\"schemeid\":\"dnet:pid_types\",\"classid\":\"doi\"},{\"content\":\"PMC2306130\",\"schemename\":\"dnet:pid_types\",\"classname\":\"pmc\",\"schemeid\":\"dnet:pid_types\"," +
744
                "\"classid\":\"pmc\"},{\"content\":\"10.1136/bmj.f4399\",\"schemename\":\"dnet:pid_types\",\"classname\":\"doi\",\"schemeid\":\"dnet:pid_types\",\"classid\":\"doi\"}],\"resourcetype\":{\"schemename\":\"\",\"classname\":\"\",\"schemeid\":\"\",\"c" +
745
                "lassid\":\"\"},\"format\":\"\",\"dateofacceptance\":\"2013-01-01\",\"embargoenddate\":\"\",\"version\":\"\",\"size\":\"\",\"publisher\":\"BMJ Publishing Group\",\"country\":{\"schemename\":\"\",\"classname\":\"\",\"schemeid\":\"\",\"classid\":\"\"},\"" +
746
                "metadataversionnumber\":\"\",\"title\":{\"content\":\"Iron supplementation in pregnancy\",\"schemename\":\"dnet:dataCite_title\",\"classname\":\"main title\",\"schemeid\":\"dnet:dataCite_title\",\"classid\":\"main title\"},\"result" +
747
                "type\":{\"schemename\":\"dnet:result_typologies\",\"classname\":\"publication\",\"schemeid\":\"dnet:result_typologies\",\"classid\":\"publication\"},\"source\":\"Krafft, Alexander (2013). Iron supplementation in pregnancy. Br" +
748
                "itish Medical Journal, 347:f4399.\",\"contributor\":\"\",\"description\":\"\",\"originalId\":[\"oai:europepmc.org:1052305\",\"oai:www.zora.uzh.ch:87059\"],\"lastmetadataupdate\":\"\",\"relevantdate\":{\"schemename\":\"\",\"classnam" +
749
                "e\":\"\",\"schemeid\":\"\",\"classid\":\"\"},\"device\":\"\",\"bestlicense\":{\"schemename\":\"dnet:access_modes\",\"classname\":\"Open Access\",\"schemeid\":\"dnet:access_modes\",\"classid\":\"OPEN\"},\"language\":{\"schemename\":\"dnet:langu" +
750
                "ages\",\"classname\":\"English\",\"schemeid\":\"dnet:languages\",\"classid\":\"eng\"},\"storagedate\":\"\",\"fulltext\":\"\"},\"xsi:schemaLocation\":\"http://namespace.openaire.eu/oaf https://www.openaire.eu/schema/0.2/oaf-0.2.xs" +
751
                "d\"}},\"xmlns:dri\":\"http://www.driver-repository.eu/namespace/dri\"}}";
752

    
753
        String s = "{\"result\":{\"xmlns:oaf\":\"http://namespace.openaire.eu/oaf\",\"xmlns:xsi\":\"http://www.w3.org/2001" +
754
                "/XMLSchema-instance\",\"header\":{\"dri:dateOfCollection\":\"2014-04-10T13:35:33Z\",\"dri:dateOfTransformation\":\"\",\"counters\":{\"counter_dedup\":{\"value\":2},\"counter_authorship\":{\"value\":1},\"counter_authorship_infer" +
755
                "red\":{\"value\":1}},\"dri:objIdentifier\":\"dedup_wf_001::4d934888dee33a62dece6fa36192c710\"},\"metadata\":{\"oaf:entity\":{\"oaf:result\":{\"datainfo\":{\"provenanceaction\":{\"schemename\":\"dnet:provenanceActions\",\"classn" +
756
                "ame\":\"sysimport:dedup\",\"schemeid\":\"dnet:provenanceActions\",\"classid\":\"sysimport:dedup\"},\"trust\":0.9,\"inferenceprovenance\":\"dedup-similarity-result\",\"deletedbyinference\":false,\"inferred\":true},\"rels\":{\"rel\"" +
757
                ":{\"to\":{\"content\":\"od______1232::d4f9cea02c7762da24cd71ea0b9791de\",\"scheme\":\"dnet:person_result_relations\",\"class\":\"hasAuthor\",\"type\":\"person\"},\"provenanceaction\":\"sysimport:crosswalk:repository\",\"trust\":0" +
758
                ".9,\"inferenceprovenance\":\"\",\"ranking\":1,\"inferred\":true,\"fullname\":\"Anonymous\"}},\"subject\":{\"content\":\"Señoríos-Legislación\",\"schemename\":\"dnet:result_subject\",\"classname\":\"keyword\",\"schemeid\":\"dnet:result" +
759
                "_subject\",\"classid\":\"keyword\"},\"collectedfrom\":[{\"id\":\"opendoar____::e53a0a2978c28872a4505bdb51db06dc\",\"name\":\"Biblioteca Virtual del Patrimonio Bibliográfico (Virtual Library of Bibliographical Heritage)\"" +
760
                "},{\"id\":\"opendoar____::7aee26c309def8c5a2a076eb250b8f36\",\"name\":\"Biblioteca Virtual de Aragón\"}],\"children\":{\"result\":[{\"title\":{\"content\":\"Discurso sobre los señoríos : necesidad y justicia del decreto de" +
761
                " Cortes de 6 de Agosto de 1811 y ventaja que debe causar a la Nación\",\"schemename\":\"dnet:dataCite_title\",\"classname\":\"main title\",\"schemeid\":\"dnet:dataCite_title\",\"classid\":\"main title\"},\"resulttype\":{\"sch" +
762
                "emename\":\"dnet:result_typologies\",\"classname\":\"publication\",\"schemeid\":\"dnet:result_typologies\",\"classid\":\"publication\"},\"dateofacceptance\":\"1820-01-01\",\"objidentifier\":\"od______2719::bc2326a31763719dc5ebd" +
763
                "38f16a25404\"},{\"title\":{\"content\":\"Discurso sobre los señoríos : necesidad y justicia del decreto de Cortes de 6 de Agosto de 1811 y ventaja que debe causar a la Nación\",\"schemename\":\"dnet:dataCite_title\"," +
764
                "\"classname\":\"main title\",\"schemeid\":\"dnet:dataCite_title\",\"classid\":\"main title\"},\"resulttype\":{\"schemename\":\"dnet:result_typologies\",\"classname\":\"publication\",\"schemeid\":\"dnet:result_typologies\",\"classid\"" +
765
                ":\"publication\"},\"dateofacceptance\":\"1820-01-01\",\"objidentifier\":\"od______1232::4d934888dee33a62dece6fa36192c710\"}],\"instance\":[{\"webresource\":[{\"url\":\"http://bvpb.mcu.es/es/consulta/registro.cmd?id=403864\"" +
766
                "},{\"url\":\"http://bvpb.mcu.es/es/catalogo_imagenes/grupo.cmd?path=2755\"}],\"id\":\"opendoar____::e53a0a2978c28872a4505bdb51db06dc\",\"licence\":{\"schemename\":\"dnet:access_modes\",\"classname\":\"Open Access\",\"schemei" +
767
                "d\":\"dnet:access_modes\",\"classid\":\"OPEN\"},\"hostedby\":{\"id\":\"opendoar____::e53a0a2978c28872a4505bdb51db06dc\",\"name\":\"Biblioteca Virtual del Patrimonio Bibliográfico (Virtual Library of Bibliographical Herita" +
768
                "ge)\"},\"instancetype\":{\"schemename\":\"dnet:publication_resource\",\"classname\":\"Book\",\"schemeid\":\"dnet:publication_resource\",\"classid\":\"0002\"}},{\"webresource\":{\"url\":\"http://bibliotecavirtual.aragon.es/bva/i18" +
769
                "n/consulta/registro.cmd?id=2878\"},\"id\":\"opendoar____::7aee26c309def8c5a2a076eb250b8f36\",\"licence\":{\"schemename\":\"dnet:access_modes\",\"classname\":\"Open Access\",\"schemeid\":\"dnet:access_modes\",\"classid\":\"OPEN\"" +
770
                "},\"hostedby\":{\"id\":\"opendoar____::7aee26c309def8c5a2a076eb250b8f36\",\"name\":\"Biblioteca Virtual de Aragón\"},\"instancetype\":{\"schemename\":\"dnet:publication_resource\",\"classname\":\"Book\",\"schemeid\":\"dnet:publi" +
771
                "cation_resource\",\"classid\":\"0002\"}}]},\"pid\":{\"schemename\":\"\",\"classname\":\"\",\"schemeid\":\"\",\"classid\":\"\"},\"resourcetype\":{\"schemename\":\"\",\"classname\":\"\",\"schemeid\":\"\",\"classid\":\"\"},\"format\":\"\",\"dateofaccepta" +
772
                "nce\":\"1820-01-01\",\"embargoenddate\":\"\",\"version\":\"\",\"size\":\"\",\"country\":{\"schemename\":\"\",\"classname\":\"\",\"schemeid\":\"\",\"classid\":\"\"},\"publisher\":\"\",\"metadataversionnumber\":\"\",\"title\":{\"content\":\"Discurso sob" +
773
                "re los señoríos : necesidad y justicia del decreto de Cortes de 6 de Agosto de 1811 y ventaja que debe causar a la Nación\",\"schemename\":\"dnet:dataCite_title\",\"classname\":\"main title\",\"schemeid\":\"dnet:dataC" +
774
                "ite_title\",\"classid\":\"main title\"},\"resulttype\":{\"schemename\":\"dnet:result_typologies\",\"classname\":\"publication\",\"schemeid\":\"dnet:result_typologies\",\"classid\":\"publication\"},\"source\":\"\",\"contributor\":\"Impr" +
775
                "enta de Heras, imp.\",\"description\":\"\",\"originalId\":[\"oai:bvpb.mcu.es:403864\",\"oai:bibliotecavirtual.aragon.es:2878\"],\"lastmetadataupdate\":\"\",\"relevantdate\":{\"schemename\":\"\",\"classname\":\"\",\"schemeid\":\"\",\"cl" +
776
                "assid\":\"\"},\"device\":\"\",\"bestlicense\":{\"schemename\":\"dnet:access_modes\",\"classname\":\"Open Access\",\"schemeid\":\"dnet:access_modes\",\"classid\":\"OPEN\"},\"language\":{\"schemename\":\"dnet:languages\",\"classname\":\"Span" +
777
                "ish\",\"schemeid\":\"dnet:languages\",\"classid\":\"esl/spa\"},\"storagedate\":\"\",\"fulltext\":\"\"},\"xsi:schemaLocation\":\"http://namespace.openaire.eu/oaf https://www.openaire.eu/schema/0.2/oaf-0.2.xsd\"}},\"xmlns:dri\":\"h" +
778
                "ttp://www.driver-repository.eu/namespace/dri\"}}\n";
779

    
780
        JSONObject finalOject = new JSONObject();
781
        finalOject.put("dri:objIdentifier", new JSONObject(json).getJSONObject("result").getJSONObject("header").getString("dri:objIdentifier"));
782
        finalOject.put("content", new JSONObject(new JSONObject(json).getJSONObject("result").getJSONObject("metadata").getJSONObject("oaf:entity").getJSONObject("oaf:result"),
783
                new String[]{"title", "description", "language", "bestlicense", "pid", "rels"}));
784

    
785
        System.out.println(finalOject);
786

    
787
        JSONObject jsonObject = new JSONObject(s).getJSONObject("result").getJSONObject("metadata").getJSONObject("oaf:entity").getJSONObject("oaf:result");
788
        System.out.println("title --> " + jsonObject.getJSONObject("title").getString("content"));
789
        System.out.println("pid --> " + jsonObject.getJSONArray("pid"));
790

    
791
        JSONObject newJsonObject1 = new JSONObject(jsonObject, new String[]{"title", "description", "language", "bestlicense", "pid", "rels"});
792

    
793
    }
794
*/
795

    
796
    public static void main(String[] args) throws IOException, CQLParseException {
797
        CqlTranslator translator = new CqlTranslatorImpl();
798
        System.out.println(translator.toLucene("relfundinglevel0_id = ec__________::EC::FP7"));
799
    }
800

    
801
}
(6-6/8)