2 * Copyright © 2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.openecomp.sdcrests.item.rest.services;
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;
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;
47 public class CatalogNotifier {
49 private static final Logger LOGGER = LoggerFactory.getLogger(CatalogNotifier.class);
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/";
59 private static String configurationYamlFile = System.getProperty(CONFIG_FILE);
60 private static String notifyCatalogUrl;
62 private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
66 Function<InputStream, Map<String, LinkedHashMap<String, Object>>> reader = is -> {
67 YamlUtil yamlUtil = new YamlUtil();
68 return yamlUtil.yamlToMap(is);
71 Map<String, LinkedHashMap<String, Object>> configurationMap;
74 configurationMap = readFromFile(configurationYamlFile, reader);
76 } catch (IOException e) {
77 throw new RuntimeException("Could not read configuration file configuration.yaml");
80 Object protocol = configurationMap.get(PROTOCOL_KEY);
81 Object host = configurationMap.get(HOST_KEY);
82 Object port = configurationMap.get(PORT_KEY);
84 if (protocol == null || host == null || port == null) {
85 throw new RuntimeException("Could not read configuration file configuration.yaml");
88 if (configurationMap.get(URL_KEY) != null) {
89 String urlFormat = String.valueOf(configurationMap.get(URL_KEY));
91 String.format(urlFormat, String.valueOf(protocol), String.valueOf(host), String.valueOf(port));
94 notifyCatalogUrl = String.format(URL_DEFAULT_FORMAT, String.valueOf(protocol), String.valueOf(host),
95 String.valueOf(port));
100 public void execute(Collection<String> itemIds, ItemAction action, int numOfRetries) {
102 String userId = SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId();
104 Callable callable = createCallable(JsonUtil.object2Json(itemIds), action, numOfRetries, userId);
106 executor.submit(callable);
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);
116 private Void handleHttpRequest(String url, String itemIds, ItemAction action, String userId,
119 try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
120 HttpPost request = createPostRequest(url, itemIds, userId);
121 HttpResponse response = httpclient.execute(request);
123 String.format("Catalog notification on vspId - %s action - %s. Response: %s", itemIds,
124 action.name(), response.getStatusLine()));
126 if (numOfRetries > 1 && response.getStatusLine().getStatusCode() == 500) {
128 createCallable(getFailedIds(itemIds, response.getEntity()), action, --numOfRetries, userId);
129 executor.schedule(callable, 5 , TimeUnit.SECONDS);
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()));
139 private String getFailedIds(String itemIds, HttpEntity responseBody) {
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");
146 return JsonUtil.object2Json(itemIds);
149 private HttpPost createPostRequest(String postUrl, String itemIds, String userId)
150 throws UnsupportedEncodingException {
152 HttpPost request = new HttpPost(postUrl);
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);
158 HttpEntity entity = new StringEntity(itemIds);
159 request.setEntity(entity);
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";
171 LOGGER.error("Catalog notification on URL - " + notifyCatalogUrl + actionStr);
172 return notifyCatalogUrl + actionStr;
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);