2  * ============LICENSE_START==========================================
 
   4  * ===================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 
   6  * ===================================================================
 
   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
 
  13  *             http://www.apache.org/licenses/LICENSE-2.0
 
  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.
 
  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
 
  26  *             https://creativecommons.org/licenses/by/4.0/
 
  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.
 
  34  * ============LICENSE_END============================================
 
  38 package org.onap.portalapp.portal.controller;
 
  41 import java.io.FileInputStream;
 
  42 import java.io.FileOutputStream;
 
  43 import java.io.IOException;
 
  44 import java.io.OutputStream;
 
  45 import java.util.ArrayList;
 
  46 import java.util.List;
 
  48 import javax.servlet.ServletContext;
 
  49 import javax.servlet.http.HttpServletRequest;
 
  50 import javax.servlet.http.HttpServletResponse;
 
  52 import org.apache.commons.lang.StringUtils;
 
  53 import org.onap.portalapp.controller.EPRestrictedBaseController;
 
  54 import org.onap.portalapp.portal.domain.EPUser;
 
  55 import org.onap.portalapp.portal.domain.MicroserviceParameter;
 
  56 import org.onap.portalapp.portal.domain.WidgetCatalog;
 
  57 import org.onap.portalapp.portal.domain.WidgetCatalogParameter;
 
  58 import org.onap.portalapp.portal.domain.WidgetParameterResult;
 
  59 import org.onap.portalapp.portal.domain.WidgetServiceHeaders;
 
  60 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
 
  61 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
 
  62 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
 
  63 import org.onap.portalapp.portal.service.ConsulHealthService;
 
  64 import org.onap.portalapp.portal.service.MicroserviceService;
 
  65 import org.onap.portalapp.portal.service.WidgetParameterService;
 
  66 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
 
  67 import org.onap.portalapp.portal.utils.EcompPortalUtils;
 
  68 import org.onap.portalapp.util.EPUserUtils;
 
  69 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 
  70 import org.onap.portalsdk.core.util.SystemProperties;
 
  71 import org.springframework.beans.factory.annotation.Autowired;
 
  72 import org.springframework.context.annotation.Bean;
 
  73 import org.springframework.context.annotation.EnableAspectJAutoProxy;
 
  74 import org.springframework.core.io.FileSystemResource;
 
  75 import org.springframework.http.HttpEntity;
 
  76 import org.springframework.http.HttpHeaders;
 
  77 import org.springframework.http.HttpMethod;
 
  78 import org.springframework.http.MediaType;
 
  79 import org.springframework.http.ResponseEntity;
 
  80 import org.springframework.util.LinkedMultiValueMap;
 
  81 import org.springframework.util.MultiValueMap;
 
  82 import org.springframework.web.bind.annotation.PathVariable;
 
  83 import org.springframework.web.bind.annotation.RequestBody;
 
  84 import org.springframework.web.bind.annotation.RequestMapping;
 
  85 import org.springframework.web.bind.annotation.RequestMethod;
 
  86 import org.springframework.web.bind.annotation.RestController;
 
  87 import org.springframework.web.client.RestClientException;
 
  88 import org.springframework.web.client.RestTemplate;
 
  89 import org.springframework.web.multipart.MultipartFile;
 
  90 import org.springframework.web.multipart.MultipartHttpServletRequest;
 
  91 import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 
  93 @SuppressWarnings("unchecked")
 
  95 @org.springframework.context.annotation.Configuration
 
  96 @EnableAspectJAutoProxy
 
  98 public class WidgetsCatalogController extends EPRestrictedBaseController {
 
 100         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogController.class);
 
 102         private static final String MS_WIDGET_LOCAL_PORT = "microservices.widget.local.port";
 
 104         private static final String UNAUTHORIZED_OR_FORBIDDEN_FOR_A_DISABLED_USER = "Unauthorized or  Forbidden for a disabled user";
 
 106         private RestTemplate template = new RestTemplate();
 
 108         private String whatService = "widgets-service";
 
 111         private ConsulHealthService consulHealthService;
 
 114         private MicroserviceService microserviceService;
 
 117         private WidgetParameterService widgetParameterService;
 
 120         public CommonsMultipartResolver multipartResolver() {
 
 121                 return new CommonsMultipartResolver();
 
 125                 // for localhost testing only
 
 126                 javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
 
 127                         public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
 
 128                                 if ("localhost".equals(hostname))
 
 135         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{loginName}" }, method = RequestMethod.GET)
 
 136         public List<WidgetCatalog> getUserWidgetCatalog(@PathVariable("loginName") String loginName) {
 
 137                 List<WidgetCatalog> widgets = new ArrayList<>();
 
 139                         ResponseEntity<List> ans = template.exchange(
 
 140                                         EcompPortalUtils.widgetMsProtocol() + "://"
 
 141                                                         + consulHealthService.getServiceLocation(whatService,
 
 142                                                                         SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
 
 143                                                         + "/widget/microservices/widgetCatalog/" + loginName,
 
 144                                         HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class);
 
 145                         widgets = ans.getBody();
 
 146                 } catch (Exception e) {
 
 147                         logger.error(EELFLoggerDelegate.errorLogger, "getUserWidgetCatalog failed", e);
 
 148                         // returning null because null help check on the UI if there was a
 
 149                         // communication problem with Microservice.
 
 155         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.GET)
 
 156         public List<WidgetCatalog> getWidgetCatalog() {
 
 157                 List<WidgetCatalog> widgets = new ArrayList<>();
 
 159                         ResponseEntity<List> ans = template.exchange(
 
 160                                         EcompPortalUtils.widgetMsProtocol() + "://"
 
 161                                                         + consulHealthService.getServiceLocation(whatService,
 
 162                                                                         SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
 
 163                                                         + "/widget/microservices/widgetCatalog",
 
 164                                         HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class);
 
 165                         widgets = ans.getBody();
 
 166                 } catch (Exception e) {
 
 167                         logger.error(EELFLoggerDelegate.errorLogger, "getWidgetCatalog failed", e);
 
 168                         // returning null because null help check on the UI if there was a
 
 169                         // communication problem with Microservice.
 
 175         @RequestMapping(value = {
 
 176                         "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.PUT, produces = "application/json")
 
 177         public void updateWidgetCatalog(@RequestBody WidgetCatalog newWidgetCatalog, @PathVariable("widgetId") long widgetId) throws Exception {
 
 179                                 EcompPortalUtils.widgetMsProtocol() + "://"
 
 180                                                 + consulHealthService.getServiceLocation(whatService,
 
 181                                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
 
 182                                                 + "/widget/microservices/widgetCatalog/" + widgetId,
 
 183                                 HttpMethod.PUT, new HttpEntity<>(newWidgetCatalog, WidgetServiceHeaders.getInstance()), String.class);
 
 186         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.DELETE)
 
 187         public void deleteOnboardingWidget(@PathVariable("widgetId") long widgetId) throws Exception {
 
 189                                 EcompPortalUtils.widgetMsProtocol() + "://"
 
 190                                                 + consulHealthService.getServiceLocation(whatService,
 
 191                                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
 
 192                                                 + "/widget/microservices/widgetCatalog/" + widgetId,
 
 193                                 HttpMethod.DELETE, new HttpEntity<>(WidgetServiceHeaders.getInstance()), String.class);
 
 196         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.POST)
 
 197         public String updateWidgetCatalogWithFiles(HttpServletRequest request,
 
 198                         @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
 
 199                 MultipartHttpServletRequest mRequest;
 
 200                 MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
 
 202                 String tmpFolderName = "/tmp/";
 
 203                 String respond = null;
 
 204                 FileOutputStream fo = null;
 
 206                         mRequest = (MultipartHttpServletRequest) request;
 
 207                         MultipartFile mFile = mRequest.getFile("file");
 
 208                         fileName = mFile.getOriginalFilename();
 
 209                         fo = new FileOutputStream(tmpFolderName + fileName);
 
 210                         fo.write(mFile.getBytes());
 
 211                         // silence sonar scan by calling close here
 
 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                                                         + consulHealthService.getServiceLocation(whatService,
 
 222                                                                         SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
 
 223                                                         + "/widget/microservices/widgetCatalog/" + widgetId,
 
 224                                         new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
 
 225                         File f = new File(tmpFolderName + fileName);
 
 227                 } catch (Exception e) {
 
 228                         logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed", e);
 
 233                         } catch (IOException e) {
 
 234                                 logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed 2", e);
 
 240         @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.POST)
 
 241         public String createWidgetCatalog(HttpServletRequest request)
 
 244                 if (StringUtils.isNotBlank(SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG))
 
 245                                 && SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG).equalsIgnoreCase("false")) {
 
 246                         return UNAUTHORIZED_OR_FORBIDDEN_FOR_A_DISABLED_USER;
 
 249                 MultipartHttpServletRequest mRequest;
 
 250                 MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
 
 252                 String tmpFolderName = "/tmp/";
 
 253                 String respond = null;
 
 254                 FileOutputStream fo = null;
 
 256                         mRequest = (MultipartHttpServletRequest) request;
 
 257                         MultipartFile mFile = mRequest.getFile("file");
 
 258                         fileName = mFile.getOriginalFilename();
 
 259                         fo = new FileOutputStream(tmpFolderName + fileName);
 
 260                         fo.write(mFile.getBytes());
 
 261                         // silence sonar scan by calling close here
 
 265                         HttpHeaders header = new HttpHeaders();
 
 266                         header.setContentType(MediaType.MULTIPART_FORM_DATA);
 
 267                         multipartRequest.add("file", new FileSystemResource(tmpFolderName + fileName));
 
 268                         multipartRequest.add("widget", request.getParameter("newWidget"));
 
 270                         respond = template.postForObject(
 
 271                                         EcompPortalUtils.widgetMsProtocol() + "://"
 
 272                                                         + consulHealthService.getServiceLocation(whatService,
 
 273                                                                         SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
 
 274                                                         + "/widget/microservices/widgetCatalog",
 
 275                                         new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
 
 276                         File f = new File(tmpFolderName + fileName);
 
 278                 } catch (Exception e) {
 
 279                         logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed", e);
 
 284                         } catch (IOException e) {
 
 285                                 logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed 2", e);
 
 291         @RequestMapping(value = "/portalApi/microservices/{widgetId}/framework.js", method = RequestMethod.GET)
 
 292         public String getWidgetFramework(@PathVariable("widgetId") long widgetId) throws Exception {
 
 293                 return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
 
 294                                 + consulHealthService.getServiceLocation(whatService,
 
 295                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
 
 296                                 + "/widget/microservices/" + widgetId + "/framework.js", String.class,
 
 297                                 WidgetServiceHeaders.getInstance());
 
 300         @RequestMapping(value = "/portalApi/microservices/{widgetId}/controller.js", method = RequestMethod.GET)
 
 301         public String getWidgetController(@PathVariable("widgetId") long widgetId) throws Exception {
 
 302                 return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
 
 303                                 + consulHealthService.getServiceLocation(whatService,
 
 304                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
 
 305                                 + "/widget/microservices/" + widgetId + "/controller.js", String.class,
 
 306                                 WidgetServiceHeaders.getInstance());
 
 309         @RequestMapping(value = "/portalApi/microservices/{widgetId}/style.css", method = RequestMethod.GET)
 
 310         public String getWidgetCSS(@PathVariable("widgetId") long widgetId) throws Exception {
 
 311                 return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
 
 312                                 + consulHealthService.getServiceLocation(whatService,
 
 313                                                 SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
 
 314                                 + "/widget/microservices/" + widgetId + "/styles.css", String.class,
 
 315                                 WidgetServiceHeaders.getInstance());
 
 318         @RequestMapping(value = { "/portalApi/microservices/parameters/{widgetId}" }, method = RequestMethod.GET)
 
 319         public PortalRestResponse<List<WidgetParameterResult>> getWidgetParameterResult(HttpServletRequest request,
 
 320                         @PathVariable("widgetId") long widgetId) throws Exception {
 
 321                 EPUser user = EPUserUtils.getUserSession(request);
 
 323                 List<WidgetParameterResult> list = new ArrayList<>();
 
 324                 Long serviceId = template.exchange(
 
 325                                 EcompPortalUtils.widgetMsProtocol() + "://"
 
 326                                                 + consulHealthService.getServiceLocation(whatService,
 
 327                                                                 SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
 
 328                                                 + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
 
 329                                 HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), Long.class).getBody();
 
 330                 if (serviceId == null) {
 
 331                         // return ok/sucess and no service parameter for this widget
 
 332                         return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.WARN,
 
 333                                         "No service parameters for this widget", list);
 
 335                         List<MicroserviceParameter> defaultParam = microserviceService.getParametersById(serviceId);
 
 336                         for (MicroserviceParameter param : defaultParam) {
 
 337                                 WidgetParameterResult userResult = new WidgetParameterResult();
 
 338                                 userResult.setParam_id(param.getId());
 
 339                                 userResult.setDefault_value(param.getPara_value());
 
 340                                 userResult.setParam_key(param.getPara_key());
 
 341                                 WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
 
 343                                 if (userValue == null)
 
 344                                         userResult.setUser_value(param.getPara_value());
 
 346                                         userResult.setUser_value(userValue.getUser_value());
 
 348                                 list.add(userResult);
 
 351                 return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.OK, "SUCCESS", list);
 
 354         @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.GET)
 
 355         public List<WidgetCatalogParameter> getUserParameterById(       @PathVariable("paramId") long paramId) {
 
 356                 List<WidgetCatalogParameter> list = widgetParameterService.getUserParameterById(paramId);
 
 360         @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.DELETE)
 
 361         public void deleteUserParameterById(@PathVariable("paramId") long paramId) {
 
 362                 widgetParameterService.deleteUserParameterById(paramId);
 
 365         @RequestMapping(value = { "/portalApi/microservices/download/{widgetId}" }, method = RequestMethod.GET)
 
 366         public void doDownload(HttpServletRequest request, HttpServletResponse response,
 
 367                         @PathVariable("widgetId") long widgetId) throws Exception {
 
 369                 ServletContext context = request.getServletContext();
 
 370                 byte[] byteFile = template
 
 372                                                 EcompPortalUtils.widgetMsProtocol() + "://"
 
 373                                                                 + consulHealthService.getServiceLocation(whatService,
 
 374                                                                                 SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
 
 375                                                                 + "/widget/microservices/download/" + widgetId,
 
 376                                                 HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), byte[].class)
 
 379                 File downloadFile = File.createTempFile("temp", ".zip");
 
 380                 FileOutputStream stream = new FileOutputStream(downloadFile.getPath());
 
 381                 stream.write(byteFile);
 
 384                 FileInputStream inputStream = new FileInputStream(downloadFile);
 
 385                 String mimeType = context.getMimeType(downloadFile.getPath());
 
 386                 if (mimeType == null) {
 
 387                         mimeType = "application/octet-stream";
 
 390                 response.setContentType(mimeType);
 
 391                 response.setContentLength((int) downloadFile.length());
 
 392                 String headerKey = "Content-Disposition";
 
 393                 String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
 
 394                 downloadFile.delete();
 
 395                 response.setHeader(headerKey, headerValue);
 
 397                 OutputStream outStream = response.getOutputStream();
 
 398                 byte[] buffer = new byte[32 * 1024];
 
 400                 while ((bytesRead = inputStream.read(buffer)) != -1) {
 
 401                         outStream.write(buffer, 0, bytesRead);
 
 408         @RequestMapping(value = { "/portalApi/microservices/parameters" }, method = RequestMethod.POST)
 
 409         public PortalRestResponse<String> saveWidgetParameter(HttpServletRequest request,
 
 410                         @RequestBody WidgetCatalogParameter widgetParameters) {
 
 411                 EPUser user = EPUserUtils.getUserSession(request);
 
 412                 widgetParameters.setUserId(user.getId());
 
 414                         WidgetCatalogParameter oldParam = widgetParameterService.getUserParamById(widgetParameters.getWidgetId(),
 
 415                                         widgetParameters.getUserId(), widgetParameters.getParamId());
 
 416                         if (oldParam != null) {
 
 417                                 widgetParameters.setId(oldParam.getId());
 
 419                         widgetParameterService.saveUserParameter(widgetParameters);
 
 421                 } catch (Exception e) {
 
 422                         logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetParameter failed", e);
 
 423                         return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
 
 425                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
 
 428         @RequestMapping(value = { "/portalApi/microservices/uploadFlag" }, method = RequestMethod.GET)
 
 429         public String getUploadFlag() {
 
 430              String uplaodFlag="";
 
 432                         uplaodFlag = SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG);
 
 433                 } catch (Exception e) {
 
 434                         logger.error(EELFLoggerDelegate.errorLogger, "uploadFlag failed", e);