2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.dao.api;
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
26 import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
27 import org.elasticsearch.action.get.GetResponse;
28 import org.elasticsearch.action.get.MultiGetItemResponse;
29 import org.elasticsearch.action.get.MultiGetResponse;
30 import org.elasticsearch.client.Client;
31 import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
32 import org.openecomp.sdc.common.log.wrappers.Logger;
33 import org.openecomp.sdc.exception.IndexingServiceException;
35 import javax.annotation.Resource;
36 import java.io.IOException;
39 public abstract class ESGenericIdDAO implements IGenericIdDAO {
41 private static Logger log = Logger.getLogger(ESGenericIdDAO.class.getName());
43 @Resource(name = "elasticsearch-client")
44 private ElasticSearchClient esClient;
46 private ObjectMapper jsonMapper = new ObjectMapper();
47 private final Map<String, String> typesToIndices = new HashMap<>();
49 public Client getClient() {
50 return this.esClient.getClient();
53 public ElasticSearchClient getEsClient() {
57 public ObjectMapper getJsonMapper() {
61 public void setJsonMapper(ObjectMapper jsonMapper) {
62 this.jsonMapper = jsonMapper;
65 public void addToIndicesMap(String type, String index) {
66 typesToIndices.put(type, index);
69 public String getIndexForType(String type) {
70 return typesToIndices.get(type);
74 public <T> T findById(String typeName, String id, Class<T> clazz) {
76 String indexName = getIndexForType(typeName);
77 GetResponse response = getClient().prepareGet(indexName, typeName, id).execute().actionGet();
79 if (response == null || !response.isExists()) {
80 log.debug("Nothing found in index <{}>, type <{}>, for Id <{}>.", indexName, typeName, id);
84 log.debug("Found one in index <{}>, type <{}>, for Id <{}>.", indexName, typeName, id);
88 ret = (T) jsonMapper.readValue(response.getSourceAsString(), clazz);
89 } catch (IOException e) {
90 throw new RuntimeException(e);
96 public <T> List<T> findByIds(String typeName, Class<T> clazz, String... ids) {
97 String indexName = getIndexForType(typeName);
98 MultiGetResponse response = getClient().prepareMultiGet().add(indexName, typeName, ids).execute().actionGet();
100 if (response == null || response.getResponses() == null || response.getResponses().length == 0) {
101 log.debug("Nothing found in index <{}>, type <{}>, for Ids <{}>.", indexName, typeName,
102 Arrays.toString(ids));
106 List<T> result = new ArrayList<>();
107 for (MultiGetItemResponse getItemResponse : response.getResponses()) {
108 if (getItemResponse.getResponse().isExists()) {
111 val = jsonMapper.readValue(getItemResponse.getResponse().getSourceAsString(), clazz);
113 } catch (IOException e) {
114 throw new RuntimeException(e);
122 protected void saveResourceData(String typeName, Object data, String id) throws JsonProcessingException {
123 String indexName = getIndexForType(typeName);
125 log.debug("ESGenericIdDAO saveResourceData resource indexName: {} | typeName is: {}", indexName, typeName);
127 String json = getJsonMapper().writeValueAsString(data);
128 log.debug("ESGenericIdDAO saveResourceData resource id is: {}", id);
130 getClient().prepareIndex(indexName, typeName, id).setSource(json).setRefresh(true).execute().actionGet();
131 } catch (Exception e) {
132 log.error("failed to write data with id {} to elasticsearch type {}. error: {}", id, typeName,
139 public void delete(String typeName, String id) {
140 assertIdNotNullFor(id, "delete");
141 String indexName = getIndexForType(typeName);
142 getClient().prepareDelete(indexName, typeName, id).setRefresh(true).execute().actionGet();
145 public void deleteIndex(String indexName) {
146 DeleteIndexResponse actionGet = getClient().admin().indices().delete(new DeleteIndexRequest(indexName))
148 if (!actionGet.isAcknowledged()) {
149 log.error("failed to delete index {}", indexName);
153 private void assertIdNotNullFor(String id, String operation) {
154 if (id == null || id.trim().isEmpty()) {
155 log.error("Null or empty Id is not allowed for operation <{}>.", operation);
156 throw new IndexingServiceException("Null or empty Id is not allowed for operation <" + operation + ">.");
160 public static String indexTypeFromClass(Class<?> clazz) {
161 return clazz.getSimpleName().toLowerCase();