Fix sonar issues
[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.WidgetMService;
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 static final String MS_WIDGET_CATALOG_URL = "/widget/microservices/widgetCatalog/";
107
108     private static final String MS_WIDGET_URL = "/widget/microservices/";
109
110         private RestTemplate template = new RestTemplate();
111
112         private String whatService = "widgets-service";
113
114         @Autowired
115         private WidgetMService widgetMService;
116
117         @Autowired
118         private MicroserviceService microserviceService;
119
120         @Autowired
121         private WidgetParameterService widgetParameterService;
122
123         @Bean
124         public CommonsMultipartResolver multipartResolver() {
125                 return new CommonsMultipartResolver();
126         }
127
128         static {
129                 // for localhost testing only
130                 javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
131                         public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
132                                 if ("localhost".equals(hostname))
133                                         return true;
134                                 return false;
135                         }
136                 });
137         }
138
139         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{loginName}" }, method = RequestMethod.GET)
140         public List<WidgetCatalog> getUserWidgetCatalog(@PathVariable("loginName") String loginName) {
141                 List<WidgetCatalog> widgets = new ArrayList<>();
142                 try {
143                         ResponseEntity<List> ans = template.exchange(
144                                         EcompPortalUtils.widgetMsProtocol() + "://"
145                                                         + widgetMService.getServiceLocation(whatService,
146                                                                         SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
147                             + MS_WIDGET_CATALOG_URL + loginName,
148                                         HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class);
149                         widgets = ans.getBody();
150                 } catch (Exception e) {
151                         logger.error(EELFLoggerDelegate.errorLogger, "getUserWidgetCatalog failed", e);
152                         // returning null because null help check on the UI if there was a
153                         // communication problem with Microservice.
154                         return null;
155                 }
156                 return widgets;
157         }
158
159         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.GET)
160         public List<WidgetCatalog> getWidgetCatalog() {
161                 List<WidgetCatalog> widgets = new ArrayList<>();
162                 try {
163                         ResponseEntity<List> ans = template.exchange(
164                                         EcompPortalUtils.widgetMsProtocol() + "://"
165                                                         + widgetMService.getServiceLocation(whatService,
166                                                                         SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
167                                                         + "/widget/microservices/widgetCatalog",
168                                         HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class);
169                         widgets = ans.getBody();
170                 } catch (Exception e) {
171                         logger.error(EELFLoggerDelegate.errorLogger, "getWidgetCatalog failed", e);
172                         // returning null because null help check on the UI if there was a
173                         // communication problem with Microservice.
174                         return null;
175                 }
176                 return widgets;
177         }
178
179         @RequestMapping(value = {
180                         "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.PUT, produces = "application/json")
181         public void updateWidgetCatalog(@RequestBody WidgetCatalog newWidgetCatalog, @PathVariable("widgetId") long widgetId) throws Exception {
182                 template.exchange(
183                                 EcompPortalUtils.widgetMsProtocol() + "://"
184                                                 + widgetMService.getServiceLocation(whatService,
185                                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
186                         + MS_WIDGET_CATALOG_URL + widgetId,
187                                 HttpMethod.PUT, new HttpEntity<>(newWidgetCatalog, WidgetServiceHeaders.getInstance()), String.class);
188         }
189
190         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.DELETE)
191         public void deleteOnboardingWidget(@PathVariable("widgetId") long widgetId) throws Exception {
192                 template.exchange(
193                                 EcompPortalUtils.widgetMsProtocol() + "://"
194                                                 + widgetMService.getServiceLocation(whatService,
195                                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
196                         + MS_WIDGET_CATALOG_URL + widgetId,
197                                 HttpMethod.DELETE, new HttpEntity<>(WidgetServiceHeaders.getInstance()), String.class);
198         }
199
200         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.POST)
201         public String updateWidgetCatalogWithFiles(HttpServletRequest request,
202                         @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
203                 MultipartHttpServletRequest mRequest;
204                 MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
205                 String fileName;
206                 String tmpFolderName = "/tmp/";
207                 String respond = null;
208         try {
209             mRequest = (MultipartHttpServletRequest) request;
210             MultipartFile mFile = mRequest.getFile("file");
211             fileName = mFile.getOriginalFilename();
212             try (FileOutputStream fo = new FileOutputStream(tmpFolderName + fileName)) {
213                 fo.write(mFile.getBytes());
214             }
215
216                         HttpHeaders header = new HttpHeaders();
217                         header.setContentType(MediaType.MULTIPART_FORM_DATA);
218                         multipartRequest.add("file", new FileSystemResource(tmpFolderName + fileName));
219                         multipartRequest.add("widget", request.getParameter("newWidget"));
220                         respond = template.postForObject(
221                                         EcompPortalUtils.widgetMsProtocol() + "://"
222                                                         + widgetMService.getServiceLocation(whatService,
223                                                                         SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
224                             + MS_WIDGET_CATALOG_URL + widgetId,
225                                         new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
226                         File f = new File(tmpFolderName + fileName);
227                         f.delete();
228                 } catch (Exception e) {
229                         logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed", e);
230         }
231                 return respond;
232         }
233
234         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.POST)
235         public String createWidgetCatalog(HttpServletRequest request)
236                         throws Exception {
237
238                 if (StringUtils.isNotBlank(SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG))
239                 && "false".equalsIgnoreCase(
240                         SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG))) {
241                         return UNAUTHORIZED_OR_FORBIDDEN_FOR_A_DISABLED_USER;
242                 }
243
244                 MultipartHttpServletRequest mRequest;
245                 MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
246                 String fileName;
247                 String tmpFolderName = "/tmp/";
248                 String respond = null;
249                 try {
250                         mRequest = (MultipartHttpServletRequest) request;
251                         MultipartFile mFile = mRequest.getFile("file");
252                         fileName = mFile.getOriginalFilename();
253             try (FileOutputStream fo = new FileOutputStream(tmpFolderName + fileName)) {
254                 fo.write(mFile.getBytes());
255             }
256
257                         HttpHeaders header = new HttpHeaders();
258                         header.setContentType(MediaType.MULTIPART_FORM_DATA);
259                         multipartRequest.add("file", new FileSystemResource(tmpFolderName + fileName));
260                         multipartRequest.add("widget", request.getParameter("newWidget"));
261
262                         respond = template.postForObject(
263                                         EcompPortalUtils.widgetMsProtocol() + "://"
264                                                         + widgetMService.getServiceLocation(whatService,
265                                                                         SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
266                                                         + "/widget/microservices/widgetCatalog",
267                                         new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
268                         File f = new File(tmpFolderName + fileName);
269                         f.delete();
270                 } catch (Exception e) {
271                         logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed", e);
272                 }
273                 return respond;
274         }
275
276         @RequestMapping(value = "/portalApi/microservices/{widgetId}/framework.js", method = RequestMethod.GET)
277         public String getWidgetFramework(@PathVariable("widgetId") long widgetId) throws Exception {
278                 return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
279                                 + widgetMService.getServiceLocation(whatService,
280                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
281                 + MS_WIDGET_URL + widgetId + "/framework.js", String.class,
282                                 WidgetServiceHeaders.getInstance());
283         }
284
285         @RequestMapping(value = "/portalApi/microservices/{widgetId}/controller.js", method = RequestMethod.GET)
286         public String getWidgetController(@PathVariable("widgetId") long widgetId) throws Exception {
287                 return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
288                                 + widgetMService.getServiceLocation(whatService,
289                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
290                 + MS_WIDGET_URL + widgetId + "/controller.js", String.class,
291                                 WidgetServiceHeaders.getInstance());
292         }
293
294         @RequestMapping(value = "/portalApi/microservices/{widgetId}/style.css", method = RequestMethod.GET)
295         public String getWidgetCSS(@PathVariable("widgetId") long widgetId) throws Exception {
296                 return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
297                                 + widgetMService.getServiceLocation(whatService,
298                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
299                 + MS_WIDGET_URL + widgetId + "/styles.css", String.class,
300                                 WidgetServiceHeaders.getInstance());
301         }
302
303         @RequestMapping(value = { "/portalApi/microservices/parameters/{widgetId}" }, method = RequestMethod.GET)
304         public PortalRestResponse<List<WidgetParameterResult>> getWidgetParameterResult(HttpServletRequest request,
305                         @PathVariable("widgetId") long widgetId) throws Exception {
306                 EPUser user = EPUserUtils.getUserSession(request);
307
308                 List<WidgetParameterResult> list = new ArrayList<>();
309                 Long serviceId = template.exchange(
310                                 EcompPortalUtils.widgetMsProtocol() + "://"
311                                                 + widgetMService.getServiceLocation(whatService,
312                                                                 SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
313                                                 + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
314                                 HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), Long.class).getBody();
315                 if (serviceId == null) {
316                         // return ok/sucess and no service parameter for this widget
317             return new PortalRestResponse<>(PortalRestStatusEnum.WARN,
318                                         "No service parameters for this widget", list);
319                 } else {
320                         List<MicroserviceParameter> defaultParam = microserviceService.getParametersById(serviceId);
321                         for (MicroserviceParameter param : defaultParam) {
322                                 WidgetParameterResult userResult = new WidgetParameterResult();
323                                 userResult.setParam_id(param.getId());
324                                 userResult.setDefault_value(param.getPara_value());
325                                 userResult.setParam_key(param.getPara_key());
326                                 WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
327                                                 param.getId());
328                                 if (userValue == null)
329                                         userResult.setUser_value(param.getPara_value());
330                                 else {
331                                         userResult.setUser_value(userValue.getUser_value());
332                                 }
333                                 list.add(userResult);
334                         }
335                 }
336         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", list);
337         }
338
339         @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.GET)
340         public List<WidgetCatalogParameter> getUserParameterById(       @PathVariable("paramId") long paramId) {
341         return widgetParameterService.getUserParameterById(paramId);
342         }
343
344         @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.DELETE)
345         public void deleteUserParameterById(@PathVariable("paramId") long paramId) {
346                 widgetParameterService.deleteUserParameterById(paramId);
347         }
348
349         @RequestMapping(value = { "/portalApi/microservices/download/{widgetId}" }, method = RequestMethod.GET)
350         public void doDownload(HttpServletRequest request, HttpServletResponse response,
351                         @PathVariable("widgetId") long widgetId) throws Exception {
352
353                 ServletContext context = request.getServletContext();
354                 byte[] byteFile = template
355                                 .exchange(
356                                                 EcompPortalUtils.widgetMsProtocol() + "://"
357                                                                 + widgetMService.getServiceLocation(whatService,
358                                                                                 SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
359                                                                 + "/widget/microservices/download/" + widgetId,
360                                                 HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), byte[].class)
361                                 .getBody();
362
363                 File downloadFile = File.createTempFile("temp", ".zip");
364                 try(FileOutputStream stream = new FileOutputStream(downloadFile.getPath())){
365                         stream.write(byteFile);
366                 }catch(Exception e)
367                 {
368                         logger.error(EELFLoggerDelegate.errorLogger, "doDownload failed", e);
369                         throw e;
370                 }
371
372                 try(FileInputStream inputStream = new FileInputStream(downloadFile);
373                         OutputStream outStream = response.getOutputStream()){
374                         String mimeType = context.getMimeType(downloadFile.getPath());
375                         if (mimeType == null) {
376                                 mimeType = "application/octet-stream";
377                         }
378
379                         response.setContentType(mimeType);
380                         response.setContentLength((int) downloadFile.length());
381                         String headerKey = "Content-Disposition";
382                         String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
383                         downloadFile.delete();
384                         response.setHeader(headerKey, headerValue);
385
386                         byte[] buffer = new byte[32 * 1024];
387                         int bytesRead;
388                         while ((bytesRead = inputStream.read(buffer)) != -1) {
389                                 outStream.write(buffer, 0, bytesRead);
390                         }
391                 }catch(Exception e)
392                 {
393                         logger.error(EELFLoggerDelegate.errorLogger, "doDownload failed", e);
394                         throw e;
395                 }
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<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
414                 }
415                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", "");
416         }
417
418         @RequestMapping(value = { "/portalApi/microservices/uploadFlag" }, method = RequestMethod.GET)
419         public String getUploadFlag() {
420              String uplaodFlag="";
421                 try {
422                         uplaodFlag = SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG);
423                 } catch (Exception e) {
424                         logger.error(EELFLoggerDelegate.errorLogger, "uploadFlag failed", e);
425                         return null;
426                 }
427                 return uplaodFlag;
428         }
429 }