Repair widget micro service, onboarding of widgets
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / MicroserviceProxyServiceImpl.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
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  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.service;
21
22 import java.util.List;
23
24 import javax.servlet.http.HttpServletRequest;
25
26 import org.apache.commons.codec.binary.Base64;
27 import org.openecomp.portalapp.portal.domain.EPUser;
28 import org.openecomp.portalapp.portal.domain.MicroserviceData;
29 import org.openecomp.portalapp.portal.domain.MicroserviceParameter;
30 import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter;
31 import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
32 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
33 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
34 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
35 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
36 import org.openecomp.portalsdk.core.util.SystemProperties;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.context.annotation.EnableAspectJAutoProxy;
39 import org.springframework.http.HttpEntity;
40 import org.springframework.http.HttpHeaders;
41 import org.springframework.http.HttpMethod;
42 import org.springframework.http.MediaType;
43 import org.springframework.http.ResponseEntity;
44 import org.springframework.stereotype.Service;
45 import org.springframework.web.client.HttpClientErrorException;
46 import org.springframework.web.client.RestTemplate;
47
48 @Service("microserviceProxyService")
49 @EnableAspectJAutoProxy
50 @EPMetricsLog
51 public class MicroserviceProxyServiceImpl implements MicroserviceProxyService {
52
53         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyServiceImpl.class);
54         private static final String BASIC_AUTH = "Basic Authentication";
55         private static final String NO_AUTH = "No Authentication";
56         private static final String COOKIE_AUTH = "Cookie based Authentication";
57         private static final String QUESTION_MARK = "?";
58         private static final String ADD_MARK = "&";
59
60         String whatService = "widgets-service";
61
62         @Autowired
63         private ConsulHealthService consulHealthService;
64
65         @Autowired
66         MicroserviceService microserviceService;
67
68         @Autowired
69         WidgetParameterService widgetParameterService;
70
71         RestTemplate template = new RestTemplate();
72
73         @Override
74         public String proxyToDestination(long serviceId, EPUser user, HttpServletRequest request) throws Exception {
75
76                 String response = null;
77
78                 // get the microservice object by the id
79                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
80
81                 // No such microservice available
82                 if (data == null) {
83                         return response;
84                 }
85                 List<MicroserviceParameter> params = data.getParameterList();
86                 MicroserviceParameter userId_param = new MicroserviceParameter();
87                 userId_param.setPara_key("userId");
88                 userId_param.setPara_value(user.getOrgUserId());
89                 params.add(userId_param);
90
91                 if (data.getSecurityType().equals(NO_AUTH)) {
92                         HttpHeaders headers = new HttpHeaders();
93                         headers.setContentType(MediaType.APPLICATION_JSON);
94                         HttpEntity<String> entity = new HttpEntity<String>(headers);
95
96                         String url = microserviceUrlConverter(data, params);
97                         logger.debug(EELFLoggerDelegate.debugLogger, "Before making no authentication call: {}", url);
98                         response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
99                         logger.debug(EELFLoggerDelegate.debugLogger, "No authentication call response: {}", response);
100
101                 } else if (data.getSecurityType().equals(BASIC_AUTH)) {
102                         // encoding the username and password
103                         String plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
104                         byte[] plainCredsBytes = plainCreds.getBytes();
105                         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
106                         String base64Creds = new String(base64CredsBytes);
107
108                         HttpHeaders headers = new HttpHeaders();
109                         headers.add("Authorization", "Basic " + base64Creds);
110                         headers.setContentType(MediaType.APPLICATION_JSON);
111                         String rawCookie = request.getHeader("Cookie");
112                         headers.add("Cookie", rawCookie);
113                         HttpEntity<String> entity = new HttpEntity<String>(headers);
114
115                         String url = microserviceUrlConverter(data, params);
116                         logger.debug(EELFLoggerDelegate.debugLogger, "Before making basic authentication call: {}", url);
117                         response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
118                         logger.debug(EELFLoggerDelegate.debugLogger, "Basic authentication call response: {}", response);
119
120                 } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
121                         HttpHeaders headers = new HttpHeaders();
122                         headers.setContentType(MediaType.APPLICATION_JSON);
123                         String rawCookie = request.getHeader("Cookie");
124                         headers.add("Cookie", rawCookie);
125                         HttpEntity<String> entity = new HttpEntity<String>(headers);
126
127                         String url = microserviceUrlConverter(data, params);
128                         logger.debug(EELFLoggerDelegate.debugLogger, "Before making cookie-based authentication call: {}", url);
129                         response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
130                         logger.debug(EELFLoggerDelegate.debugLogger, "Cookie-based authentication call response: {}", response);
131                 }
132                 return response;
133         }
134
135         @Override
136         public String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request)
137                         throws Exception {
138
139                 String response = null;
140
141                 @SuppressWarnings({ "rawtypes", "unchecked" })
142                 ResponseEntity<Long> ans = (ResponseEntity<Long>) template.exchange(
143                                 EcompPortalUtils.widgetMsProtocol() + "://"
144                                                 + consulHealthService.getServiceLocation(whatService,
145                                                                 SystemProperties.getProperty("microservices.widget.local.port"))
146                                                 + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
147                                 HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class);
148                 Long serviceId = ans.getBody();
149
150                 // get the microservice object by the id
151                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
152
153                 // No such microservice available
154                 if (data == null) {
155                         return response;
156                 }
157
158                 List<MicroserviceParameter> params = data.getParameterList();
159                 MicroserviceParameter userId_param = new MicroserviceParameter();
160                 userId_param.setPara_key("userId");
161                 userId_param.setPara_value(user.getOrgUserId());
162                 params.add(userId_param);
163
164                 for (MicroserviceParameter p : params) {
165                         WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
166                                         p.getId());
167                         if (userValue != null)
168                                 p.setPara_value(userValue.getUser_value());
169                 }
170
171                 if (data.getSecurityType().equals(NO_AUTH)) {
172                         HttpHeaders headers = new HttpHeaders();
173                         headers.setContentType(MediaType.APPLICATION_JSON);
174                         HttpEntity<String> entity = new HttpEntity<String>(headers);
175
176                         String url = microserviceUrlConverter(data, params);
177                         try {
178                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
179                         } catch (HttpClientErrorException e) {
180                                 throw e;
181                         }
182                 } else if (data.getSecurityType().equals(BASIC_AUTH)) {
183                         // encoding the username and password
184                         String plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
185                         byte[] plainCredsBytes = plainCreds.getBytes();
186                         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
187                         String base64Creds = new String(base64CredsBytes);
188
189                         HttpHeaders headers = new HttpHeaders();
190                         headers.add("Authorization", "Basic " + base64Creds);
191                         headers.setContentType(MediaType.APPLICATION_JSON);
192                         HttpEntity<String> entity = new HttpEntity<String>(headers);
193
194                         String url = microserviceUrlConverter(data, params);
195                         try {
196                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
197                         } catch (HttpClientErrorException e) {
198                                 throw e;
199                         }
200                 } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
201                         HttpHeaders headers = new HttpHeaders();
202                         headers.setContentType(MediaType.APPLICATION_JSON);
203                         String rawCookie = request.getHeader("Cookie");
204                         headers.add("Cookie", rawCookie);
205                         HttpEntity<String> entity = new HttpEntity<String>(headers);
206
207                         String url = microserviceUrlConverter(data, params);
208                         try {
209                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
210                         } catch (HttpClientErrorException e) {
211                                 throw e;
212                         }
213                 }
214                 return response;
215         }
216
217         private String decryptedPassword(String encryptedPwd) throws Exception {
218                 String result = "";
219                 if (encryptedPwd != null & encryptedPwd.length() > 0) {
220                         try {
221                                 result = CipherUtil.decrypt(encryptedPwd,
222                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
223                         } catch (Exception e) {
224                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
225                                 throw e;
226                         }
227                 }
228                 return result;
229         }
230
231         private String microserviceUrlConverter(MicroserviceData data, List<MicroserviceParameter> params) {
232                 String url = data.getUrl();
233                 for (int i = 0; i < params.size(); i++) {
234                         if (i == 0) {
235                                 url += QUESTION_MARK;
236                         }
237                         url += params.get(i).getPara_key() + "=" + params.get(i).getPara_value();
238                         if (i != (params.size() - 1)) {
239                                 url += ADD_MARK;
240                         }
241                 }
242                 return url;
243         }
244
245 }