notify catalog on items action
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / item-rest / item-rest-services / src / main / java / org / openecomp / sdcrests / item / rest / services / CatalogNotifier.java
1 /*
2  * Copyright © 2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdcrests.item.rest.services;
18
19 import java.io.FileInputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.UnsupportedEncodingException;
23 import java.util.Collection;
24 import java.util.LinkedHashMap;
25 import java.util.Map;
26 import java.util.concurrent.Callable;
27 import java.util.concurrent.Executors;
28 import java.util.concurrent.ScheduledExecutorService;
29 import java.util.concurrent.TimeUnit;
30 import java.util.function.Function;
31 import javax.ws.rs.core.HttpHeaders;
32 import javax.ws.rs.core.MediaType;
33 import org.apache.http.HttpEntity;
34 import org.apache.http.HttpResponse;
35 import org.apache.http.client.methods.HttpPost;
36 import org.apache.http.entity.StringEntity;
37 import org.apache.http.impl.client.CloseableHttpClient;
38 import org.apache.http.impl.client.HttpClients;
39 import org.onap.sdc.tosca.services.YamlUtil;
40 import org.openecomp.core.utilities.json.JsonUtil;
41 import org.openecomp.sdc.common.session.SessionContextProviderFactory;
42 import org.openecomp.sdc.logging.api.Logger;
43 import org.openecomp.sdc.logging.api.LoggerFactory;
44 import org.openecomp.sdc.logging.api.LoggingContext;
45 import org.openecomp.sdcrests.item.types.ItemAction;
46
47 public class CatalogNotifier {
48
49     private static final Logger LOGGER = LoggerFactory.getLogger(CatalogNotifier.class);
50
51     private static final String USER_ID_HEADER_PARAM = "USER_ID";
52     private static final String CONFIG_FILE = "configuration.yaml";
53     private static final String PROTOCOL_KEY = "beProtocol";
54     private static final String HOST_KEY = "beFqdn";
55     private static final String PORT_KEY = "beHttpPort";
56     private static final String URL_KEY = "onboardCatalogNotificationUrl";
57     private static final String URL_DEFAULT_FORMAT = "%s://%s:%s/sdc2/rest/v1/catalog/notif/vsp/";
58
59     private static String configurationYamlFile = System.getProperty(CONFIG_FILE);
60     private static String notifyCatalogUrl;
61
62     private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
63
64
65     static {
66         Function<InputStream, Map<String, LinkedHashMap<String, Object>>> reader = is -> {
67             YamlUtil yamlUtil = new YamlUtil();
68             return yamlUtil.yamlToMap(is);
69         };
70
71         Map<String, LinkedHashMap<String, Object>> configurationMap;
72
73         try {
74             configurationMap = readFromFile(configurationYamlFile, reader);
75
76         } catch (IOException e) {
77             throw new RuntimeException("Could not read configuration file configuration.yaml");
78         }
79
80         Object protocol = configurationMap.get(PROTOCOL_KEY);
81         Object host = configurationMap.get(HOST_KEY);
82         Object port = configurationMap.get(PORT_KEY);
83
84         if (protocol == null || host == null || port == null) {
85             throw new RuntimeException("Could not read configuration file configuration.yaml");
86         }
87
88         if (configurationMap.get(URL_KEY) != null) {
89             String urlFormat = String.valueOf(configurationMap.get(URL_KEY));
90             notifyCatalogUrl =
91                     String.format(urlFormat, String.valueOf(protocol), String.valueOf(host), String.valueOf(port));
92
93         } else {
94             notifyCatalogUrl = String.format(URL_DEFAULT_FORMAT, String.valueOf(protocol), String.valueOf(host),
95                     String.valueOf(port));
96         }
97     }
98
99
100     public void execute(Collection<String> itemIds, ItemAction action, int numOfRetries) {
101
102         String userId = SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId();
103
104         Callable callable = createCallable(JsonUtil.object2Json(itemIds), action, numOfRetries, userId);
105
106         executor.submit(callable);
107
108     }
109
110     private Callable createCallable(String itemIds, ItemAction action, int numOfRetries, String userId) {
111         Callable callable = () -> handleHttpRequest(getUrl(action), itemIds, action, userId, numOfRetries);
112         LoggingContext.copyToCallable(callable);
113         return callable;
114     }
115
116     private Void handleHttpRequest(String url, String itemIds, ItemAction action, String userId,
117             int numOfRetries) {
118
119         try (CloseableHttpClient httpclient =  HttpClients.createDefault()) {
120             HttpPost request = createPostRequest(url, itemIds, userId);
121             HttpResponse response = httpclient.execute(request);
122             LOGGER.error(
123                     String.format("Catalog notification on vspId - %s action  - %s. Response: %s", itemIds,
124                             action.name(), response.getStatusLine()));
125
126             if (numOfRetries > 1 && response.getStatusLine().getStatusCode() == 500) {
127                 Callable callable =
128                         createCallable(getFailedIds(itemIds, response.getEntity()), action, --numOfRetries, userId);
129                 executor.schedule(callable, 5 , TimeUnit.SECONDS);
130             }
131
132         } catch (Exception e) {
133             LOGGER.error(String.format("Catalog notification on vspId - %s action  - %s FAILED. Error: %S",
134                     itemIds.toString(), action.name(), e.getMessage()));
135         }
136         return null;
137     }
138
139     private String getFailedIds(String itemIds, HttpEntity responseBody) {
140         try {
141             Map jsonBody = JsonUtil.json2Object(responseBody.getContent(), Map.class);
142             return jsonBody.get("failedIds").toString();
143         } catch (Exception e) {
144             LOGGER.error("Catalog Notification RETRY - no failed IDs in response");
145         }
146         return JsonUtil.object2Json(itemIds);
147     }
148
149     private HttpPost createPostRequest(String postUrl, String itemIds, String userId)
150             throws UnsupportedEncodingException {
151
152         HttpPost request = new HttpPost(postUrl);
153
154         request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
155         request.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
156         request.addHeader(USER_ID_HEADER_PARAM, userId);
157
158         HttpEntity entity = new StringEntity(itemIds);
159         request.setEntity(entity);
160
161         return request;
162     }
163
164     private String getUrl(ItemAction action) {
165         String actionStr = "";
166         if (action == ItemAction.ARCHIVE) {
167             actionStr = "archived";
168         } else if (action == ItemAction.RESTORE) {
169             actionStr = "restored";
170         }
171         LOGGER.error("Catalog notification on URL - " + notifyCatalogUrl + actionStr);
172         return notifyCatalogUrl + actionStr;
173     }
174
175     private static <T> T readFromFile(String file, Function<InputStream, T> reader) throws IOException {
176         try (InputStream is = new FileInputStream(file)) {
177             return reader.apply(is);
178         }
179     }
180 }