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