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