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