aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/aai/sa/rest/AnalysisConfiguration.java
blob: f30075a4dc2bae314a4a1ab249b12e0b1ab4ebdd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
 * Copyright © 2017-2018 Amdocs
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.onap.aai.sa.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.onap.aai.cl.api.Logger;
import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
import org.onap.aai.sa.searchdbabstraction.util.SearchDbConstants;

/**
 * This class encapsulates the configuration of the predefined
 * Analyzer and Filter behaviours that help to tell the document
 * store how to index the documents that are provided to it.
 */
public class AnalysisConfiguration {

  /**
   * Contains all of the predefined indexing filters.
   */
  private FilterSchema[] customFilters;

  /**
   * Contains all of the predefined indexing analyzers.
   */
  private AnalyzerSchema[] customAnalysers;

  /**
   * Indicates whether or not we have imported the filter and
   * analyzer configurations.
   */
  private AtomicBoolean configured = new AtomicBoolean(false);

  /**
   * A json format string which is readable by Elastic Search and defines
   * all of the custom filters and analyzers that we need Elastic Search
   * to know about.
   */
  private String esSettings = null;

  private static Logger logger = LoggerFactory.getInstance()
      .getLogger(AnalysisConfiguration.class.getName());


  /**
   * Imports the filter and analyzer configuration files and
   * builds an Elastic Search readable settings file from the
   * contents.
   *
   * @param filterConfigFile   - Location of filter configuration json file
   * @param analyzerConfigFile - Location of analyzer configuration json file
   */
  public void init(String filterConfigFile, String analyzerConfigFile) {

    if (configured.compareAndSet(false, true)) {
      ObjectMapper mapper = new ObjectMapper();

      File filtersConfig = new File(filterConfigFile);
      try {
        customFilters = mapper.readValue(filtersConfig, FilterSchema[].class);
      } catch (IOException e) {

        // generate log
        logger.warn(SearchDbMsgs.FILTERS_CONFIG_FAILURE, filterConfigFile, e.getMessage());
      }

      File analysersConfig = new File(analyzerConfigFile);
      try {
        customAnalysers = mapper.readValue(analysersConfig, AnalyzerSchema[].class);
      } catch (IOException e) {

        // generate log
        logger.warn(SearchDbMsgs.ANALYSYS_CONFIG_FAILURE, analyzerConfigFile, e.getMessage());
      }

      esSettings = buildEsIndexSettings();
    }
  }


  /**
   * Returns the set of pre-configured filters.
   *
   * @return - An array of filters.
   */
  public FilterSchema[] getFilters() {
    return customFilters;
  }


  /**
   * Returns the set of pre-configured analyzers.
   *
   * @return - An array of analyzers.
   */
  public AnalyzerSchema[] getAnalyzers() {
    init(SearchDbConstants.SDB_FILTER_CONFIG_FILE, SearchDbConstants.SDB_ANALYSIS_CONFIG_FILE);
    return customAnalysers;
  }


  /**
   * Imports the filter and analyzer configurations and translates those
   * into a settings string that will be parseable by Elastic Search.
   *
   * @return - Elastic Search formatted settings string.
   */
  public String getEsIndexSettings() {

    // Generate the es-settings string from our filter and analyzer
    // configurations if we have not already done so.
    init(SearchDbConstants.SDB_FILTER_CONFIG_FILE, SearchDbConstants.SDB_ANALYSIS_CONFIG_FILE);

    // Now, return the es-settings string.
    return esSettings;
  }


  /**
   * Constructs a settings string that is readable by Elastic Search based
   * on the contents of the filter and analyzer configuration files.
   *
   * @return Elastic Search formatted settings string.
   */
  public String buildEsIndexSettings() {

    StringBuilder sb = new StringBuilder();

    sb.append("{");
    sb.append("\"analysis\": {");

    // Define the custom filters.
    boolean atLeastOneFilter = false;
    sb.append("\"filter\": {");
    AtomicBoolean firstFilter = new AtomicBoolean(true);
    for (FilterSchema filter : customFilters) {

      // Append a comma before the next entry, unless it is the
      // first one.
      if (!firstFilter.compareAndSet(true, false)) {
        sb.append(", ");
      }

      // Now, build the filter entry.
      buildFilterEntry(filter, sb);
      atLeastOneFilter = true;
    }
    sb.append((atLeastOneFilter) ? "}," : "}");

    // Define the custom analyzers.
    sb.append("\"analyzer\": {");
    AtomicBoolean firstAnalyzer = new AtomicBoolean(true);
    for (AnalyzerSchema analyzer : customAnalysers) {

      // Prepend a comma before the entry, unless it is the
      // first one.
      if (!firstAnalyzer.compareAndSet(true, false)) {
        sb.append(",");
      }

      // Now, construct the entry for this analyzer.
      buildAnalyzerEntry(analyzer, sb);
    }
    sb.append("}");

    sb.append("}");
    sb.append("}");

    return sb.toString();
  }


  /**
   * Constructs an ElasticSearch friendly custom filter definition.
   *
   * @param filter - The filter to generate ElasticSearch json for.
   * @param sb     - The string builder to append the filter definition
   *               to.
   */
  private void buildFilterEntry(FilterSchema filter, StringBuilder sb) {

    sb.append("\"" + filter.getName()).append("\": {");

    sb.append(filter.getConfiguration());

    sb.append("}");
  }


  /**
   * Constructs an ElasticSearch friendly custom analyzer definition.
   *
   * @param analyzer - The analyzer to generate ElasticSearch json for.
   * @param sb       - The string builder to append the analyzer definition
   *                 to.
   */
  private void buildAnalyzerEntry(AnalyzerSchema analyzer, StringBuilder sb) {

    sb.append("\"").append(analyzer.getName()).append("\": {");
    sb.append("\"type\": \"custom\",");
    sb.append("\"tokenizer\": ").append("\"").append(analyzer.getTokenizer()).append("\",");
    sb.append("\"filter\": [");
    boolean firstFilter = true;
    for (String filter : analyzer.getFilters()) {
      if (!firstFilter) {
        sb.append(",");
      } else {
        firstFilter = false;
      }
      sb.append("\"").append(filter).append("\"");
    }
    sb.append("]");
    sb.append("}");
  }
}