229ef1f38e14f2cf44241005963d596ee0c77c9d
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / controller / WidgetsCatalogController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the “License”);
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.openecomp.portalapp.portal.controller;
39
40 import java.io.File;
41 import java.io.FileInputStream;
42 import java.io.FileOutputStream;
43 import java.io.IOException;
44 import java.io.OutputStream;
45 import java.util.ArrayList;
46 import java.util.List;
47
48 import javax.servlet.ServletContext;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51
52 import org.openecomp.portalapp.controller.EPRestrictedBaseController;
53 import org.openecomp.portalapp.portal.domain.EPUser;
54 import org.openecomp.portalapp.portal.domain.MicroserviceParameter;
55 import org.openecomp.portalapp.portal.domain.WidgetCatalog;
56 import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter;
57 import org.openecomp.portalapp.portal.domain.WidgetParameterResult;
58 import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
59 import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
60 import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
61 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
62 import org.openecomp.portalapp.portal.service.ConsulHealthService;
63 import org.openecomp.portalapp.portal.service.MicroserviceService;
64 import org.openecomp.portalapp.portal.service.WidgetParameterService;
65 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
66 import org.openecomp.portalapp.util.EPUserUtils;
67 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
68 import org.openecomp.portalsdk.core.util.SystemProperties;
69 import org.springframework.beans.factory.annotation.Autowired;
70 import org.springframework.context.annotation.Bean;
71 import org.springframework.context.annotation.EnableAspectJAutoProxy;
72 import org.springframework.core.io.FileSystemResource;
73 import org.springframework.http.HttpEntity;
74 import org.springframework.http.HttpHeaders;
75 import org.springframework.http.HttpMethod;
76 import org.springframework.http.MediaType;
77 import org.springframework.http.ResponseEntity;
78 import org.springframework.util.LinkedMultiValueMap;
79 import org.springframework.util.MultiValueMap;
80 import org.springframework.web.bind.annotation.PathVariable;
81 import org.springframework.web.bind.annotation.RequestBody;
82 import org.springframework.web.bind.annotation.RequestMapping;
83 import org.springframework.web.bind.annotation.RequestMethod;
84 import org.springframework.web.bind.annotation.RestController;
85 import org.springframework.web.client.RestClientException;
86 import org.springframework.web.client.RestTemplate;
87 import org.springframework.web.multipart.MultipartFile;
88 import org.springframework.web.multipart.MultipartHttpServletRequest;
89 import org.springframework.web.multipart.commons.CommonsMultipartResolver;
90
91 @SuppressWarnings("unchecked")
92 @RestController
93 @org.springframework.context.annotation.Configuration
94 @EnableAspectJAutoProxy
95 @EPAuditLog
96 public class WidgetsCatalogController extends EPRestrictedBaseController {
97
98         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogController.class);
99
100         private static final String MS_WIDGET_LOCAL_PORT = "microservices.widget.local.port";
101
102         private RestTemplate template = new RestTemplate();
103
104         private String whatService = "widgets-service";
105
106         @Autowired
107         private ConsulHealthService consulHealthService;
108
109         @Autowired
110         private MicroserviceService microserviceService;
111
112         @Autowired
113         private WidgetParameterService widgetParameterService;
114
115         @Bean
116         public CommonsMultipartResolver multipartResolver() {
117                 return new CommonsMultipartResolver();
118         }
119
120         static {
121                 // for localhost testing only
122                 javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
123                         public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
124                                 if ("localhost".equals(hostname))
125                                         return true;
126                                 return false;
127                         }
128                 });
129         }
130
131         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{loginName}" }, method = RequestMethod.GET)
132         public List<WidgetCatalog> getUserWidgetCatalog(@PathVariable("loginName") String loginName) {
133                 List<WidgetCatalog> widgets = new ArrayList<>();
134                 try {
135                         ResponseEntity<List> ans = template.exchange(
136                                         EcompPortalUtils.widgetMsProtocol() + "://"
137                                                         + consulHealthService.getServiceLocation(whatService,
138                                                                         SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
139                                                         + "/widget/microservices/widgetCatalog/" + loginName,
140                                         HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class);
141                         widgets = ans.getBody();
142                 } catch (Exception e) {
143                         logger.error(EELFLoggerDelegate.errorLogger, "getUserWidgetCatalog failed", e);
144                         // returning null because null help check on the UI if there was a
145                         // communication problem with Microservice.
146                         return null;
147                 }
148                 return widgets;
149         }
150
151         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.GET)
152         public List<WidgetCatalog> getWidgetCatalog() {
153                 List<WidgetCatalog> widgets = new ArrayList<>();
154                 try {
155                         ResponseEntity<List> ans = template.exchange(
156                                         EcompPortalUtils.widgetMsProtocol() + "://"
157                                                         + consulHealthService.getServiceLocation(whatService,
158                                                                         SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
159                                                         + "/widget/microservices/widgetCatalog",
160                                         HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class);
161                         widgets = ans.getBody();
162                 } catch (Exception e) {
163                         logger.error(EELFLoggerDelegate.errorLogger, "getWidgetCatalog failed", e);
164                         // returning null because null help check on the UI if there was a
165                         // communication problem with Microservice.
166                         return null;
167                 }
168                 return widgets;
169         }
170
171         @RequestMapping(value = {
172                         "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.PUT, produces = "application/json")
173         public void updateWidgetCatalog(@RequestBody WidgetCatalog newWidgetCatalog, @PathVariable("widgetId") long widgetId) throws Exception {
174                 template.exchange(
175                                 EcompPortalUtils.widgetMsProtocol() + "://"
176                                                 + consulHealthService.getServiceLocation(whatService,
177                                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
178                                                 + "/widget/microservices/widgetCatalog/" + widgetId,
179                                 HttpMethod.PUT, new HttpEntity<>(newWidgetCatalog, WidgetServiceHeaders.getInstance()), String.class);
180         }
181
182         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.DELETE)
183         public void deleteOnboardingWidget(@PathVariable("widgetId") long widgetId) throws Exception {
184                 template.exchange(
185                                 EcompPortalUtils.widgetMsProtocol() + "://"
186                                                 + consulHealthService.getServiceLocation(whatService,
187                                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
188                                                 + "/widget/microservices/widgetCatalog/" + widgetId,
189                                 HttpMethod.DELETE, new HttpEntity<>(WidgetServiceHeaders.getInstance()), String.class);
190         }
191
192         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.POST)
193         public String updateWidgetCatalogWithFiles(HttpServletRequest request,
194                         @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
195                 MultipartHttpServletRequest mRequest;
196                 MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
197                 String fileName;
198                 String tmpFolderName = "/tmp/";
199                 String respond = null;
200                 FileOutputStream fo = null;
201                 try {
202                         mRequest = (MultipartHttpServletRequest) request;
203                         MultipartFile mFile = mRequest.getFile("file");
204                         fileName = mFile.getOriginalFilename();
205                         fo = new FileOutputStream(tmpFolderName + fileName);
206                         fo.write(mFile.getBytes());
207                         // silence sonar scan by calling close here
208                         fo.close();
209                         fo = null;
210
211                         HttpHeaders header = new HttpHeaders();
212                         header.setContentType(MediaType.MULTIPART_FORM_DATA);
213                         multipartRequest.add("file", new FileSystemResource(tmpFolderName + fileName));
214                         multipartRequest.add("widget", request.getParameter("newWidget"));
215                         respond = template.postForObject(
216                                         EcompPortalUtils.widgetMsProtocol() + "://"
217                                                         + consulHealthService.getServiceLocation(whatService,
218                                                                         SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
219                                                         + "/widget/microservices/widgetCatalog/" + widgetId,
220                                         new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
221                         File f = new File(tmpFolderName + fileName);
222                         f.delete();
223                 } catch (Exception e) {
224                         logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed", e);
225                 } finally {
226                         try {
227                                 if (fo != null)
228                                         fo.close();
229                         } catch (IOException e) {
230                                 logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed 2", e);
231                         }
232                 }
233                 return respond;
234         }
235
236         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.POST)
237         public String createWidgetCatalog(HttpServletRequest request)
238                         throws Exception {
239                 MultipartHttpServletRequest mRequest;
240                 MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
241                 String fileName;
242                 String tmpFolderName = "/tmp/";
243                 String respond = null;
244                 FileOutputStream fo = null;
245                 try {
246                         mRequest = (MultipartHttpServletRequest) request;
247                         MultipartFile mFile = mRequest.getFile("file");
248                         fileName = mFile.getOriginalFilename();
249                         fo = new FileOutputStream(tmpFolderName + fileName);
250                         fo.write(mFile.getBytes());
251                         // silence sonar scan by calling close here
252                         fo.close();
253                         fo = null;
254
255                         HttpHeaders header = new HttpHeaders();
256                         header.setContentType(MediaType.MULTIPART_FORM_DATA);
257                         multipartRequest.add("file", new FileSystemResource(tmpFolderName + fileName));
258                         multipartRequest.add("widget", request.getParameter("newWidget"));
259
260                         respond = template.postForObject(
261                                         EcompPortalUtils.widgetMsProtocol() + "://"
262                                                         + consulHealthService.getServiceLocation(whatService,
263                                                                         SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
264                                                         + "/widget/microservices/widgetCatalog",
265                                         new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
266                         File f = new File(tmpFolderName + fileName);
267                         f.delete();
268                 } catch (Exception e) {
269                         logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed", e);
270                 } finally {
271                         try {
272                                 if (fo != null)
273                                         fo.close();
274                         } catch (IOException e) {
275                                 logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed 2", e);
276                         }
277                 }
278                 return respond;
279         }
280
281         @RequestMapping(value = "/portalApi/microservices/{widgetId}/framework.js", method = RequestMethod.GET)
282         public String getWidgetFramework(@PathVariable("widgetId") long widgetId) throws Exception {
283                 return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
284                                 + consulHealthService.getServiceLocation(whatService,
285                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
286                                 + "/widget/microservices/" + widgetId + "/framework.js", String.class,
287                                 WidgetServiceHeaders.getInstance());
288         }
289
290         @RequestMapping(value = "/portalApi/microservices/{widgetId}/controller.js", method = RequestMethod.GET)
291         public String getWidgetController(@PathVariable("widgetId") long widgetId) throws Exception {
292                 return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
293                                 + consulHealthService.getServiceLocation(whatService,
294                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
295                                 + "/widget/microservices/" + widgetId + "/controller.js", String.class,
296                                 WidgetServiceHeaders.getInstance());
297         }
298
299         @RequestMapping(value = "/portalApi/microservices/{widgetId}/style.css", method = RequestMethod.GET)
300         public String getWidgetCSS(@PathVariable("widgetId") long widgetId) throws Exception {
301                 return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
302                                 + consulHealthService.getServiceLocation(whatService,
303                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
304                                 + "/widget/microservices/" + widgetId + "/styles.css", String.class,
305                                 WidgetServiceHeaders.getInstance());
306         }
307
308         @RequestMapping(value = { "/portalApi/microservices/parameters/{widgetId}" }, method = RequestMethod.GET)
309         public PortalRestResponse<List<WidgetParameterResult>> getWidgetParameterResult(HttpServletRequest request,
310                         @PathVariable("widgetId") long widgetId) throws Exception {
311                 EPUser user = EPUserUtils.getUserSession(request);
312
313                 List<WidgetParameterResult> list = new ArrayList<>();
314                 Long serviceId = template.exchange(
315                                 EcompPortalUtils.widgetMsProtocol() + "://"
316                                                 + consulHealthService.getServiceLocation(whatService,
317                                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
318                                                 + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
319                                 HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), Long.class).getBody();
320                 if (serviceId == null) {
321                         // return ok/sucess and no service parameter for this widget
322                         return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.WARN,
323                                         "No service parameters for this widget", list);
324                 } else {
325                         List<MicroserviceParameter> defaultParam = microserviceService.getParametersById(serviceId);
326                         for (MicroserviceParameter param : defaultParam) {
327                                 WidgetParameterResult userResult = new WidgetParameterResult();
328                                 userResult.setParam_id(param.getId());
329                                 userResult.setDefault_value(param.getPara_value());
330                                 userResult.setParam_key(param.getPara_key());
331                                 WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
332                                                 param.getId());
333                                 if (userValue == null)
334                                         userResult.setUser_value(param.getPara_value());
335                                 else {
336                                         userResult.setUser_value(userValue.getUser_value());
337                                 }
338                                 list.add(userResult);
339                         }
340                 }
341                 return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.OK, "SUCCESS", list);
342         }
343
344         @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.GET)
345         public List<WidgetCatalogParameter> getUserParameterById(       @PathVariable("paramId") long paramId) {
346                 List<WidgetCatalogParameter> list = widgetParameterService.getUserParameterById(paramId);
347                 return list;
348         }
349
350         @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.DELETE)
351         public void deleteUserParameterById(@PathVariable("paramId") long paramId) {
352                 widgetParameterService.deleteUserParameterById(paramId);
353         }
354
355         @RequestMapping(value = { "/portalApi/microservices/download/{widgetId}" }, method = RequestMethod.GET)
356         public void doDownload(HttpServletRequest request, HttpServletResponse response,
357                         @PathVariable("widgetId") long widgetId) throws Exception {
358
359                 ServletContext context = request.getServletContext();
360                 byte[] byteFile = template
361                                 .exchange(
362                                                 EcompPortalUtils.widgetMsProtocol() + "://"
363                                                                 + consulHealthService.getServiceLocation(whatService,
364                                                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
365                                                                 + "/widget/microservices/download/" + widgetId,
366                                                 HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), byte[].class)
367                                 .getBody();
368
369                 File downloadFile = File.createTempFile("temp", ".zip");
370                 FileOutputStream stream = new FileOutputStream(downloadFile.getPath());
371                 stream.write(byteFile);
372                 stream.close();
373
374                 FileInputStream inputStream = new FileInputStream(downloadFile);
375                 String mimeType = context.getMimeType(downloadFile.getPath());
376                 if (mimeType == null) {
377                         mimeType = "application/octet-stream";
378                 }
379
380                 response.setContentType(mimeType);
381                 response.setContentLength((int) downloadFile.length());
382                 String headerKey = "Content-Disposition";
383                 String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
384                 downloadFile.delete();
385                 response.setHeader(headerKey, headerValue);
386
387                 OutputStream outStream = response.getOutputStream();
388                 byte[] buffer = new byte[32 * 1024];
389                 int bytesRead;
390                 while ((bytesRead = inputStream.read(buffer)) != -1) {
391                         outStream.write(buffer, 0, bytesRead);
392                 }
393
394                 inputStream.close();
395                 outStream.close();
396         }
397
398         @RequestMapping(value = { "/portalApi/microservices/parameters" }, method = RequestMethod.POST)
399         public PortalRestResponse<String> saveWidgetParameter(HttpServletRequest request,
400                         @RequestBody WidgetCatalogParameter widgetParameters) {
401                 EPUser user = EPUserUtils.getUserSession(request);
402                 widgetParameters.setUserId(user.getId());
403                 try {
404                         WidgetCatalogParameter oldParam = widgetParameterService.getUserParamById(widgetParameters.getWidgetId(),
405                                         widgetParameters.getUserId(), widgetParameters.getParamId());
406                         if (oldParam != null) {
407                                 widgetParameters.setId(oldParam.getId());
408                         }
409                         widgetParameterService.saveUserParameter(widgetParameters);
410
411                 } catch (Exception e) {
412                         logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetParameter failed", e);
413                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
414                 }
415                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
416         }
417 }