Update poms to conform to merge job requirements
[aai/search-data-service.git] / search-data-service-app / src / main / java / org / onap / aai / sa / rest / AnalysisConfiguration.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.sa.rest;
22
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import java.io.File;
25 import java.io.IOException;
26 import java.util.concurrent.atomic.AtomicBoolean;
27 import org.onap.aai.cl.api.Logger;
28 import org.onap.aai.cl.eelf.LoggerFactory;
29 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
30 import org.onap.aai.sa.searchdbabstraction.util.SearchDbConstants;
31
32 /**
33  * This class encapsulates the configuration of the predefined Analyzer and Filter behaviours that help to tell the
34  * document store how to index the documents that are provided to it.
35  */
36 public class AnalysisConfiguration {
37
38     /**
39      * Contains all of the predefined indexing filters.
40      */
41     private FilterSchema[] customFilters;
42
43     /**
44      * Contains all of the predefined indexing analyzers.
45      */
46     private AnalyzerSchema[] customAnalysers;
47
48     /**
49      * Indicates whether or not we have imported the filter and analyzer configurations.
50      */
51     private AtomicBoolean configured = new AtomicBoolean(false);
52
53     /**
54      * A json format string which is readable by Elastic Search and defines all of the custom filters and analyzers that
55      * we need Elastic Search to know about.
56      */
57     private String esSettings = null;
58
59     private static Logger logger = LoggerFactory.getInstance().getLogger(AnalysisConfiguration.class.getName());
60
61
62     /**
63      * Imports the filter and analyzer configuration files and builds an Elastic Search readable settings file from the
64      * contents.
65      *
66      * @param filterConfigFile - Location of filter configuration json file
67      * @param analyzerConfigFile - Location of analyzer configuration json file
68      */
69     public void init(String filterConfigFile, String analyzerConfigFile) {
70
71         if (configured.compareAndSet(false, true)) {
72             ObjectMapper mapper = new ObjectMapper();
73
74             File filtersConfig = new File(filterConfigFile);
75             try {
76                 customFilters = mapper.readValue(filtersConfig, FilterSchema[].class);
77             } catch (IOException e) {
78
79                 // generate log
80                 logger.warn(SearchDbMsgs.FILTERS_CONFIG_FAILURE, filterConfigFile, e.getMessage());
81             }
82
83             File analysersConfig = new File(analyzerConfigFile);
84             try {
85                 customAnalysers = mapper.readValue(analysersConfig, AnalyzerSchema[].class);
86             } catch (IOException e) {
87
88                 // generate log
89                 logger.warn(SearchDbMsgs.ANALYSYS_CONFIG_FAILURE, analyzerConfigFile, e.getMessage());
90             }
91
92             esSettings = buildEsIndexSettings();
93         }
94     }
95
96
97     /**
98      * Returns the set of pre-configured filters.
99      *
100      * @return - An array of filters.
101      */
102     public FilterSchema[] getFilters() {
103         return customFilters;
104     }
105
106
107     /**
108      * Returns the set of pre-configured analyzers.
109      *
110      * @return - An array of analyzers.
111      */
112     public AnalyzerSchema[] getAnalyzers() {
113         init(SearchDbConstants.SDB_FILTER_CONFIG_FILE, SearchDbConstants.SDB_ANALYSIS_CONFIG_FILE);
114         return customAnalysers;
115     }
116
117
118     /**
119      * Imports the filter and analyzer configurations and translates those into a settings string that will be parseable
120      * by Elastic Search.
121      *
122      * @return - Elastic Search formatted settings string.
123      */
124     public String getEsIndexSettings() {
125
126         // Generate the es-settings string from our filter and analyzer
127         // configurations if we have not already done so.
128         init(SearchDbConstants.SDB_FILTER_CONFIG_FILE, SearchDbConstants.SDB_ANALYSIS_CONFIG_FILE);
129
130         // Now, return the es-settings string.
131         return esSettings;
132     }
133
134
135     /**
136      * Constructs a settings string that is readable by Elastic Search based on the contents of the filter and analyzer
137      * configuration files.
138      *
139      * @return Elastic Search formatted settings string.
140      */
141     public String buildEsIndexSettings() {
142
143         StringBuilder sb = new StringBuilder();
144
145         sb.append("{");
146         sb.append("\"analysis\": {");
147
148         // Define the custom filters.
149         boolean atLeastOneFilter = false;
150         sb.append("\"filter\": {");
151         AtomicBoolean firstFilter = new AtomicBoolean(true);
152         for (FilterSchema filter : customFilters) {
153
154             // Append a comma before the next entry, unless it is the
155             // first one.
156             if (!firstFilter.compareAndSet(true, false)) {
157                 sb.append(", ");
158             }
159
160             // Now, build the filter entry.
161             buildFilterEntry(filter, sb);
162             atLeastOneFilter = true;
163         }
164         sb.append((atLeastOneFilter) ? "}," : "}");
165
166         // Define the custom analyzers.
167         sb.append("\"analyzer\": {");
168         AtomicBoolean firstAnalyzer = new AtomicBoolean(true);
169         for (AnalyzerSchema analyzer : customAnalysers) {
170
171             // Prepend a comma before the entry, unless it is the
172             // first one.
173             if (!firstAnalyzer.compareAndSet(true, false)) {
174                 sb.append(",");
175             }
176
177             // Now, construct the entry for this analyzer.
178             buildAnalyzerEntry(analyzer, sb);
179         }
180         sb.append("}");
181
182         sb.append("}");
183         sb.append("}");
184
185         return sb.toString();
186     }
187
188
189     /**
190      * Constructs an ElasticSearch friendly custom filter definition.
191      *
192      * @param filter - The filter to generate ElasticSearch json for.
193      * @param sb - The string builder to append the filter definition to.
194      */
195     private void buildFilterEntry(FilterSchema filter, StringBuilder sb) {
196
197         sb.append("\"" + filter.getName()).append("\": {");
198
199         sb.append(filter.getConfiguration());
200
201         sb.append("}");
202     }
203
204
205     /**
206      * Constructs an ElasticSearch friendly custom analyzer definition.
207      *
208      * @param analyzer - The analyzer to generate ElasticSearch json for.
209      * @param sb - The string builder to append the analyzer definition to.
210      */
211     private void buildAnalyzerEntry(AnalyzerSchema analyzer, StringBuilder sb) {
212
213         sb.append("\"").append(analyzer.getName()).append("\": {");
214         sb.append("\"type\": \"custom\",");
215         sb.append("\"tokenizer\": ").append("\"").append(analyzer.getTokenizer()).append("\",");
216         sb.append("\"filter\": [");
217         boolean firstFilter = true;
218         for (String filter : analyzer.getFilters()) {
219             if (!firstFilter) {
220                 sb.append(",");
221             } else {
222                 firstFilter = false;
223             }
224             sb.append("\"").append(filter).append("\"");
225         }
226         sb.append("]");
227         sb.append("}");
228     }
229 }