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