re base code
[sdc.git] / catalog-dao / src / main / java / org / openecomp / sdc / be / dao / api / ESGenericIdDAO.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.sdc.be.dao.api;
22
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;
34
35 import javax.annotation.Resource;
36 import java.io.IOException;
37 import java.util.*;
38
39 public abstract class ESGenericIdDAO implements IGenericIdDAO {
40
41         private static Logger log = Logger.getLogger(ESGenericIdDAO.class.getName());
42
43         @Resource(name = "elasticsearch-client")
44         private ElasticSearchClient esClient;
45
46         private ObjectMapper jsonMapper = new ObjectMapper();
47         private final Map<String, String> typesToIndices = new HashMap<>();
48
49         public Client getClient() {
50                 return this.esClient.getClient();
51         }
52
53         public ElasticSearchClient getEsClient() {
54                 return esClient;
55         }
56
57         public ObjectMapper getJsonMapper() {
58                 return jsonMapper;
59         }
60
61         public void setJsonMapper(ObjectMapper jsonMapper) {
62                 this.jsonMapper = jsonMapper;
63         }
64
65         public void addToIndicesMap(String type, String index) {
66                 typesToIndices.put(type, index);
67         }
68
69         public String getIndexForType(String type) {
70                 return typesToIndices.get(type);
71         }
72
73         @Override
74         public <T> T findById(String typeName, String id, Class<T> clazz) {
75
76                 String indexName = getIndexForType(typeName);
77                 GetResponse response = getClient().prepareGet(indexName, typeName, id).execute().actionGet();
78
79                 if (response == null || !response.isExists()) {
80                         log.debug("Nothing found in index <{}>, type <{}>, for Id <{}>.", indexName, typeName, id);
81                         return null;
82                 }
83
84                 log.debug("Found one in index <{}>, type <{}>, for Id <{}>.", indexName, typeName, id);
85
86                 T ret = null;
87                 try {
88                         ret = (T) jsonMapper.readValue(response.getSourceAsString(), clazz);
89                 } catch (IOException e) {
90                         throw new RuntimeException(e);
91                 }
92                 return ret;
93         }
94
95         @Override
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();
99
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));
103                         return null;
104                 }
105
106                 List<T> result = new ArrayList<>();
107                 for (MultiGetItemResponse getItemResponse : response.getResponses()) {
108                         if (getItemResponse.getResponse().isExists()) {
109                                 T val = null;
110                                 try {
111                                         val = jsonMapper.readValue(getItemResponse.getResponse().getSourceAsString(), clazz);
112                                         result.add(val);
113                                 } catch (IOException e) {
114                                         throw new RuntimeException(e);
115                                 }
116                         }
117                 }
118
119                 return result;
120         }
121
122         protected void saveResourceData(String typeName, Object data, String id) throws JsonProcessingException {
123                 String indexName = getIndexForType(typeName);
124
125                 log.debug("ESGenericIdDAO saveResourceData resource indexName: {} | typeName is: {}", indexName, typeName);
126
127                 String json = getJsonMapper().writeValueAsString(data);
128                 log.debug("ESGenericIdDAO saveResourceData resource id is: {}", id);
129                 try {
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,
133                                         e.getMessage(), e);
134                         throw e;
135                 }
136         }
137
138         @Override
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();
143         }
144
145         public void deleteIndex(String indexName) {
146                 DeleteIndexResponse actionGet = getClient().admin().indices().delete(new DeleteIndexRequest(indexName))
147                                 .actionGet();
148                 if (!actionGet.isAcknowledged()) {
149                         log.error("failed to delete index {}", indexName);
150                 }
151         }
152
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 + ">.");
157                 }
158         }
159
160         public static String indexTypeFromClass(Class<?> clazz) {
161                 return clazz.getSimpleName().toLowerCase();
162         }
163 }