4f2b7aed63cbe205a53a749cbb54648d7376a090
[sdc.git] /
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 javax.ws.rs.core.Response;
34 import org.apache.http.HttpEntity;
35 import org.apache.http.HttpResponse;
36 import org.apache.http.client.methods.HttpPost;
37 import org.apache.http.entity.StringEntity;
38 import org.apache.http.impl.client.CloseableHttpClient;
39 import org.apache.http.impl.client.HttpClients;
40 import org.onap.sdc.tosca.services.YamlUtil;
41 import org.openecomp.core.utilities.json.JsonUtil;
42 import org.openecomp.sdc.common.session.SessionContextProviderFactory;
43 import org.openecomp.sdc.logging.api.Logger;
44 import org.openecomp.sdc.logging.api.LoggerFactory;
45 import org.openecomp.sdc.logging.api.LoggingContext;
46 import org.openecomp.sdcrests.item.types.ItemAction;
47
48  class CatalogNotifier {
49
50     private static final Logger LOGGER = LoggerFactory.getLogger(CatalogNotifier.class);
51
52     private static final String USER_ID_HEADER_PARAM = "USER_ID";
53     private static final String CONFIG_FILE = "configuration.yaml";
54     private static final String PROTOCOL_KEY = "beProtocol";
55     private static final String HTTP_PROTOCOL = "http|HTTP";
56     private static final String HTTPS_PROTOCOL = "https|HTTPS";
57     private static final String HOST_KEY = "beFqdn";
58     private static final String HTTP_PORT_KEY = "beHttpPort";
59     private static final String HTTPS_PORT_KEY = "beSslPort";
60     private static final String URL_KEY = "onboardCatalogNotificationUrl";
61     private static final String URL_DEFAULT_FORMAT = "%s://%s:%s/sdc2/rest/v1/catalog/notif/vsp/";
62
63     private static String configurationYamlFile = System.getProperty(CONFIG_FILE);
64     private static String notifyCatalogUrl;
65
66     private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
67
68
69     static {
70         Function<InputStream, Map<String, LinkedHashMap<String, Object>>> reader = is -> {
71             YamlUtil yamlUtil = new YamlUtil();
72             return yamlUtil.yamlToMap(is);
73         };
74
75         Map<String, LinkedHashMap<String, Object>> configurationMap;
76
77         try {
78             configurationMap = readFromFile(configurationYamlFile, reader);
79             Object protocol = configurationMap.get(PROTOCOL_KEY);
80             Object host = configurationMap.get(HOST_KEY);
81
82             if (protocol == null || host == null) {
83                 throw new ExceptionInInitializerError("Could not read configuration file configuration.yaml.");
84             }
85
86             Object port = null;
87             if (String.valueOf(protocol).matches(HTTP_PROTOCOL)) {
88                 port = configurationMap.get(HTTP_PORT_KEY);
89             }
90             if (String.valueOf(protocol).matches(HTTPS_PROTOCOL)) {
91                 port = configurationMap.get(HTTPS_PORT_KEY);
92             }
93
94             if (configurationMap.get(URL_KEY) != null) {
95                 String urlFormat = String.valueOf(configurationMap.get(URL_KEY));
96                 notifyCatalogUrl =
97                         String.format(urlFormat, String.valueOf(protocol), String.valueOf(host), String.valueOf(port));
98
99             } else {
100                 notifyCatalogUrl = String.format(URL_DEFAULT_FORMAT, String.valueOf(protocol), String.valueOf(host),
101                         String.valueOf(port));
102             }
103
104         } catch (Exception e) {
105             throw new ExceptionInInitializerError(
106                     "Could not read configuration file configuration.yaml. Error: " + e.getMessage());
107
108         }
109     }
110
111
112     public void execute(Collection<String> itemIds, ItemAction action, int numOfRetries) {
113
114         String userId = SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId();
115
116         Callable callable = createCallable(JsonUtil.object2Json(itemIds), action, numOfRetries, userId);
117
118         executor.submit(callable);
119
120     }
121
122     private Callable createCallable(String itemIds, ItemAction action, int numOfRetries, String userId) {
123         Callable callable = () -> handleHttpRequest(getUrl(action), itemIds, action, userId, numOfRetries);
124         LoggingContext.copyToCallable(callable);
125         return callable;
126     }
127
128     private Void handleHttpRequest(String url, String itemIds, ItemAction action, String userId,
129             int numOfRetries) {
130
131         try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
132             HttpPost request = createPostRequest(url, itemIds, userId);
133             HttpResponse response = httpclient.execute(request);
134             LOGGER.debug(String.format("Catalog notification on vspId - %s action  - %s. Response: %s", itemIds,
135                     action.name(), response.getStatusLine()));
136
137             if (numOfRetries > 1 && response.getStatusLine().getStatusCode() == Response.Status.INTERNAL_SERVER_ERROR
138                                                                                         .getStatusCode()) {
139                 Callable callable =
140                         createCallable(getFailedIds(itemIds, response.getEntity()), action, --numOfRetries, userId);
141                 executor.schedule(callable, 5, TimeUnit.SECONDS);
142             }
143
144         } catch (Exception e) {
145             LOGGER.error(String.format("Catalog notification on vspId - %s action  - %s FAILED. Error: %S", itemIds,
146                     action.name(), e.getMessage()));
147         }
148         return null;
149     }
150
151     private String getFailedIds(String itemIds, HttpEntity responseBody) {
152         try {
153             Map jsonBody = JsonUtil.json2Object(responseBody.getContent(), Map.class);
154             return jsonBody.get("failedIds").toString();
155         } catch (Exception e) {
156             LOGGER.error("Catalog Notification RETRY - no failed IDs in response");
157         }
158         return JsonUtil.object2Json(itemIds);
159     }
160
161     private HttpPost createPostRequest(String postUrl, String itemIds, String userId)
162             throws UnsupportedEncodingException {
163
164         HttpPost request = new HttpPost(postUrl);
165
166         request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
167         request.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
168         request.addHeader(USER_ID_HEADER_PARAM, userId);
169
170         HttpEntity entity = new StringEntity(itemIds);
171         request.setEntity(entity);
172
173         return request;
174     }
175
176     private String getUrl(ItemAction action) {
177         String actionStr = "";
178         if (action == ItemAction.ARCHIVE) {
179             actionStr = "archived";
180         } else if (action == ItemAction.RESTORE) {
181             actionStr = "restored";
182         }
183         LOGGER.debug("Catalog notification URL - " + notifyCatalogUrl + actionStr);
184         return notifyCatalogUrl + actionStr;
185     }
186
187     private static <T> T readFromFile(String file, Function<InputStream, T> reader) throws IOException {
188         try (InputStream is = new FileInputStream(file)) {
189             return reader.apply(is);
190         }
191     }
192 }