Fix variable declaration
[aai/search-data-service.git] / 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
25 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
26 import org.onap.aai.sa.searchdbabstraction.util.SearchDbConstants;
27 import org.onap.aai.cl.api.Logger;
28 import org.onap.aai.cl.eelf.LoggerFactory;
29 import org.onap.aai.sa.rest.AnalyzerSchema;
30 import org.onap.aai.sa.rest.FilterSchema;
31
32 import java.io.File;
33 import java.io.IOException;
34 import java.util.concurrent.atomic.AtomicBoolean;
35
36 /**
37  * This class encapsulates the configuration of the predefined
38  * Analyzer and Filter behaviours that help to tell the document
39  * store how to index the documents that are provided to it.
40  */
41 public class AnalysisConfiguration {
42
43   /**
44    * Contains all of the predefined indexing filters.
45    */
46   private FilterSchema[] customFilters;
47
48   /**
49    * Contains all of the predefined indexing analyzers.
50    */
51   private AnalyzerSchema[] customAnalysers;
52
53   /**
54    * Indicates whether or not we have imported the filter and
55    * analyzer configurations.
56    */
57   private AtomicBoolean configured = new AtomicBoolean(false);
58
59   /**
60    * A json format string which is readable by Elastic Search and defines
61    * all of the custom filters and analyzers that we need Elastic Search
62    * to know about.
63    */
64   private String esSettings = null;
65
66   private static Logger logger = LoggerFactory.getInstance()
67       .getLogger(AnalysisConfiguration.class.getName());
68
69
70   /**
71    * Imports the filter and analyzer configuration files and
72    * builds an Elastic Search readable settings file from the
73    * contents.
74    *
75    * @param filterConfigFile   - Location of filter configuration json file
76    * @param analyzerConfigFile - Location of analyzer configuration json file
77    */
78   public void init(String filterConfigFile, String analyzerConfigFile) {
79
80     if (configured.compareAndSet(false, true)) {
81       ObjectMapper mapper = new ObjectMapper();
82
83       File filtersConfig = new File(filterConfigFile);
84       try {
85         customFilters = mapper.readValue(filtersConfig, FilterSchema[].class);
86       } catch (IOException e) {
87
88         // generate log
89         logger.warn(SearchDbMsgs.FILTERS_CONFIG_FAILURE, filterConfigFile, e.getMessage());
90       }
91
92       File analysersConfig = new File(analyzerConfigFile);
93       try {
94         customAnalysers = mapper.readValue(analysersConfig, AnalyzerSchema[].class);
95       } catch (IOException e) {
96
97         // generate log
98         logger.warn(SearchDbMsgs.ANALYSYS_CONFIG_FAILURE, analyzerConfigFile, e.getMessage());
99       }
100
101       esSettings = buildEsIndexSettings();
102     }
103   }
104
105
106   /**
107    * Returns the set of pre-configured filters.
108    *
109    * @return - An array of filters.
110    */
111   public FilterSchema[] getFilters() {
112     return customFilters;
113   }
114
115
116   /**
117    * Returns the set of pre-configured analyzers.
118    *
119    * @return - An array of analyzers.
120    */
121   public AnalyzerSchema[] getAnalyzers() {
122     init(SearchDbConstants.SDB_FILTER_CONFIG_FILE, SearchDbConstants.SDB_ANALYSIS_CONFIG_FILE);
123     return customAnalysers;
124   }
125
126
127   /**
128    * Imports the filter and analyzer configurations and translates those
129    * into a settings string that will be parseable by Elastic Search.
130    *
131    * @return - Elastic Search formatted settings string.
132    */
133   public String getEsIndexSettings() {
134
135     // Generate the es-settings string from our filter and analyzer
136     // configurations if we have not already done so.
137     init(SearchDbConstants.SDB_FILTER_CONFIG_FILE, SearchDbConstants.SDB_ANALYSIS_CONFIG_FILE);
138
139     // Now, return the es-settings string.
140     return esSettings;
141   }
142
143
144   /**
145    * Constructs a settings string that is readable by Elastic Search based
146    * on the contents of the filter and analyzer configuration files.
147    *
148    * @return Elastic Search formatted settings string.
149    */
150   public String buildEsIndexSettings() {
151
152     StringBuilder sb = new StringBuilder();
153
154     sb.append("{");
155     sb.append("\"analysis\": {");
156
157     // Define the custom filters.
158     boolean atLeastOneFilter = false;
159     sb.append("\"filter\": {");
160     AtomicBoolean firstFilter = new AtomicBoolean(true);
161     for (FilterSchema filter : customFilters) {
162
163       // Append a comma before the next entry, unless it is the
164       // first one.
165       if (!firstFilter.compareAndSet(true, false)) {
166         sb.append(", ");
167       }
168
169       // Now, build the filter entry.
170       buildFilterEntry(filter, sb);
171       atLeastOneFilter = true;
172     }
173     sb.append((atLeastOneFilter) ? "}," : "}");
174
175     // Define the custom analyzers.
176     sb.append("\"analyzer\": {");
177     AtomicBoolean firstAnalyzer = new AtomicBoolean(true);
178     for (AnalyzerSchema analyzer : customAnalysers) {
179
180       // Prepend a comma before the entry, unless it is the
181       // first one.
182       if (!firstAnalyzer.compareAndSet(true, false)) {
183         sb.append(",");
184       }
185
186       // Now, construct the entry for this analyzer.
187       buildAnalyzerEntry(analyzer, sb);
188     }
189     sb.append("}");
190
191     sb.append("}");
192     sb.append("}");
193
194     return sb.toString();
195   }
196
197
198   /**
199    * Constructs an ElasticSearch friendly custom filter definition.
200    *
201    * @param filter - The filter to generate ElasticSearch json for.
202    * @param sb     - The string builder to append the filter definition
203    *               to.
204    */
205   private void buildFilterEntry(FilterSchema filter, StringBuilder sb) {
206
207     sb.append("\"" + filter.getName()).append("\": {");
208
209     sb.append(filter.getConfiguration());
210
211     sb.append("}");
212   }
213
214
215   /**
216    * Constructs an ElasticSearch friendly custom analyzer definition.
217    *
218    * @param analyzer - The analyzer to generate ElasticSearch json for.
219    * @param sb       - The string builder to append the analyzer definition
220    *                 to.
221    */
222   private void buildAnalyzerEntry(AnalyzerSchema analyzer, StringBuilder sb) {
223
224     sb.append("\"").append(analyzer.getName()).append("\": {");
225     sb.append("\"type\": \"custom\",");
226     sb.append("\"tokenizer\": ").append("\"").append(analyzer.getTokenizer()).append("\",");
227     sb.append("\"filter\": [");
228     boolean firstFilter = true;
229     for (String filter : analyzer.getFilters()) {
230       if (!firstFilter) {
231         sb.append(",");
232       } else {
233         firstFilter = false;
234       }
235       sb.append("\"").append(filter).append("\"");
236     }
237     sb.append("]");
238     sb.append("}");
239   }
240 }