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