WidgetsCatalogController up
[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.fn.FnUser;
53 import org.onap.portal.domain.dto.PortalRestResponse;
54 import org.onap.portal.domain.dto.PortalRestStatusEnum;
55 import org.onap.portal.domain.dto.ecomp.MicroserviceParameter;
56 import org.onap.portal.domain.dto.ecomp.WidgetCatalog;
57 import org.onap.portal.domain.dto.ecomp.WidgetCatalogParameter;
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.ep.EpMicroserviceParameterService;
63 import org.onap.portal.service.ep.EpWidgetCatalogParameterService;
64 import org.onap.portal.service.fn.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 @EnableAspectJAutoProxy
92 @EPAuditLog
93 public class WidgetsCatalogController {
94
95        private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogController.class);
96
97        private static final String MS_WIDGET_LOCAL_PORT = "microservices.widget.local.port";
98        private static final String UNAUTHORIZED_OR_FORBIDDEN_FOR_A_DISABLED_USER = "Unauthorized or  Forbidden for a disabled user";
99        private RestTemplate template = new RestTemplate();
100        private String whatService = "widgets-service";
101
102        private final EpWidgetCatalogParameterService epWidgetCatalogParameterService;
103        private final EpMicroserviceParameterService epMicroserviceParameterService;
104        private final WidgetMService widgetMService;
105        private final FnUserService fnUserService;
106
107        @Autowired
108        public WidgetsCatalogController(final EpWidgetCatalogParameterService epWidgetCatalogParameterService,
109                final EpMicroserviceParameterService epMicroserviceParameterService,
110                final WidgetMService widgetMService,
111                final FnUserService fnUserService) {
112               this.epWidgetCatalogParameterService = epWidgetCatalogParameterService;
113               this.epMicroserviceParameterService = epMicroserviceParameterService;
114               this.widgetMService = widgetMService;
115               this.fnUserService = fnUserService;
116        }
117
118
119        @GetMapping(value = {
120                "/portalApi/microservices/widgetCatalog/{loginName}"}, produces = MediaType.APPLICATION_JSON_VALUE)
121        public List<WidgetCatalog> getUserWidgetCatalog(@PathVariable("loginName") String loginName) {
122               List<WidgetCatalog> widgets;
123               try {
124                      ResponseEntity<List> ans = template.exchange(
125                              EcompPortalUtils.widgetMsProtocol() + "://"
126                                      + widgetMService.getServiceLocation(whatService,
127                                      SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
128                                      + "/widget/microservices/widgetCatalog/" + loginName,
129                              HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class);
130                      widgets = ans.getBody();
131               } catch (Exception e) {
132                      logger.error(EELFLoggerDelegate.errorLogger, "getUserWidgetCatalog failed", e);
133                      return null;
134               }
135               return widgets;
136        }
137
138        @GetMapping(value = {"/portalApi/microservices/widgetCatalog"}, produces = MediaType.APPLICATION_JSON_VALUE)
139        public List<WidgetCatalog> getWidgetCatalog() {
140               List<WidgetCatalog> widgets;
141               try {
142                      ResponseEntity<List> ans = template.exchange(
143                              EcompPortalUtils.widgetMsProtocol() + "://"
144                                      + widgetMService.getServiceLocation(whatService,
145                                      SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
146                                      + "/widget/microservices/widgetCatalog",
147                              HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class);
148                      widgets = ans.getBody();
149               } catch (Exception e) {
150                      logger.error(EELFLoggerDelegate.errorLogger, "getWidgetCatalog failed", e);
151                      return null;
152               }
153               return widgets;
154        }
155
156        @PutMapping(value = {
157                "/portalApi/microservices/widgetCatalog/{widgetId}"}, produces = MediaType.APPLICATION_JSON_VALUE)
158        public void updateWidgetCatalog(@RequestBody WidgetCatalog newWidgetCatalog,
159                @PathVariable("widgetId") long widgetId) throws Exception {
160               template.exchange(
161                       EcompPortalUtils.widgetMsProtocol() + "://"
162                               + widgetMService.getServiceLocation(whatService,
163                               SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
164                               + "/widget/microservices/widgetCatalog/" + widgetId,
165                       HttpMethod.PUT, new HttpEntity<>(newWidgetCatalog, WidgetServiceHeaders.getInstance()),
166                       String.class);
167        }
168
169        @DeleteMapping(value = {"/portalApi/microservices/widgetCatalog/{widgetId}"})
170        public void deleteOnboardingWidget(@PathVariable("widgetId") long widgetId) throws Exception {
171               template.exchange(
172                       EcompPortalUtils.widgetMsProtocol() + "://"
173                               + widgetMService.getServiceLocation(whatService,
174                               SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
175                               + "/widget/microservices/widgetCatalog/" + widgetId,
176                       HttpMethod.DELETE, new HttpEntity<>(WidgetServiceHeaders.getInstance()), String.class);
177        }
178
179        @PostMapping(value = {"/portalApi/microservices/widgetCatalog/{widgetId}"})
180        public String updateWidgetCatalogWithFiles(HttpServletRequest request,
181                @PathVariable("widgetId") long widgetId) {
182               MultipartHttpServletRequest mRequest;
183               MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
184               String fileName;
185               String tmpFolderName = "/tmp/";
186               String respond = null;
187               FileOutputStream fo = null;
188               try {
189                      mRequest = (MultipartHttpServletRequest) request;
190                      MultipartFile mFile = mRequest.getFile("file");
191                      fileName = mFile.getOriginalFilename();
192                      fo = new FileOutputStream(tmpFolderName + fileName);
193                      fo.write(mFile.getBytes());
194                      fo.close();
195                      fo = null;
196
197                      HttpHeaders header = new HttpHeaders();
198                      header.setContentType(MediaType.MULTIPART_FORM_DATA);
199                      multipartRequest.add("file", new FileSystemResource(tmpFolderName + fileName));
200                      multipartRequest.add("widget", request.getParameter("newWidget"));
201                      respond = template.postForObject(
202                              EcompPortalUtils.widgetMsProtocol() + "://"
203                                      + widgetMService.getServiceLocation(whatService,
204                                      SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
205                                      + "/widget/microservices/widgetCatalog/" + widgetId,
206                              new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
207                      File f = new File(tmpFolderName + fileName);
208                      f.delete();
209               } catch (Exception e) {
210                      logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed", e);
211               } finally {
212                      try {
213                             if (fo != null) {
214                                    fo.close();
215                             }
216                      } catch (IOException e) {
217                             logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed 2", e);
218                      }
219               }
220               return respond;
221        }
222
223        @PostMapping(value = {"/portalApi/microservices/widgetCatalog"})
224        public String createWidgetCatalog(HttpServletRequest request)
225                throws Exception {
226
227               if (StringUtils.isNotBlank(SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG))
228                       && SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG)
229                       .equalsIgnoreCase("false")) {
230                      return UNAUTHORIZED_OR_FORBIDDEN_FOR_A_DISABLED_USER;
231               }
232
233               MultipartHttpServletRequest mRequest;
234               MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
235               String fileName;
236               String tmpFolderName = "/tmp/";
237               String respond = null;
238               FileOutputStream fo = null;
239               try {
240                      mRequest = (MultipartHttpServletRequest) request;
241                      MultipartFile mFile = mRequest.getFile("file");
242                      fileName = mFile.getOriginalFilename();
243                      fo = new FileOutputStream(tmpFolderName + fileName);
244                      fo.write(mFile.getBytes());
245                      // silence sonar scan by calling close here
246                      fo.close();
247                      fo = null;
248
249                      HttpHeaders header = new HttpHeaders();
250                      header.setContentType(MediaType.MULTIPART_FORM_DATA);
251                      multipartRequest.add("file", new FileSystemResource(tmpFolderName + fileName));
252                      multipartRequest.add("widget", request.getParameter("newWidget"));
253
254                      respond = template.postForObject(
255                              EcompPortalUtils.widgetMsProtocol() + "://"
256                                      + widgetMService.getServiceLocation(whatService,
257                                      SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
258                                      + "/widget/microservices/widgetCatalog",
259                              new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
260                      File f = new File(tmpFolderName + fileName);
261                      f.delete();
262               } catch (Exception e) {
263                      logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed", e);
264               } finally {
265                      try {
266                             if (fo != null) {
267                                    fo.close();
268                             }
269                      } catch (IOException e) {
270                             logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed 2", e);
271                      }
272               }
273               return respond;
274        }
275
276        @GetMapping(value = "/portalApi/microservices/{widgetId}/framework.js")
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                               + "/widget/microservices/" + widgetId + "/framework.js", String.class,
282                       WidgetServiceHeaders.getInstance());
283        }
284
285        @GetMapping(value = "/portalApi/microservices/{widgetId}/controller.js")
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                               + "/widget/microservices/" + widgetId + "/controller.js", String.class,
291                       WidgetServiceHeaders.getInstance());
292        }
293
294        @GetMapping(value = "/portalApi/microservices/{widgetId}/style.css")
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                               + "/widget/microservices/" + widgetId + "/styles.css", String.class,
300                       WidgetServiceHeaders.getInstance());
301        }
302
303        @GetMapping(value = {"/portalApi/microservices/parameters/{widgetId}"})
304        public PortalRestResponse<List<WidgetParameterResult>> getWidgetParameterResult(Principal principal, 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.getParametersById(serviceId);
321                      for (MicroserviceParameter param : defaultParam) {
322                             WidgetParameterResult userResult = new WidgetParameterResult();
323                             userResult.setParamId(param.getId());
324                             userResult.setDefaultValue(param.getPara_value());
325                             userResult.setParamKey(param.getPara_key());
326                             WidgetCatalogParameter userValue = epWidgetCatalogParameterService
327                                     .getUserParamById(widgetId, user.getId(),
328                                             param.getId());
329                             if (userValue == null) {
330                                    userResult.setUserValue(param.getPara_value());
331                             } else {
332                                    userResult.setUserValue(userValue.getUserValue());
333                             }
334                             list.add(userResult);
335                      }
336               }
337               return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.OK, "SUCCESS", list);
338        }
339
340        @GetMapping(value = {"/portalApi/microservices/services/{paramId}"})
341        public List<WidgetCatalogParameter> getUserParameterById(@PathVariable("paramId") long paramId) {
342               return epWidgetCatalogParameterService.getUserParameterById(paramId);
343        }
344
345        @DeleteMapping(value = {"/portalApi/microservices/services/{paramId}"})
346        public void deleteUserParameterById(@PathVariable("paramId") long paramId) {
347               epWidgetCatalogParameterService.deleteUserParameterById(paramId);
348        }
349
350        @GetMapping(value = {"/portalApi/microservices/download/{widgetId}"})
351        public void doDownload(HttpServletRequest request, HttpServletResponse response,
352                @PathVariable("widgetId") long widgetId) throws Exception {
353
354               ServletContext context = request.getServletContext();
355               byte[] byteFile = template
356                       .exchange(
357                               EcompPortalUtils.widgetMsProtocol() + "://"
358                                       + widgetMService.getServiceLocation(whatService,
359                                       SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
360                                       + "/widget/microservices/download/" + widgetId,
361                               HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), byte[].class)
362                       .getBody();
363
364               File downloadFile = File.createTempFile("temp", ".zip");
365               try (FileOutputStream stream = new FileOutputStream(downloadFile.getPath())) {
366                      stream.write(byteFile);
367               } catch (Exception e) {
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                      logger.error(EELFLoggerDelegate.errorLogger, "doDownload failed", e);
393                      throw e;
394               }
395        }
396
397        @PostMapping(value = {"/portalApi/microservices/parameters"})
398        public PortalRestResponse<String> saveWidgetParameter(Principal principal, HttpServletRequest request,
399                @RequestBody WidgetCatalogParameter widgetParameters) {
400               FnUser user = fnUserService.loadUserByUsername(principal.getName());
401               widgetParameters.setUserId(user.getId());
402               try {
403                      WidgetCatalogParameter oldParam = epWidgetCatalogParameterService
404                              .getUserParamById(widgetParameters.getWidgetId(),
405                                      widgetParameters.getUserId(), widgetParameters.getParamId());
406                      if (oldParam != null) {
407                             widgetParameters.setId(oldParam.getId());
408                      }
409                      epWidgetCatalogParameterService.saveUserParameter(widgetParameters);
410
411               } catch (Exception e) {
412                      logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetParameter failed", e);
413                      return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
414               }
415               return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", "");
416        }
417
418        @GetMapping(value = {"/portalApi/microservices/uploadFlag"})
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
430 }