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