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 { //version 2 sygma model
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
    public static void enhanceQueryWithProjectMetadataKeywords(StringBuilder queryBuilder, HttpServletRequest request) {
360
        String keywords = request.getParameter("keywords");
361
        String acronym = request.getParameter("acronym");
362
        String name = request.getParameter("name");
363
        String grantID = request.getParameter("grantID");
364
        String callID = request.getParameter("callID");
365

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

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

    
378

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

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

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

    
389
    }
390

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

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

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

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

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

    
432
    public static void enhanceQueryWithOriginalId(StringBuilder queryBuilder, HttpServletRequest request) {
433
        String[] originalIds = request.getParameterValues("originalId");
434

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

    
450
    public static void enhanceProjectQueryWithOpenAIREIds(StringBuilder queryBuilder, HttpServletRequest request) {
451
        String openaireProjectID  = request.getParameter("openaireProjectID");
452

    
453
        if (openaireProjectID != null) {
454
            addExactQueryTerm("objIdentifier", openaireProjectID, queryBuilder);
455
        }
456
    }
457

    
458
    public static void enhanceQueryWithIds(String idIndexFieldName, String[] ids, StringBuilder queryBuilder) {
459
        if (ids != null && !(ids.length==0)) {
460
            queryBuilder.append(" and ");
461
            for (int i = 0; i < ids.length; i++) {
462
                String[] commaSeparated = ids[i].split(",");
463
                for (int j = 0; j < commaSeparated.length; j++) {
464
                    queryBuilder.append("(" + idIndexFieldName + " exact \"").append(commaSeparated[j]).append("\")");
465
                    if (idIndexFieldName.equals("objidentifier"))
466
                        queryBuilder.append(" or ( resultdupid exact \"").append(commaSeparated[j]).append("\")");
467
                    if (i < ids.length-1 || j < commaSeparated.length-1 ) {
468
                        queryBuilder.append(" or ");
469
                    }
470
                }
471
            }
472
        }
473
    }
474

    
475
    public static void enhanceQueryWithCommaSeparatedValues(String indexFieldName, String[] fieldValues, StringBuilder queryBuilder) {
476
        if (fieldValues != null && !(fieldValues.length==0)) {
477
            queryBuilder.append(" and ");
478
            for (int i = 0; i < fieldValues.length; i++) {
479
                String[] commaSeparated = fieldValues[i].split(",");
480
                for (int j = 0; j < commaSeparated.length; j++) {
481
                    queryBuilder.append("(").append(indexFieldName).append(" exact \"").append(commaSeparated[j].toUpperCase()).append("\")");
482
                    if (i < fieldValues.length-1 || j < commaSeparated.length-1 ) {
483
                        queryBuilder.append(" and ");
484
                    }
485
                }
486
            }
487
        }
488
    }
489

    
490
    public static void enhanceQueryWithInstanceType(StringBuilder queryBuilder, boolean modelSygma, String version) {
491
        if(modelSygma && version!=null && version.equals("2")) {
492
            addNotEqualQueryTerm("instancetypename", "Project proposal", queryBuilder);
493
            addNotEqualQueryTerm("instancetypename", "Project deliverable", queryBuilder);
494
            addNotEqualQueryTerm("instancetypename", "Project milestone", queryBuilder);
495
            addNotEqualQueryTerm("instancetypename", "Project proposal", queryBuilder);
496
        }
497

    
498
        System.out.println("QUERY " + queryBuilder.toString());
499
    }
500

    
501
    public static void addMetadataQueryTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder) {
502
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
503
            if(indexFieldName != null) {
504
                for (String term: fieldValue.trim().split(" ")){
505
                    addEqualQueryTerm(indexFieldName, term, queryBuilder);
506
                }
507
            } else {
508
                queryBuilder.append(" and ( " );
509
                String[] keywords = fieldValue.trim().split(" ");
510
                for (int i = 0; i < keywords.length; i++) {
511
                    if (i == keywords.length -1) {
512
                        queryBuilder.append(keywords[i]);
513
                    } else {
514
                        queryBuilder.append(keywords[i]).append(" and ");
515
                    }
516
                }
517
                queryBuilder.append(")" );
518
            }
519
        }
520
    }
521

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

    
543
    public static void addORQueryTerm(String indexFieldName1, String indexFieldName2, String fieldValue, StringBuilder queryBuilder) {
544
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
545
            for (String term: fieldValue.trim().split(" ")) {
546
                queryBuilder.append(" and (" + indexFieldName1 + " = " + term + " or  " + indexFieldName2 + " = " + term + ")");
547
            }
548
        }
549
    }
550

    
551
    public static void addORQueryTerm(String[] indexFields, String fieldValue, StringBuilder queryBuilder) {
552
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
553
            queryBuilder.append(" and ( ");
554
            for (int i = 0; i < indexFields.length; i++) {
555
                for (String term : fieldValue.trim().split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1)) {
556
                    //logger.info("term: " + term);
557
                    queryBuilder.append(" (" + indexFields[i] + " = " + term + ")");
558
                }
559

    
560
                if (i == indexFields.length-1) {
561
                    queryBuilder.append(")");
562

    
563
                } else {
564
                    queryBuilder.append(" or ");
565
                }
566

    
567
            }
568
        }
569
    }
570

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

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

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

    
587
            }
588
        }
589
    }
590

    
591
    private static void addBooleanQueryTerm(String indexFieldName, String requestValue, StringBuilder queryBuilder) {
592
        if (requestValue != null && !requestValue.trim().isEmpty()) {
593
            addExactQueryTerm(indexFieldName, requestValue, queryBuilder);
594
        }
595
    }
596

    
597
    public static void addBooleanQueryTerm(String indexFieldName, String requestValue, String fieldValue, StringBuilder queryBuilder){
598
        if (requestValue != null && !requestValue.trim().isEmpty()) {
599
            if (requestValue.trim().equals("true")) {
600
                addExactQueryTerm(indexFieldName, fieldValue, queryBuilder);
601
            } else {
602
                addDifferentQueryTerm(indexFieldName, fieldValue, queryBuilder);
603
            }
604
        }
605
    }
606

    
607
    public static void addExactQueryTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder){
608
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
609
            CQLQueryBuilder.appendFieldQuotedTerm(queryBuilder, CQLQueryBuilder.Operator.AND, indexFieldName, CQLQueryBuilder.Operator.EXACT, fieldValue);
610
        }
611
    }
612

    
613
    public static void addEqualQueryTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder){
614
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
615
            if (fieldValue.startsWith("\"") && fieldValue.endsWith("\"")) {
616
                CQLQueryBuilder.appendFieldTerm(queryBuilder, CQLQueryBuilder.Operator.AND, indexFieldName, CQLQueryBuilder.Operator.EQUAL, fieldValue);
617
            } else {
618
                CQLQueryBuilder.appendFieldQuotedTerm(queryBuilder, CQLQueryBuilder.Operator.AND, indexFieldName, CQLQueryBuilder.Operator.EQUAL, fieldValue);
619
            }
620
        }
621

    
622

    
623

    
624

    
625
    }
626

    
627
    public static void addNotEqualQueryTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder){
628
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
629
            CQLQueryBuilder.appendFieldQuotedTerm(queryBuilder, CQLQueryBuilder.Operator.NOT, indexFieldName, CQLQueryBuilder.Operator.EQUAL, fieldValue);
630
        }
631
    }
632

    
633
    public static void addDifferentQueryTerm(String indexFieldName, String fieldValue, StringBuilder queryBuilder){
634
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
635
            CQLQueryBuilder.appendFieldQuotedTerm(queryBuilder, CQLQueryBuilder.Operator.AND, indexFieldName, CQLQueryBuilder.Operator.NOTEQUAL, fieldValue);
636
        }
637
    }
638

    
639
    public static void addVocabularizedQueryTerm(String indexFieldName, String fieldValue, Vocabulary vocabulary, StringBuilder queryBuilder){
640
        if (fieldValue != null && !fieldValue.trim().isEmpty()) {
641
            addExactQueryTerm(indexFieldName, devocabularizedTerm(fieldValue, vocabulary), queryBuilder);
642
        }
643
    }
644

    
645
    private static void addSortParameter(String indexField, String order, StringBuilder queryBuilder) {
646
        queryBuilder.append(" sortBy " + indexField + "/sort." + order);
647
    }
648

    
649
    /**
650
     * Returns the encoding of the given value. If the encoding does not exist
651
     * in the given vocabulary the method returns the original value.|
652
     * @param value the value to be encoded
653
     * @param vocabulary the vocabulary containing the encoding - value mapping
654
     * @return the encoding of the given value taken from the given vocabulary
655
     */
656
    public static String devocabularizedTerm(String value, Vocabulary vocabulary) {
657
        if (vocabulary != null) {
658
            String term = vocabulary.getEncoding(value);
659
            logger.debug("VOCABULARY " + vocabulary.getName());
660
            logger.debug("VALUE " + value);
661
            if (term == null) {
662
                return value;
663
            }
664
            return term;
665
        }
666
        return value;
667
    }
668

    
669

    
670
}
(2-2/2)