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