1 /*******************************************************************************
2 * ============LICENSE_START========================================================================
3 * ONAP : ccsdk feature sdnr wt
4 * =================================================================================================
5 * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6 * =================================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8 * in compliance with the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software distributed under the License
13 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14 * or implied. See the License for the specific language governing permissions and limitations under
16 * ============LICENSE_END==========================================================================
17 ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.common.database;
20 import java.io.IOException;
21 import java.util.List;
22 import javax.annotation.Nonnull;
23 import javax.annotation.Nullable;
25 import org.json.JSONObject;
26 import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo;
27 import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilder;
28 import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders;
29 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteByQueryRequest;
30 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteRequest;
31 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.GetIndexRequest;
32 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.GetRequest;
33 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.IndexRequest;
34 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.RefreshIndexRequest;
35 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.SearchRequest;
36 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.UpdateByQueryRequest;
37 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.UpdateRequest;
38 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.DeleteByQueryResponse;
39 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.DeleteResponse;
40 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.GetResponse;
41 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.IndexResponse;
42 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.RefreshIndexResponse;
43 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.SearchResponse;
44 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.UpdateByQueryResponse;
45 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.UpdateResponse;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * @author Herbert, Micha
52 * Hint: Elasticsearch index/alias and doctype will be the same value
53 * server side restricted since ES 5.0
56 public class HtDatabaseClient extends ExtRestClient implements DatabaseClient, AutoCloseable {
58 private static final boolean REFRESH_AFTER_REWRITE_DEFAULT = true;
60 private final Logger LOG = LoggerFactory.getLogger(HtDatabaseClient.class);
62 private boolean doRefreshAfterWrite;
63 public HtDatabaseClient(HostInfo[] hosts) {
64 this(hosts,REFRESH_AFTER_REWRITE_DEFAULT);
66 public HtDatabaseClient(HostInfo[] hosts, boolean refreshAfterWrite) {
68 this.doRefreshAfterWrite = refreshAfterWrite;
71 public HtDatabaseClient(HostInfo[] hosts, boolean refreshAfterWrite,String username,String password) {
72 super(hosts,username,password);
73 this.doRefreshAfterWrite = refreshAfterWrite;
75 public HtDatabaseClient(HostInfo[] hosts,String username,String password) {
76 this(hosts,REFRESH_AFTER_REWRITE_DEFAULT,username,password);
81 /*----------------------------------
92 } catch (IOException e) {
93 LOG.warn("Problem closing db client: {}",e);
98 public boolean isExistsIndex(String esIndexAlias) {
100 LOG.debug("Check status of ES index: {}", esIndexAlias);
102 GetIndexRequest request = new GetIndexRequest(esIndexAlias);
104 boolean indexStatus = false;
106 indexStatus = this.indicesExists(request);
107 } catch (IOException e) {
108 LOG.warn("Problem checking index for {}: {}",esIndexAlias,e);
116 public @Nullable String doWriteJsonString(String dataTypeName, @Nonnull IsEsObject esId, String json) {
117 return doWriteRaw(dataTypeName, esId.getEsId(), json);
121 public @Nullable String doWriteRaw(String dataTypeName, @Nullable String esId, String json) {
122 return this.doWriteRaw(dataTypeName, dataTypeName, esId, json);
125 public @Nullable String doWriteRaw(String indexName,String dataTypeName, @Nullable String esId, String json) {
127 IndexResponse response = null;
128 IndexRequest indexRequest = new IndexRequest(indexName,dataTypeName,esId);
129 indexRequest.source(json);
131 response = this.index(indexRequest );
132 } catch (IOException e) {
133 LOG.warn("ES Exception {} Json: {}", e.getMessage(), json);
136 if (response == null) {
137 LOG.warn("Response null during write: {} {}", esId, json);
140 if(this.doRefreshAfterWrite) {
141 this.doRefresh(dataTypeName);
143 return response.getId();
146 private void doRefresh(String dataTypeName) {
148 RefreshIndexResponse response = this.refreshIndex(new RefreshIndexRequest(dataTypeName));
149 if(!response.succeeded()) {
150 LOG.warn("seems that index {} was not refreshed",dataTypeName);
152 } catch (IOException e) {
153 LOG.warn("problem with refreshing index: {}",e);
158 public boolean doRemove(String dataTypeName, IsEsObject esId) {
159 return doRemove(dataTypeName, esId.getEsId());
164 public boolean doRemove(String dataTypeName, String esId) {
165 DeleteRequest deleteRequest = new DeleteRequest(dataTypeName,dataTypeName,esId);
166 DeleteResponse response = null;
168 response = this.delete(deleteRequest);
169 } catch (IOException e) {
170 LOG.warn("Problem deleting from db: {}",e.getMessage());
172 if(this.doRefreshAfterWrite) {
173 this.doRefresh(dataTypeName);
175 return response!=null?response.isDeleted():false;
179 public @Nullable String doReadJsonData(String dataTypeName, @Nonnull IsEsObject esId) {
181 if (esId.getEsId() == null) {
182 throw new IllegalArgumentException("Read access to object without database Id");
185 return doReadJsonData(dataTypeName, esId.getEsId());
189 public @Nullable String doReadJsonData(String dataTypeName, @Nonnull String esId) {
191 LOG.debug("NetworkIndex read: {}", dataTypeName);
192 GetRequest getRequest = new GetRequest(dataTypeName,dataTypeName,esId);
193 GetResponse response = null;
195 response = this.get(getRequest);
196 } catch (IOException e) {
197 LOG.warn("problem reading data {} with id {}: {}",dataTypeName,esId,e);
199 return response!=null && response.isExists() ? response.getSourceAsBytesRef() : null;
203 public @Nonnull SearchResult<SearchHit> doReadByQueryJsonData(String dataTypeName, QueryBuilder queryBuilder) {
205 return this.doReadByQueryJsonData(dataTypeName, queryBuilder, false);
209 public @Nonnull SearchResult<SearchHit> doReadByQueryJsonData(String dataTypeName,QueryBuilder queryBuilder, boolean ignoreException) {
212 LOG.debug("NetworkIndex query and read: {}", dataTypeName);
214 SearchRequest searchRequest = new SearchRequest(dataTypeName, dataTypeName);
215 searchRequest.setQuery(queryBuilder);
216 SearchResponse response = null;
218 response = this.search(searchRequest,ignoreException);
219 total = response.getTotal();
221 } catch (IOException e) {
222 LOG.warn("error do search {}: {}", queryBuilder, e);
224 return new SearchResult<SearchHit>(response != null ? response.getHits() : new SearchHit[] {}, total);
227 public @Nonnull SearchResult<SearchHit> doReadAllJsonData(String dataTypeName) {
228 return this.doReadAllJsonData( dataTypeName,false);
231 public @Nonnull SearchResult<SearchHit> doReadAllJsonData( String dataTypeName, boolean ignoreException) {
233 return doReadByQueryJsonData( dataTypeName, QueryBuilders.matchAllQuery(),ignoreException);
238 public String doUpdateOrCreate(String dataTypeName, String esId, String json) {
239 return this.doUpdateOrCreate(dataTypeName, esId, json,null);
245 public String doUpdateOrCreate(String dataTypeName, String esId, String json, List<String> onlyForInsert) {
247 LOG.warn("try to update or insert {} with id null is not allowed.",dataTypeName);
250 boolean success = false;
251 UpdateRequest request = new UpdateRequest(dataTypeName, dataTypeName, esId);
252 request.source(new JSONObject(json),onlyForInsert);
254 UpdateResponse response = this.update(request);
255 success = response.succeeded();
256 } catch (IOException e) {
257 LOG.warn("Problem updating {} with id {} and data {}: {}", dataTypeName, esId, json, e);
259 if(this.doRefreshAfterWrite) {
260 this.doRefresh(dataTypeName);
262 return success ? esId : null;
265 public String doUpdate(String dataTypeName, String json, QueryBuilder query) {
266 boolean success = false;
267 UpdateByQueryRequest request = new UpdateByQueryRequest(dataTypeName, dataTypeName );
268 request.source(new JSONObject(json),query);
270 UpdateByQueryResponse response = this.update(request);
271 success = !response.hasFailures();
272 } catch (IOException e) {
273 LOG.warn("Problem updating items in {} with query {} and data {}: {}", dataTypeName, query, json, e);
275 if(this.doRefreshAfterWrite) {
276 this.doRefresh(dataTypeName);
278 return success?"":null;
284 public int doRemove(String dataTypeName, QueryBuilder query) {
286 DeleteByQueryRequest request = new DeleteByQueryRequest(dataTypeName);
287 request.source(query);
289 DeleteByQueryResponse response = this.deleteByQuery(request);
290 del = response.getDeleted();
291 } catch (IOException e) {
292 LOG.warn("Problem delete in {} with query {}:{} ", dataTypeName, query.toJSON(), e);
294 if(this.doRefreshAfterWrite) {
295 this.doRefresh(dataTypeName);