Project

General

Profile

1
package eu.dnetlib.data.search.utils.cql;
2

    
3
import eu.dnetlib.data.search.utils.vocabulary.VocabularyManager;
4
import eu.dnetlib.domain.enabling.Vocabulary;
5
import org.apache.log4j.Logger;
6

    
7
import javax.servlet.http.HttpServletRequest;
8
import java.text.ParseException;
9
import java.text.SimpleDateFormat;
10
import java.util.Date;
11
import java.util.Locale;
12

    
13
/**
14
 * Created by kiatrop on 10/7/2014.
15
 */
16
public class ParameterQueryEnhancer {
17

    
18
    private static final Logger logger = Logger.getLogger(ParameterQueryEnhancer.class);
19

    
20
    /**
21
     * Enhance the given CQL query with FP7 specific index fields
22
     */
23
    public static void enhanceQueryWithFundingLevelParams(StringBuilder queryBuilder, HttpServletRequest request, VocabularyManager vocabularyManager, boolean isModelSygma, String version) {
24
        logger.debug("enhance funding " + isModelSygma);
25
        
26
        String funder = request.getParameter("funder");
27
        String fundingStream = request.getParameter("fundingStream");
28
        String FP7scientificArea = request.getParameter("FP7scientificArea");
29

    
30
        if(isModelSygma) {
31
            if (version!=null && !version.equals("2")) {
32
                //TODO add version check and restrictions
33
            if (funder != null) {
34
                    if (!funder.equalsIgnoreCase("WT")) {
35
                    Vocabulary sygmaFundersVocabulary = vocabularyManager.getVocabulary("sygma_funders", Locale.ROOT);
36
                    addExactQueryTerm("relfundinglevel0_id", devocabularizedTerm(funder.toUpperCase(), sygmaFundersVocabulary), queryBuilder);
37
                } else {
38
                    Vocabulary funderVocabulary = vocabularyManager.getVocabulary("funders_simple", Locale.ROOT);
39
                    addExactQueryTerm("relfunderid", devocabularizedTerm(funder.toUpperCase(), funderVocabulary), queryBuilder);
40
                }
41
            }
42

    
43
            if (fundingStream != null && !fundingStream.trim().isEmpty()) {
44
                Vocabulary relfundinglevel1Vocabulary = vocabularyManager.getVocabulary("programmes_simple", Locale.ROOT);
45
                addVocabularizedQueryTerm("relfundinglevel1_id", fundingStream.toUpperCase(), relfundinglevel1Vocabulary, queryBuilder);
46
            }
47

    
48
            if (FP7scientificArea != null && !FP7scientificArea.trim().isEmpty()) {
49
                Vocabulary relfundinglevel2Vocabulary = vocabularyManager.getVocabulary("areas", Locale.ROOT);
50
                addVocabularizedQueryTerm("relfundinglevel2_id", FP7scientificArea, relfundinglevel2Vocabulary, queryBuilder);
51
                }
52
            } else if (version!= null && version.equals("2")){ //version 2 sygma model //a simple else can add EC funder in any case. do we need this? //TODO
53
                //Add funder to be EC
54
                addExactQueryTerm("relfundershortname", "EC", queryBuilder);
55
            }
56

    
57
        } else {
58

    
59
            if (funder != null) {
60
                //Vocabulary funderVocabulary = vocabularyManager.getVocabulary("funders_simple", Locale.ROOT);
61
                addExactQueryTerm("relfundershortname", funder.toUpperCase(), queryBuilder);
62
            }
63

    
64
            if (fundingStream != null && !fundingStream.trim().isEmpty()) {
65
                if(fundingStream.equalsIgnoreCase("FP7") || fundingStream.equalsIgnoreCase("H2020")) {
66
                    addORQueryTermExact(new String[]{"relfundinglevel0_name", "relfundinglevel1_name", "relfundinglevel2_name"}, "\"" + fundingStream.toUpperCase() + "\"", queryBuilder);
67
                } else {
68
                    addORQueryTermExact(new String[]{"relfundinglevel0_name", "relfundinglevel1_name", "relfundinglevel2_name"}, "\"" + fundingStream + "\"", queryBuilder);
69
                }
70
            }
71

    
72
            if (FP7scientificArea != null && !FP7scientificArea.trim().isEmpty()) {
73
                //Vocabulary relfundinglevel2Vocabulary = vocabularyManager.getVocabulary("areas", Locale.ROOT);
74
                queryBuilder.append(" and (relfundershortname exact \"EC\")").append(" and (relfundinglevel2_name exact \"").append(FP7scientificArea).append("\")");
75
            }
76
        }
77

    
78
    }
79

    
80
    public static void enhanceProjectQueryWithFundingLevelParams(StringBuilder queryBuilder, HttpServletRequest request, VocabularyManager vocabularyManager) {
81
        String funder = request.getParameter("funder");
82
        String fundingStream = request.getParameter("fundingStream");
83
        String FP7scientificArea = request.getParameter("FP7scientificArea");
84

    
85
        if (funder != null) {
86
            //addExactQueryTerm("fundinglevel0_name", funder.toUpperCase(), queryBuilder);
87
            //Vocabulary funderVocabulary = vocabularyManager.getVocabulary("funders_simple", Locale.ROOT);
88
            addExactQueryTerm("fundershortname", funder.toUpperCase(), queryBuilder);
89
        }
90

    
91
        if (fundingStream != null && !fundingStream.trim().isEmpty()) {
92
            //addExactQueryTerm("fundinglevel1_name", fundingStream.toUpperCase(), queryBuilder);
93
            if(fundingStream.equalsIgnoreCase("FP7") || fundingStream.equalsIgnoreCase("H2020")) {
94
                addORQueryTermExact(new String[]{"fundinglevel0_name", "fundinglevel1_name", "fundinglevel2_name"}, "\"" + fundingStream.toUpperCase() + "\"", queryBuilder);
95
            } else {
96
                addORQueryTermExact(new String[]{"fundinglevel0_name", "fundinglevel1_name", "fundinglevel2_name"}, "\"" + fundingStream + "\"", queryBuilder);
97
            }
98
        }
99

    
100
        if (FP7scientificArea != null && !FP7scientificArea.trim().isEmpty()) {
101
            //Vocabulary relfundinglevel2Vocabulary = vocabularyManager.getVocabulary("areas", Locale.ROOT);
102
            queryBuilder.append("and (fundershortname exact \"EC\")").append(" and (fundinglevel2_name exact \"").append(FP7scientificArea).append("\")");
103
        }
104
    }
105

    
106
    public static void enhanceQueryWithFundingParams(StringBuilder queryBuilder, HttpServletRequest request) {
107
        String hasECFunding = request.getParameter("hasECFunding");
108
        String hasWTFunding = request.getParameter("hasWTFunding");
109

    
110
        addBooleanQueryTerm("contextid", hasECFunding, "EC", queryBuilder);
111
        addBooleanQueryTerm("contextid", hasWTFunding, "WT", queryBuilder);
112
    }
113

    
114
    public static void enhanceQueryWithCommunityParams(StringBuilder queryBuilder, HttpServletRequest request) {
115
        String community = request.getParameter("community");
116

    
117
        if (community!= null) {
118
            addExactQueryTerm("communityId", community, queryBuilder);
119
        }
120

    
121
    }
122

    
123
    public static void enhanceQueryWithProjectFundingParams(StringBuilder queryBuilder, HttpServletRequest request) {
124
        String hasECFunding = request.getParameter("hasECFunding");
125
        String hasWTFunding = request.getParameter("hasWTFunding");
126

    
127
        addBooleanQueryTerm("funderid", hasECFunding, "ec__________::EC", queryBuilder);
128
        addBooleanQueryTerm("funderid", hasWTFunding, "wt__________::WT", queryBuilder);
129

    
130
    }
131

    
132
    public static void enhanceQueryWithRelProjectParams(StringBuilder queryBuilder, HttpServletRequest request) {
133
        String hasProject = request.getParameter("hasProject");
134
        String projectID = request.getParameter("projectID");
135
        String FP7ProjectID = request.getParameter("FP7ProjectID");
136

    
137
        if (hasProject != null && !hasProject.isEmpty()) {
138
            if (hasProject.equals("true")) {
139
                addEqualQueryTerm("relprojectid", "*", queryBuilder);
140
            } else {
141
                addNotEqualQueryTerm("relprojectid", "*", queryBuilder);
142
            }
143
        }
144

    
145
        if (FP7ProjectID != null && !FP7ProjectID.trim().isEmpty()) {
146
            addExactQueryTerm("relprojectcode", FP7ProjectID, queryBuilder);
147
            addExactQueryTerm(" relfundinglevel0_id", "ec__________::EC::FP7", queryBuilder);
148
        }
149

    
150
        if (projectID != null && !projectID.trim().isEmpty()) {
151
            queryBuilder.append(" and (relprojectcode exact \"").append(projectID).append("\")");
152
        }
153
    }
154

    
155
    public static void enhanceQueryWithClassifications(StringBuilder queryBuilder, HttpServletRequest request, VocabularyManager vocabularyManager) {
156
        String sdg = request.getParameter("sdg");
157

    
158
        if (sdg!= null && !sdg.trim().isEmpty()) {
159
            if (sdg.matches("[1-17]")){
160
                Vocabulary sdgVocabulary = vocabularyManager.getVocabulary("sdg", Locale.ROOT);
161
                addExactQueryTerm("sdg", devocabularizedTerm(sdg, sdgVocabulary), queryBuilder);
162
            }
163
        }
164

    
165
        String fos = request.getParameter("fos");
166
        if (fos!=null && !fos.trim().isEmpty()) {
167
            Vocabulary fosVocabulary = vocabularyManager.getVocabulary("fos", Locale.ROOT);
168
            addExactQueryTerm("fos", devocabularizedTerm(fos.toLowerCase(), fosVocabulary), queryBuilder);
169
        }
170
    }
171

    
172
    public static void enhanceQueryWithAccessRights(StringBuilder queryBuilder, HttpServletRequest request) {
173
        String oa = request.getParameter("OA");
174
        addBooleanQueryTerm("resultbestaccessright", oa, "Open Access", queryBuilder);
175
    }
176

    
177
    public static void enhanceQueryWithDate(StringBuilder queryBuilder, HttpServletRequest request) throws IllegalArgumentException{
178
        String fromDateAccepted = request.getParameter("fromDateAccepted");
179
        String toDateAccepted = request.getParameter("toDateAccepted");
180
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
181
        simpleDateFormat.setLenient(false);
182

    
183
        if (toDateAccepted != null && !toDateAccepted.isEmpty() && (fromDateAccepted == null || fromDateAccepted.isEmpty()) ) {
184
            if(!checkDate(toDateAccepted, simpleDateFormat)){
185
                //logger.debug("Format is " + !checkDate(toDateAccepted, simpleDateFormat));
186
                throw new IllegalArgumentException("toDateAccepted date must be formatted as YYYY-MM-DD");
187
            }
188
            fromDateAccepted = "*";
189
        }
190

    
191
        if (fromDateAccepted != null && !fromDateAccepted.isEmpty() && (toDateAccepted == null || toDateAccepted.isEmpty()) ) {
192
            if (!checkDate(fromDateAccepted, simpleDateFormat)){
193
                //logger.debug("Format from is " + fromDateAccepted != null && !fromDateAccepted.isEmpty());
194
                throw new IllegalArgumentException("fromDateAccepted date must be formatted as YYYY-MM-DD");
195
            }
196
            toDateAccepted = simpleDateFormat.format(new Date());
197
        }
198

    
199
        if (toDateAccepted != null && !toDateAccepted.isEmpty() && fromDateAccepted != null && !fromDateAccepted.isEmpty()) {
200
            queryBuilder.append(" and (resultdateofacceptance within \"").append(fromDateAccepted).append(" ").append(toDateAccepted).append("\")");
201
        }
202
    }
203

    
204

    
205
    public static void enhanceQueryWithYearParams(StringBuilder queryBuilder, HttpServletRequest request) {
206
        String startYear = request.getParameter("startYear");
207
        String endYear = request.getParameter("endYear");
208

    
209
        int sYear = -1;
210
        if (startYear != null && !startYear.isEmpty()) {
211
            try {
212
                sYear = Integer.parseInt(startYear);
213

    
214
            } catch(NumberFormatException e) {
215
                throw new IllegalArgumentException("startYear parameter must be a numeric value.", e);
216
            }
217
        }
218

    
219
        int eYear = -1;
220
        if (endYear !=null && !endYear.isEmpty()) {
221
            try {
222
                eYear = Integer.parseInt(endYear);
223

    
224
            } catch(NumberFormatException e) {
225
                throw new IllegalArgumentException("endYear parameter must be a numeric value.",e);
226
            }
227
        }
228

    
229
        if (eYear != -1 && sYear != -1 && eYear < sYear) {
230
            throw new IllegalArgumentException("endYear must be greater than startYear.");
231
        }
232

    
233
        addExactQueryTerm("projectstartyear", startYear, queryBuilder);
234
        addExactQueryTerm("projectendyear", endYear, queryBuilder);
235
    }
236

    
237
    public static void enhanceQueryWithResultsSortParameters(StringBuilder queryBuilder, HttpServletRequest request) {
238
        String sortByParameter = request.getParameter("sortBy");
239

    
240
        if (sortByParameter != null) {
241
            String[] sortParams = sortByParameter.split(",");
242

    
243
            if (sortParams.length != 2) {
244
                throw new IllegalArgumentException("Invalid sort paremeter. 'sortBy' parameter format is <fieldName>[,ascending|,descending].");
245
            }
246

    
247
            String sortByField = sortParams[0];
248
            String order = sortParams[1];
249

    
250
            if (!checkPublicationSortParameterFields(sortByField)){
251
                throw new IllegalArgumentException("'" + sortByField + "' is not a sortable field.");
252
            }
253

    
254
            if (!checkOrder(order)) {
255
                throw new IllegalArgumentException("'" + order + "' is not a valid ordering. Please use one of {ascending, descending}");
256
            }
257

    
258
            addSortParameter(sortByField, order, queryBuilder);
259
        }
260
    }
261

    
262
    public static void enhanceQueryWithProjectSortParameters(StringBuilder queryBuilder, HttpServletRequest request) {
263
        String sortByParameter = request.getParameter("sortBy");
264

    
265
        if (sortByParameter != null) {
266
            String[] sortParams = sortByParameter.split(",");
267

    
268
            if (sortParams.length != 2) {
269
                throw new IllegalArgumentException("Invalid sort paremeter. 'sortBy' parameter format is <fieldName>[,ascending|,descending].");
270
            }
271

    
272
            String sortByField = sortParams[0];
273
            String order = sortParams[1];
274

    
275
            if (!checkProjectSortParameterFields(sortByField)){
276
                throw new IllegalArgumentException("'" + sortByField + "' is not a sortable field.");
277
            }
278

    
279
            if (!checkOrder(order)) {
280
                throw new IllegalArgumentException("'" + order + "' is not a valid ordering. Please use one of {ascending, descending}");
281
            }
282

    
283
            addSortParameter(sortByField, order, queryBuilder);
284
        }
285
    }
286

    
287
    private static boolean checkPublicationSortParameterFields(String sortField) {
288
        if ((sortField != null) && (!sortField.isEmpty()) &&
289
                sortField.matches("dateofcollection|resultstoragedate|resultembargoenddate|resultembargoendyear|" +
290
                "resulttypeid|resulttypename|resultlanguageid|resultlanguagename|resultbestaccessright|" +
291
                "resultbestlicenseid|resultdateofacceptance|resultacceptanceyear")) {
292
            return true;
293
        }
294
        return false;
295
    }
296

    
297
    private static boolean checkProjectSortParameterFields(String sortField) {
298
        if ((sortField != null) && (!sortField.isEmpty()) &&
299
                sortField.matches("dateofcollection|projectstartdate|projectstartyear|" +
300
                        "projectenddate|projectendyear|projectcallidentifier|projectduration|" +
301
                        "projectecsc39|projectcontracttypeid|projectcontracttypename")) {
302
            return true;
303
        }
304
        return false;
305
    }
306

    
307
    private static boolean checkOrder(String order) {
308
        if (order.matches("ascending|descending")) {
309
            return true;
310
        }
311
        return false;
312
    }
313

    
314
    public static boolean checkDate(String date, SimpleDateFormat simpleDateFormat) {
315
        try {
316
            simpleDateFormat.parse(date);
317

    
318
        } catch (ParseException pe) {
319
            logger.warn("Wrong date format.", pe);
320
            return false;
321
        }
322

    
323
        return true;
324
    }
325

    
326
    /**
327
     * Enhance the given CQL query with OpenAIRE specific ids
328
     * @param queryBuilder The string builder of the query
329
     * @param request the HTTP request
330
     */
331
    public static void enhanceQueryWithOpenAIREIds(StringBuilder queryBuilder, HttpServletRequest request) {
332
        String[] openairePublicationIDs = request.getParameterValues("openairePublicationID");
333
        String[] openaireDatasetIDs = request.getParameterValues("openaireDatasetID");
334
        String[] openaireSoftwareIDs = request.getParameterValues("openaireSoftwareID");
335
        String[] openaireOtherIDs = request.getParameterValues("openaireOtherID");
336
        String[] openaireProviderIDs  = request.getParameterValues("openaireProviderID");
337
        String[] openaireProjectIDs  = request.getParameterValues("openaireProjectID");
338

    
339
        enhanceQueryWithIds("objidentifier", openairePublicationIDs, queryBuilder);
340
        enhanceQueryWithIds("objidentifier", openaireDatasetIDs, queryBuilder);
341
        enhanceQueryWithIds("objidentifier", openaireSoftwareIDs, queryBuilder);
342
        enhanceQueryWithIds("objidentifier", openaireOtherIDs, queryBuilder);
343
        enhanceQueryWithIds("resulthostingdatasourceid", openaireProviderIDs, queryBuilder);
344
        enhanceQueryWithIds("relprojectid", openaireProjectIDs, queryBuilder);
345
    }
346

    
347
    public static void enhanceQueryWithMetadataKeywords(StringBuilder queryBuilder, HttpServletRequest request) {
348
        String keywords = request.getParameter("keywords");
349
        String title = request.getParameter("title");
350
        String author = request.getParameter("author");
351
        String country = request.getParameter("country");
352

    
353
        addMetadataQueryTerm(null, keywords, queryBuilder);
354
        addMetadataQueryTerm("resulttitle", title, queryBuilder);
355
        addMetadataAuthorTerm("resultauthor", author, queryBuilder);
356
        addMetadataQueryTerm("country", country, queryBuilder);
357

    
358
    }
359

    
360
    public static void enhanceQueryWithProjectMetadataKeywords(StringBuilder queryBuilder, HttpServletRequest request) {
361
        String keywords = request.getParameter("keywords");
362
        String acronym = request.getParameter("acronym");
363
        String name = request.getParameter("name");
364
        String grantID = request.getParameter("grantID");
365
        String callID = request.getParameter("callID");
366

    
367
        addMetadataQueryTerm(null, keywords, queryBuilder);
368
        addMetadataQueryTerm("projectacronym", acronym, queryBuilder);
369
        addEqual2QueryTerm("projecttitle", name, queryBuilder);
370
        addExactQueryTerm("projectcode_nt", grantID, queryBuilder);
371
        addExactQueryTerm("projectcallidentifier", callID, queryBuilder);
372
    }
373

    
374
    public static void enhanceQueryWithParticipantsInfoParams(StringBuilder queryBuilder, HttpServletRequest request) {
375
        String[] participantCountries = request.getParameterValues("participantCountries");
376
        String participantAcronyms = request.getParameter("participantAcronyms");
377
        String openaireParticipantID = request.getParameter("openaireParticipantID");
378

    
379

    
380
        if(participantCountries != null) {
381
            enhanceQueryWithCommaSeparatedValues("relorganizationcountryid", participantCountries, queryBuilder);
382
        }
383

    
384
        addORQueryTerm("relorganizationname", "relorganizationshortname", participantAcronyms, queryBuilder);
385

    
386
        if(openaireParticipantID != null) {
387
            addEqualQueryTerm("relorganizationid", openaireParticipantID, queryBuilder);
388
        }
389

    
390
    }
391

    
392
    public static void enhanceQueryWithSC39Params(StringBuilder queryBuilder, HttpServletRequest request) {
393
        String sc39 = request.getParameter("sc39");
394
        addBooleanQueryTerm("projectecsc39", sc39, queryBuilder);
395
    }
396

    
397
    public static void enhanceQueryWithDoi(StringBuilder queryBuilder, HttpServletRequest request) {
398
        String[] dois = request.getParameterValues("doi");
399

    
400
        if (dois != null && !(dois.length==0)) {
401
            queryBuilder.append(" and (");
402
            for (int i = 0; i < dois.length; i++) {
403
                String[] commaSeparated = dois[i].split(",");
404
                for (int j = 0; j < commaSeparated.length; j++) {
405
                    queryBuilder.append("(pidclassid exact \"doi\" and pid exact \"").append(commaSeparated[j]).append("\")");
406
                    if (i < dois.length-1 || j < commaSeparated.length-1 ) {
407
                        queryBuilder.append(" or ");
408
                    }
409
                }
410
            }
411
            queryBuilder.append(")");
412
        }
413
    }
414

    
415
    public static void enhanceQueryWithOrcid(StringBuilder queryBuilder, HttpServletRequest request) {
416
        String[] dois = request.getParameterValues("orcid");
417

    
418
        if (dois != null && !(dois.length==0)) {
419
            queryBuilder.append(" and (");
420
            for (int i = 0; i < dois.length; i++) {
421
                String[] commaSeparated = dois[i].split(",");
422
                for (int j = 0; j < commaSeparated.length; j++) {
423
                    queryBuilder.append("(orcidtypevalue exact \"").append(commaSeparated[j]).append("||orcid\")");
424
                    if (i < dois.length-1 || j < commaSeparated.length-1 ) {
425
                        queryBuilder.append(" or ");
426
                    }
427
                }
428
            }
429
            queryBuilder.append(")");
430
        }
431
    }
432

    
433
    public static void enhanceQueryWithInstancetype(StringBuilder queryBuilder, HttpServletRequest request) {
434
        String[] originalIds = request.getParameterValues("instancetype");
435

    
436
        if (originalIds != null && !(originalIds.length==0)) {
437
            queryBuilder.append(" and (");
438
            for (int i = 0; i < originalIds.length; i++) {
439
                String[] commaSeparated = originalIds[i].split(",");
440
                for (int j = 0; j < commaSeparated.length; j++) {
441
                    queryBuilder.append("(instancetypename exact \"").append(commaSeparated[j]).append("\")");
442
                    if (i < originalIds.length-1 || j < commaSeparated.length-1 ) {
443
                        queryBuilder.append(" or ");
444
                    }
445
                }
446
            }
447
            queryBuilder.append(")");
448
        }
449
    }
450

    
451
    public static void enhanceQueryWithOriginalId(StringBuilder queryBuilder, HttpServletRequest request) {
452
        String[] originalIds = request.getParameterValues("originalId");
453

    
454
        if (originalIds != null && !(originalIds.length==0)) {
455
            queryBuilder.append(" and (");
456
            for (int i = 0; i < originalIds.length; i++) {
457
                String[] commaSeparated = originalIds[i].split(",");
458
                for (int j = 0; j < commaSeparated.length; j++) {
459
                    queryBuilder.append("(originalId exact \"").append(commaSeparated[j]).append("\")");
460
                    if (i < originalIds.length-1 || j < commaSeparated.length-1 ) {
461
                        queryBuilder.append(" or ");
462
                    }
463
                }
464
            }
465
            queryBuilder.append(")");
466
        }
467
    }
468

    
469
    public static void enhanceProjectQueryWithOpenAIREIds(StringBuilder queryBuilder, HttpServletRequest request) {
470
        String openaireProjectID  = request.getParameter("openaireProjectID");
471

    
472
        if (openaireProjectID != null) {
473
            addExactQueryTerm("objIdentifier", openaireProjectID, queryBuilder);
474
        }
475
    }
476

    
477
    public static void enhanceQueryWithIds(String idIndexFieldName, String[] ids, StringBuilder queryBuilder) {
478
        if (ids != null && !(ids.length==0)) {
479
            queryBuilder.append(" and ");
480
            for (int i = 0; i < ids.length; i++) {
481
                String[] commaSeparated = ids[i].split(",");
482
                for (int j = 0; j < commaSeparated.length; j++) {
483
                    queryBuilder.append("(" + idIndexFieldName + " exact \"").append(commaSeparated[j]).append("\")");
484
                    if (idIndexFieldName.equals("objidentifier"))
485
                        queryBuilder.append(" or ( resultdupid exact \"").append(commaSeparated[j]).append("\")");
486
                    if (i < ids.length-1 || j < commaSeparated.length-1 ) {
487
                        queryBuilder.append(" or ");
488
                    }
489
                }
490
            }
491
        }
492
    }
493

    
494
    public static void enhanceQueryWithCommaSeparatedValues(String indexFieldName, String[] fieldValues, StringBuilder queryBuilder) {
495
        if (fieldValues != null && !(fieldValues.length==0)) {
496
            queryBuilder.append(" and ");
497
            for (int i = 0; i < fieldValues.length; i++) {
498
                String[] commaSeparated = fieldValues[i].split(",");
499
                for (int j = 0; j < commaSeparated.length; j++) {
500
                    queryBuilder.append("(").append(indexFieldName).append(" exact \"").append(commaSeparated[j].toUpperCase()).append("\")");
501
                    if (i < fieldValues.length-1 || j < commaSeparated.length-1 ) {
502
                        queryBuilder.append(" and ");
503
                    }
504
                }
505
            }
506
        }
507
    }
508

    
509
    public static void enhanceQueryWithInstanceType(StringBuilder queryBuilder, boolean modelSygma, String version) {
510
        if(modelSygma && version!=null && version.equals("2")) {
511
            addNotEqualQueryTerm("instancetypename", "Project proposal", queryBuilder);
512
            addNotEqualQueryTerm("instancetypename", "Project deliverable", queryBuilder);
513
            addNotEqualQueryTerm("instancetypename", "Project milestone", queryBuilder);
514
            addNotEqualQueryTerm("instancetypename", "Project proposal", queryBuilder);
515
        }
516

    
517
        System.out.println("QUERY " + queryBuilder.toString());
518
    }
519

    
520
    public static void addMetadataQueryTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder) {
521
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
522
            if(indexFieldName != null) {
523
                for (String term: fieldValue.trim().split(" ")){
524
                    addEqualQueryTerm(indexFieldName, term, queryBuilder);
525
                }
526
            } else {
527
                queryBuilder.append(" and ( " );
528
                String[] keywords = fieldValue.trim().split(" ");
529
                for (int i = 0; i < keywords.length; i++) {
530
                    if (i == keywords.length -1) {
531
                        queryBuilder.append(keywords[i]);
532
                    } else {
533
                        queryBuilder.append(keywords[i]).append(" and ");
534
                    }
535
                }
536
                queryBuilder.append(")" );
537
            }
538
        }
539
    }
540

    
541
    public static void addMetadataAuthorTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder) {
542
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
543
            if(indexFieldName != null) {
544
                for (String term: fieldValue.trim().split(";")){
545
                    addEqualQueryTerm(indexFieldName, term, queryBuilder);
546
                }
547
            } else {
548
                queryBuilder.append(" and ( " );
549
                String[] keywords = fieldValue.trim().split(";");
550
                for (int i = 0; i < keywords.length; i++) {
551
                    if (i == keywords.length -1) {
552
                        queryBuilder.append(keywords[i]);
553
                    } else {
554
                        queryBuilder.append(keywords[i]).append(" and ");
555
                    }
556
                }
557
                queryBuilder.append(")" );
558
            }
559
        }
560
    }
561

    
562
    public static void addORQueryTerm(String indexFieldName1, String indexFieldName2, String fieldValue, StringBuilder queryBuilder) {
563
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
564
            for (String term: fieldValue.trim().split(" ")) {
565
                queryBuilder.append(" and (" + indexFieldName1 + " = " + term + " or  " + indexFieldName2 + " = " + term + ")");
566
            }
567
        }
568
    }
569

    
570
    public static void addORQueryTerm(String[] indexFields, String fieldValue, StringBuilder queryBuilder) {
571
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
572
            queryBuilder.append(" and ( ");
573
            for (int i = 0; i < indexFields.length; i++) {
574
                for (String term : fieldValue.trim().split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1)) {
575
                    //logger.info("term: " + term);
576
                    queryBuilder.append(" (" + indexFields[i] + " = " + term + ")");
577
                }
578

    
579
                if (i == indexFields.length-1) {
580
                    queryBuilder.append(")");
581

    
582
                } else {
583
                    queryBuilder.append(" or ");
584
                }
585

    
586
            }
587
        }
588
    }
589

    
590
    public static void addORQueryTermExact(String[] indexFields, String fieldValue, StringBuilder queryBuilder) {
591
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
592
            queryBuilder.append(" and ( ");
593
            for (int i = 0; i < indexFields.length; i++) {
594
                for (String term : fieldValue.trim().split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1)) {
595
                    //logger.info("term: " + term);
596
                    queryBuilder.append(" (" + indexFields[i] + " exact " + term + ")");
597
                }
598

    
599
                if (i == indexFields.length-1) {
600
                    queryBuilder.append(")");
601

    
602
                } else {
603
                    queryBuilder.append(" or ");
604
                }
605

    
606
            }
607
        }
608
    }
609

    
610
    private static void addBooleanQueryTerm(String indexFieldName, String requestValue, StringBuilder queryBuilder) {
611
        if (requestValue != null && !requestValue.trim().isEmpty()) {
612
            addExactQueryTerm(indexFieldName, requestValue, queryBuilder);
613
        }
614
    }
615

    
616
    public static void addBooleanQueryTerm(String indexFieldName, String requestValue, String fieldValue, StringBuilder queryBuilder){
617
        if (requestValue != null && !requestValue.trim().isEmpty()) {
618
            if (requestValue.trim().equals("true")) {
619
                addExactQueryTerm(indexFieldName, fieldValue, queryBuilder);
620
            } else {
621
                addDifferentQueryTerm(indexFieldName, fieldValue, queryBuilder);
622
            }
623
        }
624
    }
625

    
626
    public static void addExactQueryTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder){
627
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
628
            CQLQueryBuilder.appendFieldQuotedTerm(queryBuilder, CQLQueryBuilder.Operator.AND, indexFieldName, CQLQueryBuilder.Operator.EXACT, fieldValue);
629
        }
630
    }
631

    
632
    public static void addEqualQueryTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder){
633
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
634
            if (fieldValue.startsWith("\"") && fieldValue.endsWith("\"")) {
635
                CQLQueryBuilder.appendFieldTerm(queryBuilder, CQLQueryBuilder.Operator.AND, indexFieldName, CQLQueryBuilder.Operator.EQUAL, fieldValue);
636
            } else {
637
                CQLQueryBuilder.appendFieldQuotedTerm(queryBuilder, CQLQueryBuilder.Operator.AND, indexFieldName, CQLQueryBuilder.Operator.EQUAL, fieldValue);
638
            }
639
        }
640
    }
641

    
642
    public static void addEqual2QueryTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder){
643
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
644
            if (fieldValue.startsWith("\"") && fieldValue.endsWith("\"")) {
645
                CQLQueryBuilder.appendFieldTerm(queryBuilder, CQLQueryBuilder.Operator.AND, indexFieldName, CQLQueryBuilder.Operator.EXACT, fieldValue);
646
            } else {
647
                CQLQueryBuilder.appendFieldTerm(queryBuilder, CQLQueryBuilder.Operator.AND, indexFieldName, CQLQueryBuilder.Operator.EQUAL, fieldValue);
648
            }
649
        }
650
    }
651

    
652
    public static void addNotEqualQueryTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder){
653
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
654
            CQLQueryBuilder.appendFieldQuotedTerm(queryBuilder, CQLQueryBuilder.Operator.NOT, indexFieldName, CQLQueryBuilder.Operator.EQUAL, fieldValue);
655
        }
656
    }
657

    
658
    public static void addDifferentQueryTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder){
659
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
660
            CQLQueryBuilder.appendFieldQuotedTerm(queryBuilder, CQLQueryBuilder.Operator.AND, indexFieldName, CQLQueryBuilder.Operator.NOTEQUAL, fieldValue);
661
        }
662
    }
663

    
664
    public static void addVocabularizedQueryTerm(String indexFieldName, String fieldValue, Vocabulary vocabulary, StringBuilder queryBuilder){
665
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
666
            addExactQueryTerm(indexFieldName, devocabularizedTerm(fieldValue, vocabulary), queryBuilder);
667
        }
668
    }
669

    
670
    private static void addSortParameter(String indexField, String order, StringBuilder queryBuilder) {
671
        queryBuilder.append(" sortBy " + indexField + "/sort." + order);
672
    }
673

    
674
    /**
675
     * Returns the encoding of the given value. If the encoding does not exist
676
     * in the given vocabulary the method returns the original value.|
677
     * @param value the value to be encoded
678
     * @param vocabulary the vocabulary containing the encoding - value mapping
679
     * @return the encoding of the given value taken from the given vocabulary
680
     */
681
    public static String devocabularizedTerm(String value, Vocabulary vocabulary) {
682
        if (vocabulary != null) {
683
            String term = vocabulary.getEncoding(value);
684
            logger.debug("VOCABULARY " + vocabulary.getName());
685
            logger.debug("VALUE " + value);
686
            if (term == null) {
687
                return value;
688
            }
689
            return term;
690
        }
691
        return value;
692
    }
693

    
694

    
695
}
(2-2/2)