summaryrefslogtreecommitdiffstats
path: root/ecomp-portal-BE-common
diff options
context:
space:
mode:
Diffstat (limited to 'ecomp-portal-BE-common')
-rw-r--r--ecomp-portal-BE-common/pom.xml5
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/NotificationCleanupConfig.java18
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/externalsystemapproval/model/ExternalSystemRoleApproval.java5
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/externalsystemapproval/model/ExternalSystemUser.java10
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppContactUsController.java112
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java200
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java139
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuditLogController.java60
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperController.java215
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardController.java104
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java161
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/LanguageController.java15
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java6
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesController.java2
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java106
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SharedContextRestController.java120
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WidgetsController.java72
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ecomp/model/AppContactUsItem.java7
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NotValidDataException.java51
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java27
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/Analytics.java7
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java2
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java32
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPAppsManualPreference.java6
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPAppsSortPreference.java4
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPWidgetsSortPreference.java4
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingWidget.java8
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/DataValidator.java16
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java34
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java73
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuditLogControllerTest.java2
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java312
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java100
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java306
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java4
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SharedContextRestControllerTest.java99
-rw-r--r--ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsControllerTest.java51
37 files changed, 1763 insertions, 732 deletions
diff --git a/ecomp-portal-BE-common/pom.xml b/ecomp-portal-BE-common/pom.xml
index 61f166db..58ae5845 100644
--- a/ecomp-portal-BE-common/pom.xml
+++ b/ecomp-portal-BE-common/pom.xml
@@ -180,6 +180,11 @@
<version>${springframework.version}</version>
</dependency>
<dependency>
+ <groupId>javax.xml.bind</groupId>
+ <artifactId>jaxb-api</artifactId>
+ <version>2.4.0-b180830.0359</version>
+ </dependency>
+ <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.3.0.RELEASE</version>
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/NotificationCleanupConfig.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/NotificationCleanupConfig.java
index f18dea93..c32650e2 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/NotificationCleanupConfig.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/NotificationCleanupConfig.java
@@ -40,6 +40,7 @@
*/
package org.onap.portalapp.config;
+import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
@@ -51,23 +52,25 @@ import java.util.TimerTask;
@Configuration
public class NotificationCleanupConfig implements ApplicationContextAware {
-
+
// Once every 10 minutes should be adequate
- public static final int CLEANUP_PERIOD_MINUTES = 10;
-
+ private static final int CLEANUP_PERIOD_MINUTES = 10;
+
private static ApplicationContext applicationContext;
- public void setApplicationContext(ApplicationContext context) {
- applicationContext = context;
+
+ @Override
+ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
+ NotificationCleanupConfig.applicationContext = applicationContext;
}
- public static ApplicationContext getApplicationContext() {
+ static ApplicationContext getApplicationContext() {
return applicationContext;
}
@PostConstruct
- public void StartSchedular() {
+ public void startSchedular() {
TimerTask task = new NotificationCleanup();
Timer timer = new Timer();
timer.schedule(task, 1000, (long) CLEANUP_PERIOD_MINUTES * 60 * 1000);
@@ -77,5 +80,4 @@ public class NotificationCleanupConfig implements ApplicationContextAware {
public NotificationCleanupConfig getConfig() {
return new NotificationCleanupConfig();
}
-
} \ No newline at end of file
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/externalsystemapproval/model/ExternalSystemRoleApproval.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/externalsystemapproval/model/ExternalSystemRoleApproval.java
index 550d11df..49eb469c 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/externalsystemapproval/model/ExternalSystemRoleApproval.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/externalsystemapproval/model/ExternalSystemRoleApproval.java
@@ -38,13 +38,14 @@
package org.onap.portalapp.externalsystemapproval.model;
import java.io.Serializable;
+import org.hibernate.validator.constraints.SafeHtml;
public class ExternalSystemRoleApproval implements Serializable {
private static final long serialVersionUID = 6048830318039958615L;
-
+ @SafeHtml
private String roleName;
-
+ @SafeHtml
public String getRoleName() {
return roleName;
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/externalsystemapproval/model/ExternalSystemUser.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/externalsystemapproval/model/ExternalSystemUser.java
index cfe49267..fa6c04e1 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/externalsystemapproval/model/ExternalSystemUser.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/externalsystemapproval/model/ExternalSystemUser.java
@@ -40,15 +40,17 @@ package org.onap.portalapp.externalsystemapproval.model;
import java.util.ArrayList;
import java.util.List;
+import javax.validation.Valid;
+import org.hibernate.validator.constraints.SafeHtml;
public class ExternalSystemUser {
-
+ @SafeHtml
private String loginId;
-
+ @SafeHtml
private String applicationName;
-
+ @SafeHtml
private String myloginrequestId;
-
+ @Valid
private List<ExternalSystemRoleApproval> roles;
public ExternalSystemUser() {
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppContactUsController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppContactUsController.java
index 5da35523..b5876af8 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppContactUsController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppContactUsController.java
@@ -37,7 +37,6 @@
*/
package org.onap.portalapp.portal.controller;
-import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
@@ -53,9 +52,11 @@ import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
import org.onap.portalapp.portal.logging.aop.EPAuditLog;
import org.onap.portalapp.portal.service.AppContactUsService;
import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
+import org.onap.portalapp.validation.DataValidator;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.util.SystemProperties;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
@@ -65,42 +66,51 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/portalApi/contactus")
-@org.springframework.context.annotation.Configuration
+@Configuration
@EnableAspectJAutoProxy
@EPAuditLog
public class AppContactUsController extends EPRestrictedBaseController {
- static final String FAILURE = "failure";
+ private static final String FAILURE = "failure";
+ private static final String SUCCESS= "success";
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppContactUsController.class);
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppContactUsController.class);
+ private static final DataValidator dataValidator = new DataValidator();
+ private final Comparator<AppCategoryFunctionsItem> appCategoryFunctionsItemComparator = Comparator
+ .comparing(AppCategoryFunctionsItem::getCategory);
- @Autowired
private AppContactUsService contactUsService;
+ @Autowired
+ public AppContactUsController(AppContactUsService contactUsService) {
+ this.contactUsService = contactUsService;
+ }
+
+
/**
* Answers a JSON object with three items from the system.properties file:
* user self-help ticket URL, email for feedback, and Portal info link.
- *
+ *
* @param request HttpServletRequest
* @return PortalRestResponse
*/
@RequestMapping(value = "/feedback", method = RequestMethod.GET, produces = "application/json")
public PortalRestResponse<String> getPortalDetails(HttpServletRequest request) {
- PortalRestResponse<String> portalRestResponse = null;
+ PortalRestResponse<String> portalRestResponse;
try {
final String ticketUrl = SystemProperties.getProperty(EPCommonSystemProperties.USH_TICKET_URL);
final String portalInfoUrl = SystemProperties.getProperty(EPCommonSystemProperties.PORTAL_INFO_URL);
final String feedbackEmail = SystemProperties.getProperty(EPCommonSystemProperties.FEEDBACK_EMAIL_ADDRESS);
- HashMap<String, String> map = new HashMap<String, String>();
+ HashMap<String, String> map = new HashMap<>();
map.put(EPCommonSystemProperties.USH_TICKET_URL, ticketUrl);
map.put(EPCommonSystemProperties.PORTAL_INFO_URL, portalInfoUrl);
map.put(EPCommonSystemProperties.FEEDBACK_EMAIL_ADDRESS, feedbackEmail);
JSONObject j = new JSONObject(map);
String contactUsPortalResponse = j.toString();
- portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
- contactUsPortalResponse);
+ portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESS,
+ contactUsPortalResponse);
} catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, FAILURE, e.getMessage());
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE, e.getMessage());
}
return portalRestResponse;
}
@@ -108,21 +118,21 @@ public class AppContactUsController extends EPRestrictedBaseController {
/**
* Answers the contents of the contact-us table, extended with the
* application name.
- *
+ *
* @param request HttpServletRequest
* @return PortalRestResponse<List<AppContactUsItem>>
*/
@RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json")
public PortalRestResponse<List<AppContactUsItem>> getAppContactUsList(HttpServletRequest request) {
- PortalRestResponse<List<AppContactUsItem>> portalRestResponse = null;
+ PortalRestResponse<List<AppContactUsItem>> portalRestResponse;
try {
List<AppContactUsItem> contents = contactUsService.getAppContactUs();
- portalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(PortalRestStatusEnum.OK, "success",
- contents);
+ portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESS,
+ contents);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getAppContactUsList failed", e);
- portalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(PortalRestStatusEnum.ERROR,
- e.getMessage(), null);
+ portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), null);
}
return portalRestResponse;
}
@@ -130,36 +140,26 @@ public class AppContactUsController extends EPRestrictedBaseController {
/**
* Answers a list of objects, one per application, extended with available
* data on how to contact that app's organization (possibly none).
- *
+ *
* @param request HttpServletRequest
* @return PortalRestResponse<List<AppContactUsItem>>
*/
@RequestMapping(value = "/allapps", method = RequestMethod.GET, produces = "application/json")
public PortalRestResponse<List<AppContactUsItem>> getAppsAndContacts(HttpServletRequest request) {
- PortalRestResponse<List<AppContactUsItem>> portalRestResponse = null;
+ PortalRestResponse<List<AppContactUsItem>> portalRestResponse;
try {
List<AppContactUsItem> contents = contactUsService.getAppsAndContacts();
- portalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(PortalRestStatusEnum.OK, "success",
- contents);
+ portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESS,
+ contents);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getAllAppsAndContacts failed", e);
- portalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(PortalRestStatusEnum.ERROR,
- e.getMessage(), null);
+ portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), null);
}
return portalRestResponse;
}
/**
- * Sorts by category name.
- */
- private Comparator<AppCategoryFunctionsItem> appCategoryFunctionsItemComparator = new Comparator<AppCategoryFunctionsItem>() {
- @Override
- public int compare(AppCategoryFunctionsItem o1, AppCategoryFunctionsItem o2) {
- return o1.getCategory().compareTo(o2.getCategory());
- }
- };
-
- /**
* Answers a list of objects with category-application-function details. Not
* all applications participate in the functional menu.
*
@@ -168,20 +168,17 @@ public class AppContactUsController extends EPRestrictedBaseController {
*/
@RequestMapping(value = "/functions", method = RequestMethod.GET, produces = "application/json")
public PortalRestResponse<List<AppCategoryFunctionsItem>> getAppCategoryFunctions(HttpServletRequest request) {
- PortalRestResponse<List<AppCategoryFunctionsItem>> portalRestResponse = null;
+ PortalRestResponse<List<AppCategoryFunctionsItem>> portalRestResponse;
try {
List<AppCategoryFunctionsItem> contents = contactUsService.getAppCategoryFunctions();
- // logger.debug(EELFLoggerDelegate.debugLogger,
- // "getAppCategoryFunctions: result list size is " +
- // contents.size());
- Collections.sort(contents, appCategoryFunctionsItemComparator);
- portalRestResponse = new PortalRestResponse<List<AppCategoryFunctionsItem>>(PortalRestStatusEnum.OK,
- "success", contents);
+ contents.sort(appCategoryFunctionsItemComparator);
+ portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK,
+ SUCCESS, contents);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getAppCategoryFunctions failed", e);
// TODO build JSON error
- portalRestResponse = new PortalRestResponse<List<AppCategoryFunctionsItem>>(PortalRestStatusEnum.ERROR,
- e.getMessage(), null);
+ portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), null);
}
return portalRestResponse;
}
@@ -195,29 +192,41 @@ public class AppContactUsController extends EPRestrictedBaseController {
@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> save(@RequestBody AppContactUsItem contactUs) {
- if (contactUs == null || contactUs.getAppName() == null)
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, FAILURE,
- "AppName cannot be null or empty");
+ if (contactUs == null || contactUs.getAppName() == null) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE,
+ "AppName cannot be null or empty");
+ }else if(!dataValidator.isValid(contactUs)){
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE, "AppName is not valid.");
+ }
String saveAppContactUs = FAILURE;
try {
saveAppContactUs = contactUsService.saveAppContactUs(contactUs);
} catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, saveAppContactUs, e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, "save failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, saveAppContactUs, e.getMessage());
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, saveAppContactUs, "");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, saveAppContactUs, "");
}
@RequestMapping(value = "/saveAll", method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> save(@RequestBody List<AppContactUsItem> contactUsList) {
+ if (contactUsList == null) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE,
+ "AppNameList cannot be null or empty");
+ }else if(!dataValidator.isValid(contactUsList)){
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE, "AppNameList is not valid.");
+ }
+
String saveAppContactUs = FAILURE;
try {
saveAppContactUs = contactUsService.saveAppContactUs(contactUsList);
} catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, saveAppContactUs, e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, "save failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, saveAppContactUs, e.getMessage());
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, saveAppContactUs, "");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, saveAppContactUs, "");
}
/**
@@ -234,9 +243,10 @@ public class AppContactUsController extends EPRestrictedBaseController {
try {
saveAppContactUs = contactUsService.deleteContactUs(id);
} catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, saveAppContactUs, e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, "delete failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, saveAppContactUs, e.getMessage());
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, saveAppContactUs, "");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, saveAppContactUs, "");
}
} \ No newline at end of file
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java
index 4b401e22..9feecec1 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java
@@ -2,7 +2,7 @@
* ============LICENSE_START==========================================
* ONAP Portal
* ===================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* ===================================================================
* Modifications Copyright (c) 2019 Samsung
* ===================================================================
@@ -42,18 +42,12 @@ package org.onap.portalapp.portal.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
-import java.util.Map;
import java.util.Set;
-import java.util.stream.Stream;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONArray;
-import org.json.JSONObject;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
import org.onap.portalapp.controller.EPRestrictedBaseController;
import org.onap.portalapp.portal.domain.AdminUserApplications;
import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel;
@@ -68,7 +62,6 @@ import org.onap.portalapp.portal.logging.logic.EPLogUtil;
import org.onap.portalapp.portal.service.AdminRolesService;
import org.onap.portalapp.portal.service.EPAppService;
import org.onap.portalapp.portal.service.EPLeftMenuService;
-import org.onap.portalapp.portal.service.ExternalAccessRolesService;
import org.onap.portalapp.portal.transport.EPAppsManualPreference;
import org.onap.portalapp.portal.transport.EPAppsSortPreference;
import org.onap.portalapp.portal.transport.EPDeleteAppsManualSortPref;
@@ -76,10 +69,10 @@ import org.onap.portalapp.portal.transport.EPWidgetsSortPreference;
import org.onap.portalapp.portal.transport.FieldsValidator;
import org.onap.portalapp.portal.transport.LocalRole;
import org.onap.portalapp.portal.transport.OnboardingApp;
-import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.portal.utils.PortalConstants;
import org.onap.portalapp.util.EPUserUtils;
+import org.onap.portalapp.validation.DataValidator;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.portalsdk.core.web.support.AppUtils;
@@ -87,7 +80,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -97,27 +89,27 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
-import org.springframework.web.client.HttpStatusCodeException;
-import org.springframework.web.client.RestTemplate;
@RestController
@EnableAspectJAutoProxy
@EPAuditLog
+@NoArgsConstructor
+@Getter
public class AppsController extends EPRestrictedBaseController {
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsController.class);
+ private static final String GET_RESULT = "GET result =";
+ private static final String PUT_RESULT = "PUT result =";
+ private static final String PORTAL_API_ONBOARDING_APPS = "/portalApi/onboardingApps";
+ private static final String PORTAL_API_USER_APPS_ORDER_BY_SORT_PREF = "/portalApi/userAppsOrderBySortPref";
+
+ private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsController.class);
+ private final DataValidator dataValidator = new DataValidator();
@Autowired
private AdminRolesService adminRolesService;
-
@Autowired
private EPAppService appService;
-
@Autowired
private EPLeftMenuService leftMenuService;
-
- @Autowired
- private ExternalAccessRolesService externalAccessRolesService;
- RestTemplate template = new RestTemplate();
/**
* RESTful service method to fetch all Applications available to current
@@ -139,7 +131,7 @@ public class AppsController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
} else {
ecompApps = appService.transformAppsToEcompApps(appService.getUserApps(user));
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApps", "GET result =", ecompApps);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApps", GET_RESULT, ecompApps);
}
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getUserApps failed", e);
@@ -174,7 +166,7 @@ public class AppsController extends EPRestrictedBaseController {
else
apps = appService.getPersUserApps(user);
ecompApps = appService.transformAppsToEcompApps(apps);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userPersApps", "GET result =", ecompApps);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userPersApps", GET_RESULT, ecompApps);
}
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getPersUserApps failed", e);
@@ -203,7 +195,7 @@ public class AppsController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "getAdminApps");
} else {
adminApps = appService.getAdminApps(user);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminApps", "GET result =", adminApps);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminApps", GET_RESULT, adminApps);
}
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getAdminApps failed", e);
@@ -235,7 +227,7 @@ public class AppsController extends EPRestrictedBaseController {
} else {
adminApps = appService.getAppsForSuperAdminAndAccountAdmin(user);
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/appsForSuperAdminAndAccountAdmin",
- "GET result =", adminApps);
+ GET_RESULT, adminApps);
}
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getAppsForSuperAdminAndAccountAdmin failed", e);
@@ -245,7 +237,7 @@ public class AppsController extends EPRestrictedBaseController {
}
/**
- * RESTful service method to fetch left menu items from the user's session.
+ * RESTful service method to fetch left menu items from the user'PORTAL_API_USER_APPS_ORDER_BY_SORT_PREF session.
*
* @param request
* HttpServletRequest
@@ -267,7 +259,7 @@ public class AppsController extends EPRestrictedBaseController {
try {
menuList = leftMenuService.getLeftMenuItems(user, menuSet, roleFunctionSet);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/leftmenuItems", "GET result =", menuList);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/leftmenuItems", GET_RESULT, menuList);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getLeftMenuItems failed", e);
}
@@ -275,7 +267,7 @@ public class AppsController extends EPRestrictedBaseController {
}
@RequestMapping(value = {
- "/portalApi/userAppsOrderBySortPref" }, method = RequestMethod.GET, produces = "application/json")
+ PORTAL_API_USER_APPS_ORDER_BY_SORT_PREF }, method = RequestMethod.GET, produces = "application/json")
public List<EcompApp> getUserAppsOrderBySortPref(HttpServletRequest request, HttpServletResponse response) {
EPUser user = EPUserUtils.getUserSession(request);
List<EcompApp> ecompApps = null;
@@ -284,28 +276,28 @@ public class AppsController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "getUserAppsOrderBySortPref");
} else {
String usrSortPref = request.getParameter("mparams");
- if (usrSortPref.equals("")) {
+ if (usrSortPref.isEmpty()) {
usrSortPref = "N";
}
switch (usrSortPref) {
case "N":
ecompApps = appService.transformAppsToEcompApps(appService.getAppsOrderByName(user));
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppsOrderBySortPref", "GET result =",
+ EcompPortalUtils.logAndSerializeObject(logger, PORTAL_API_USER_APPS_ORDER_BY_SORT_PREF, GET_RESULT,
ecompApps);
break;
case "L":
ecompApps = appService.transformAppsToEcompApps(appService.getAppsOrderByLastUsed(user));
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppsOrderBySortPref", "GET result =",
+ EcompPortalUtils.logAndSerializeObject(logger, PORTAL_API_USER_APPS_ORDER_BY_SORT_PREF, GET_RESULT,
ecompApps);
break;
case "F":
ecompApps = appService.transformAppsToEcompApps(appService.getAppsOrderByMostUsed(user));
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppsOrderBySortPref", "GET result =",
+ EcompPortalUtils.logAndSerializeObject(logger, PORTAL_API_USER_APPS_ORDER_BY_SORT_PREF, GET_RESULT,
ecompApps);
break;
case "M":
ecompApps = appService.transformAppsToEcompApps(appService.getAppsOrderByManual(user));
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppsOrderBySortPref", "GET result =",
+ EcompPortalUtils.logAndSerializeObject(logger, PORTAL_API_USER_APPS_ORDER_BY_SORT_PREF, GET_RESULT,
ecompApps);
break;
default:
@@ -335,6 +327,13 @@ public class AppsController extends EPRestrictedBaseController {
public FieldsValidator putUserAppsSortingManual(HttpServletRequest request,
@RequestBody List<EPAppsManualPreference> epAppsManualPref, HttpServletResponse response) {
FieldsValidator fieldsValidator = null;
+
+ if (isNotNullAndNotValid(epAppsManualPref)){
+ fieldsValidator = new FieldsValidator();
+ fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE);
+ return fieldsValidator;
+ }
+
try {
EPUser user = EPUserUtils.getUserSession(request);
fieldsValidator = appService.saveAppsSortManual(epAppsManualPref, user);
@@ -342,7 +341,7 @@ public class AppsController extends EPRestrictedBaseController {
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "putUserAppsSortingManual failed", e);
}
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppsSortingManual", "PUT result =",
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppsSortingManual", PUT_RESULT,
response.getStatus());
return fieldsValidator;
}
@@ -352,6 +351,13 @@ public class AppsController extends EPRestrictedBaseController {
public FieldsValidator putUserWidgetsSortManual(HttpServletRequest request,
@RequestBody List<EPWidgetsSortPreference> saveManualWidgetSData, HttpServletResponse response) {
FieldsValidator fieldsValidator = null;
+
+ if (isNotNullAndNotValid(saveManualWidgetSData)){
+ fieldsValidator = new FieldsValidator();
+ fieldsValidator.setHttpStatusCode((long)HttpServletResponse.SC_NOT_ACCEPTABLE);
+ return fieldsValidator;
+ }
+
try {
EPUser user = EPUserUtils.getUserSession(request);
fieldsValidator = appService.saveWidgetsSortManual(saveManualWidgetSData, user);
@@ -359,8 +365,7 @@ public class AppsController extends EPRestrictedBaseController {
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortManual failed", e);
}
- // return fieldsValidator;
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/putUserWidgetsSortManual", "PUT result =",
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/putUserWidgetsSortManual", PUT_RESULT,
response.getStatus());
return fieldsValidator;
}
@@ -370,6 +375,13 @@ public class AppsController extends EPRestrictedBaseController {
public FieldsValidator putUserWidgetsSortPref(HttpServletRequest request,
@RequestBody List<EPWidgetsSortPreference> delManualWidgetData, HttpServletResponse response) {
FieldsValidator fieldsValidator = null;
+
+ if (isNotNullAndNotValid(delManualWidgetData)){
+ fieldsValidator = new FieldsValidator();
+ fieldsValidator.setHttpStatusCode((long)HttpServletResponse.SC_NOT_ACCEPTABLE);
+ return fieldsValidator;
+ }
+
try {
EPUser user = EPUserUtils.getUserSession(request);
fieldsValidator = appService.deleteUserWidgetSortPref(delManualWidgetData, user);
@@ -378,8 +390,7 @@ public class AppsController extends EPRestrictedBaseController {
logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e);
}
- // return fieldsValidator;
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/putUserWidgetsSortPref", "PUT result =",
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/putUserWidgetsSortPref", PUT_RESULT,
response.getStatus());
return fieldsValidator;
}
@@ -400,6 +411,7 @@ public class AppsController extends EPRestrictedBaseController {
public FieldsValidator deleteUserAppSortManual(HttpServletRequest request,
@RequestBody EPDeleteAppsManualSortPref delManualAppData, HttpServletResponse response) {
FieldsValidator fieldsValidator = null;
+
try {
EPUser user = EPUserUtils.getUserSession(request);
fieldsValidator = appService.deleteUserAppSortManual(delManualAppData, user);
@@ -408,8 +420,7 @@ public class AppsController extends EPRestrictedBaseController {
logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
}
- // return fieldsValidator;
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/deleteUserAppSortManual", "PUT result =",
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/deleteUserAppSortManual", PUT_RESULT,
response.getStatus());
return fieldsValidator;
}
@@ -428,8 +439,7 @@ public class AppsController extends EPRestrictedBaseController {
}
- // return fieldsValidator;
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/putUserAppsSortingPreference", "PUT result =",
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/putUserAppsSortingPreference", PUT_RESULT,
response.getStatus());
return fieldsValidator;
}
@@ -445,7 +455,7 @@ public class AppsController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "userAppsSortTypePreference");
} else {
userSortPreference = appService.getUserAppsSortTypePreference(user);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppsSortTypePreference", "GET result =",
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppsSortTypePreference", GET_RESULT,
userSortPreference);
}
} catch (Exception e) {
@@ -475,7 +485,7 @@ public class AppsController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "getAppsAdministrators");
} else {
admins = appService.getAppsAdmins();
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/accountAdmins", "GET result =", admins);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/accountAdmins", GET_RESULT, admins);
}
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getAppsAdministrators failed", e);
@@ -493,7 +503,7 @@ public class AppsController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "getApps");
} else {
apps = appService.getAllApplications(false);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/availableApps", "GET result =", apps);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/availableApps", GET_RESULT, apps);
}
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getApps failed", e);
@@ -522,7 +532,7 @@ public class AppsController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "getApps");
} else {
apps = appService.getAllApps(true);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/availableApps", "GET result =", apps);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/availableApps", GET_RESULT, apps);
}
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getAllApps failed", e);
@@ -547,7 +557,7 @@ public class AppsController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "getAppsFullList");
} else {
ecompApps = appService.getEcompAppAppsFullList();
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/appsFullList", "GET result =", ecompApps);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/appsFullList", GET_RESULT, ecompApps);
}
return ecompApps;
}
@@ -598,7 +608,7 @@ public class AppsController extends EPRestrictedBaseController {
|| (adminRolesService.isSuperAdmin(user) && requestedApp.getId() == PortalConstants.PORTAL_APP_ID))) {
try {
roleList = appService.getAppRoles(appId);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/appRoles/" + appId, "GET result =",
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/appRoles/" + appId, GET_RESULT,
roleList);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles failed", e);
@@ -626,8 +636,8 @@ public class AppsController extends EPRestrictedBaseController {
String appName = request.getParameter("appParam");
app = appService.getAppDetailByAppName(appName);
if (user != null && (adminRolesService.isAccountAdminOfApplication(user, app)
- || (adminRolesService.isSuperAdmin(user) && app.getId() == PortalConstants.PORTAL_APP_ID)))
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/singleAppInfo" + appName, "GET result =", app);
+ || (adminRolesService.isSuperAdmin(user) && app.getId().equals(PortalConstants.PORTAL_APP_ID))))
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/singleAppInfo" + appName, GET_RESULT, app);
else{
app= null;
EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
@@ -659,8 +669,8 @@ public class AppsController extends EPRestrictedBaseController {
app.setCentralAuth(false);
}
if (user != null && (adminRolesService.isAccountAdminOfApplication(user, app)
- || (adminRolesService.isSuperAdmin(user) && app.getId() == PortalConstants.PORTAL_APP_ID)))
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/singleAppInfoById" + appId, "GET result =", app);
+ || (adminRolesService.isSuperAdmin(user) && app.getId().equals(PortalConstants.PORTAL_APP_ID))))
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/singleAppInfoById" + appId, GET_RESULT, app);
else{
app= null;
EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
@@ -680,7 +690,7 @@ public class AppsController extends EPRestrictedBaseController {
* HTTP servlet response
* @return List<OnboardingApp>
*/
- @RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.GET, produces = "application/json")
+ @RequestMapping(value = { PORTAL_API_ONBOARDING_APPS }, method = RequestMethod.GET, produces = "application/json")
public List<OnboardingApp> getOnboardingApps(HttpServletRequest request, HttpServletResponse response) {
EPUser user = EPUserUtils.getUserSession(request);
List<OnboardingApp> onboardingApps = null;
@@ -697,8 +707,8 @@ public class AppsController extends EPRestrictedBaseController {
//get all his admin apps
onboardingApps = appService.getAdminAppsOfUser(user);
}
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/onboardingApps", "GET result =",
- "onboardingApps of size " + onboardingApps.size());
+ EcompPortalUtils.logAndSerializeObject(logger, PORTAL_API_ONBOARDING_APPS, GET_RESULT,
+ "onboardingApps of size " + (onboardingApps != null ? onboardingApps.size() : 0));
}
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getOnboardingApps failed", e);
@@ -718,14 +728,12 @@ public class AppsController extends EPRestrictedBaseController {
* @return FieldsValidator
* @throws Exception
*/
- @RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.PUT, produces = "application/json")
+ @RequestMapping(value = { PORTAL_API_ONBOARDING_APPS }, method = RequestMethod.PUT, produces = "application/json")
public FieldsValidator putOnboardingApp(HttpServletRequest request,
- @RequestBody OnboardingApp modifiedOnboardingApp, HttpServletResponse response) throws Exception {
+ @RequestBody OnboardingApp modifiedOnboardingApp, HttpServletResponse response) {
FieldsValidator fieldsValidator = null;
EPUser user = null;
- EPApp oldEPApp = null;
- oldEPApp = appService.getApp(modifiedOnboardingApp.id);
- ResponseEntity<String> res = null;
+ EPApp oldEPApp = appService.getApp(modifiedOnboardingApp.id);
try {
user = EPUserUtils.getUserSession(request);
@@ -734,20 +742,7 @@ public class AppsController extends EPRestrictedBaseController {
} else {
if((oldEPApp.getCentralAuth() && modifiedOnboardingApp.isCentralAuth && !oldEPApp.getNameSpace().equalsIgnoreCase(modifiedOnboardingApp.nameSpace) && modifiedOnboardingApp.nameSpace!= null ) || (!oldEPApp.getCentralAuth() && modifiedOnboardingApp.isCentralAuth && modifiedOnboardingApp.nameSpace!= null))
{
- try {
- res = appService.checkIfNameSpaceIsValid(modifiedOnboardingApp.nameSpace);
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- if (e.getStatusCode() == HttpStatus.NOT_FOUND || e.getStatusCode() == HttpStatus.FORBIDDEN) {
- fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response);
- throw new InvalidApplicationException("Invalid NameSpace");
- }else{
- fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response);
- throw e;
- }
- }
-
+ checkIfNameSpaceIsValid(modifiedOnboardingApp, fieldsValidator, response);
}
modifiedOnboardingApp.normalize();
fieldsValidator = appService.modifyOnboardingApp(modifiedOnboardingApp, user);
@@ -767,7 +762,7 @@ public class AppsController extends EPRestrictedBaseController {
logger.error(EELFLoggerDelegate.errorLogger, "putOnboardingApps failed", e);
}
}
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/onboardingApps", "PUT result =",
+ EcompPortalUtils.logAndSerializeObject(logger, PORTAL_API_ONBOARDING_APPS, PUT_RESULT,
response.getStatus());
return fieldsValidator;
}
@@ -784,7 +779,7 @@ public class AppsController extends EPRestrictedBaseController {
* app to add
* @return FieldsValidator
*/
- @RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.POST, produces = "application/json")
+ @RequestMapping(value = { PORTAL_API_ONBOARDING_APPS }, method = RequestMethod.POST, produces = "application/json")
public FieldsValidator postOnboardingApp(HttpServletRequest request, @RequestBody OnboardingApp newOnboardingApp,
HttpServletResponse response) {
FieldsValidator fieldsValidator = null;
@@ -794,21 +789,7 @@ public class AppsController extends EPRestrictedBaseController {
EcompPortalUtils.setBadPermissions(user, response, "postOnboardingApps");
} else {
newOnboardingApp.normalize();
- ResponseEntity<String> res = null;
- try {
- if( !(newOnboardingApp.nameSpace == null) && !newOnboardingApp.nameSpace.isEmpty())
- res = appService.checkIfNameSpaceIsValid(newOnboardingApp.nameSpace);
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
- EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
- if (e.getStatusCode() == HttpStatus.NOT_FOUND || e.getStatusCode() == HttpStatus.FORBIDDEN) {
- fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response);
- throw new InvalidApplicationException("Invalid NameSpace");
- }else{
- fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response);
- throw e;
- }
- }
+ checkIfNameSpaceIsValid(newOnboardingApp, fieldsValidator, response);
fieldsValidator = appService.addOnboardingApp(newOnboardingApp, user);
response.setStatus(fieldsValidator.httpStatusCode.intValue());
}
@@ -824,22 +805,22 @@ public class AppsController extends EPRestrictedBaseController {
logger.error(EELFLoggerDelegate.errorLogger, "postOnboardingApp failed", e);
}
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/onboardingApps", "POST result =",
+ EcompPortalUtils.logAndSerializeObject(logger, PORTAL_API_ONBOARDING_APPS, "POST result =",
response.getStatus());
return fieldsValidator;
}
- private FieldsValidator setResponse(HttpStatus statusCode,FieldsValidator fieldsValidator,HttpServletResponse response)
+ private FieldsValidator setResponse(HttpStatus statusCode, HttpServletResponse response)
{
- fieldsValidator = new FieldsValidator();
+ FieldsValidator fieldsValidator = new FieldsValidator();
if (statusCode == HttpStatus.NOT_FOUND || statusCode == HttpStatus.FORBIDDEN) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
+ fieldsValidator.httpStatusCode = (long) HttpServletResponse.SC_NOT_FOUND;
logger.error(EELFLoggerDelegate.errorLogger, "setResponse failed"+ "invalid namespace");
}else if (statusCode == HttpStatus.UNAUTHORIZED) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_UNAUTHORIZED);
+ fieldsValidator.httpStatusCode = (long) HttpServletResponse.SC_UNAUTHORIZED;
logger.error(EELFLoggerDelegate.errorLogger, "setResponse failed"+ "unauthorized");
} else{
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ fieldsValidator.httpStatusCode = (long) HttpServletResponse.SC_BAD_REQUEST;
logger.error(EELFLoggerDelegate.errorLogger, "setResponse failed ",statusCode);
}
@@ -880,7 +861,7 @@ public class AppsController extends EPRestrictedBaseController {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/onboardingApps" + appId, "DELETE result =",
+ EcompPortalUtils.logAndSerializeObject(logger, PORTAL_API_ONBOARDING_APPS + appId, "DELETE result =",
response.getStatus());
return fieldsValidator;
}
@@ -918,8 +899,29 @@ public class AppsController extends EPRestrictedBaseController {
HttpHeaders header = new HttpHeaders();
header.setContentType(mediaType);
header.setContentLength(app.getThumbnail().length);
- return new HttpEntity<byte[]>(app.getThumbnail(), header);
+ return new HttpEntity<>(app.getThumbnail(), header);
}
+ private void checkIfNameSpaceIsValid(OnboardingApp modifiedOnboardingApp, FieldsValidator fieldsValidator, HttpServletResponse response)
+ throws InvalidApplicationException {
+ try {
+ ResponseEntity<String> res = appService.checkIfNameSpaceIsValid(modifiedOnboardingApp.nameSpace);
+ } catch (HttpClientErrorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
+ EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+ if (e.getStatusCode() == HttpStatus.NOT_FOUND || e.getStatusCode() == HttpStatus.FORBIDDEN) {
+ fieldsValidator = setResponse(e.getStatusCode(),response);
+ throw new InvalidApplicationException("Invalid NameSpace");
+ }else{
+ fieldsValidator = setResponse(e.getStatusCode(),response);
+ throw e;
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception in checkIfNameSpaceIsValid", e);
+ }
+ }
+ private boolean isNotNullAndNotValid(Object o){
+ return o!=null && !dataValidator.isValid(o);
+ }
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java
index fe029e0e..0ae5aa82 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java
@@ -151,29 +151,33 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl
EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "request", epUser);
PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
- if (epUser!=null){
- Validator validator = VALIDATOR_FACTORY.getValidator();
- Set<ConstraintViolation<EPUser>> constraintViolations = validator.validate(epUser);
- if (!constraintViolations.isEmpty()){
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Data is not valid");
- return portalResponse;
- }
- }
+ if (epUser != null) {
+ Validator validator = VALIDATOR_FACTORY.getValidator();
+ Set<ConstraintViolation<EPUser>> constraintViolations = validator.validate(epUser);
+ if (!constraintViolations.isEmpty()) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage("Data is not valid");
+ return portalResponse;
+ }
+ }
- // Check mandatory fields.
- if (epUser.getEmail() == null || epUser.getEmail().trim().length() == 0 //
- || epUser.getLoginId() == null || epUser.getLoginId().trim().length() == 0 //
- || epUser.getLoginPwd() == null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Missing required field: email, loginId, or loginPwd");
- return portalResponse;
- }
+ // Check mandatory fields.
+ if (epUser != null && (epUser.getEmail() == null || epUser.getEmail().trim().length() == 0 //
+ || epUser.getLoginId() == null || epUser.getLoginId().trim().length() == 0 //
+ || epUser.getLoginPwd() == null)) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage("Missing required field: email, loginId, or loginPwd");
+ return portalResponse;
+ }
try {
- // Check for existing user; create if not found.
- List<EPUser> userList = userService.getUserByUserId(epUser.getOrgUserId());
- if (userList == null || userList.size() == 0) {
+ // Check for existing user; create if not found.
+ List<EPUser> userList = null;
+ if (epUser != null) {
+ userList = userService.getUserByUserId(epUser.getOrgUserId());
+ }
+
+ if (userList == null || userList.isEmpty()) {
// Create user with first, last names etc.; do check for
// duplicates.
String userCreateResult = userService.saveNewUser(epUser, "Yes");
@@ -185,17 +189,22 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl
}
// Check for Portal admin status; promote if not.
- if (adminRolesService.isSuperAdmin(epUser)) {
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- } else {
- FieldsValidator fv = portalAdminService.createPortalAdmin(epUser.getOrgUserId());
- if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- } else {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(fv.toString());
- }
- }
+ if (adminRolesService.isSuperAdmin(epUser)) {
+ portalResponse.setStatus(PortalRestStatusEnum.OK);
+ } else {
+ FieldsValidator fv = null;
+ if (epUser != null) {
+ fv = portalAdminService.createPortalAdmin(epUser.getOrgUserId());
+ }
+ if (fv != null && fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
+ portalResponse.setStatus(PortalRestStatusEnum.OK);
+ } else {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ if (fv != null) {
+ portalResponse.setMessage(fv.toString());
+ }
+ }
+ }
} catch (Exception ex) {
// Uncaught exceptions yield 404 and an empty error page
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
@@ -273,29 +282,37 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl
}
}
// Validate fields
- if (newOnboardApp.id != null) {
+ if (newOnboardApp != null && newOnboardApp.id != null) {
portalResponse.setStatus(PortalRestStatusEnum.ERROR);
portalResponse.setMessage("Unexpected field: id");
return portalResponse;
}
- if (newOnboardApp.name == null || newOnboardApp.name.trim().length() == 0 //
- || newOnboardApp.url == null || newOnboardApp.url.trim().length() == 0 //
- || newOnboardApp.restUrl == null || newOnboardApp.restUrl.trim().length() == 0
- || newOnboardApp.myLoginsAppOwner == null || newOnboardApp.myLoginsAppOwner.trim().length() == 0
- || newOnboardApp.restrictedApp == null //
- || newOnboardApp.isOpen == null //
- || newOnboardApp.isEnabled == null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(
- "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner");
- return portalResponse;
- }
+ if (newOnboardApp != null && (newOnboardApp.name == null || newOnboardApp.name.trim().length() == 0 //
+ || newOnboardApp.url == null || newOnboardApp.url.trim().length() == 0 //
+ || newOnboardApp.restUrl == null || newOnboardApp.restUrl.trim().length() == 0
+ || newOnboardApp.myLoginsAppOwner == null || newOnboardApp.myLoginsAppOwner.trim().length() == 0
+ || newOnboardApp.restrictedApp == null //
+ || newOnboardApp.isOpen == null //
+ || newOnboardApp.isEnabled == null)) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage(
+ "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner");
+ return portalResponse;
+ }
try {
- List<EPUser> userList = userService.getUserByUserId(newOnboardApp.myLoginsAppOwner);
- if (userList == null || userList.size() != 1) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Failed to find user: " + newOnboardApp.myLoginsAppOwner);
+ List<EPUser> userList = null;
+ if (newOnboardApp != null) {
+ userList = userService.getUserByUserId(newOnboardApp.myLoginsAppOwner);
+ }
+ if (userList == null || userList.size() != 1) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ if (newOnboardApp != null) {
+ portalResponse.setMessage("Failed to find user: " + newOnboardApp.myLoginsAppOwner);
+ } else {
+ portalResponse.setMessage("Failed to find user");
+ }
+
return portalResponse;
}
@@ -370,18 +387,18 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl
}
// Validate fields.
- if (oldOnboardApp.id == null || !appId.equals(oldOnboardApp.id)) {
+ if (oldOnboardApp !=null && (oldOnboardApp.id == null || !appId.equals(oldOnboardApp.id))) {
portalResponse.setStatus(PortalRestStatusEnum.ERROR);
portalResponse.setMessage("Unexpected value for field: id");
return portalResponse;
}
- if (oldOnboardApp.name == null || oldOnboardApp.name.trim().length() == 0 //
+ if (oldOnboardApp !=null && (oldOnboardApp.name == null || oldOnboardApp.name.trim().length() == 0 //
|| oldOnboardApp.url == null || oldOnboardApp.url.trim().length() == 0 //
|| oldOnboardApp.restUrl == null || oldOnboardApp.restUrl.trim().length() == 0
|| oldOnboardApp.myLoginsAppOwner == null || oldOnboardApp.myLoginsAppOwner.trim().length() == 0
|| oldOnboardApp.restrictedApp == null //
|| oldOnboardApp.isOpen == null //
- || oldOnboardApp.isEnabled == null) {
+ || oldOnboardApp.isEnabled == null)) {
portalResponse.setStatus(PortalRestStatusEnum.ERROR);
portalResponse.setMessage(
"Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner");
@@ -389,12 +406,20 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl
}
try {
- List<EPUser> userList = userService.getUserByUserId(oldOnboardApp.myLoginsAppOwner);
- if (userList == null || userList.size() != 1) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Failed to find user: " + oldOnboardApp.myLoginsAppOwner);
- return portalResponse;
- }
+ List<EPUser> userList = null;
+ if (oldOnboardApp != null) {
+ userList = userService.getUserByUserId(oldOnboardApp.myLoginsAppOwner);
+ }
+ if (userList == null || userList.size() != 1) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ if (oldOnboardApp != null) {
+ portalResponse.setMessage("Failed to find user: " + oldOnboardApp.myLoginsAppOwner);
+ } else {
+ portalResponse.setMessage("Failed to find user");
+ }
+
+ return portalResponse;
+ }
EPUser epUser = userList.get(0);
// Check for Portal admin status
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuditLogController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuditLogController.java
index 67d75666..cff8245a 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuditLogController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuditLogController.java
@@ -43,6 +43,8 @@ import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
+import org.onap.portalapp.validation.DataValidator;
+import org.onap.portalapp.validation.SecureString;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -68,14 +70,18 @@ import org.onap.portalsdk.core.util.SystemProperties;
@RestController
@RequestMapping("/portalApi/auditLog")
public class AuditLogController extends EPRestrictedBaseController {
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
+ private static final DataValidator dataValidator = new DataValidator();
- @Autowired
private AuditService auditService;
+ @Autowired
+ public AuditLogController(AuditService auditService) {
+ this.auditService = auditService;
+ }
/**
* Store audit log of the specified access type.
- *
+ *
* @param request
* HttpServletRequest
* @param affectedAppId
@@ -90,34 +96,50 @@ public class AuditLogController extends EPRestrictedBaseController {
@RequestParam String comment) {
logger.debug(EELFLoggerDelegate.debugLogger, "auditLog: appId {}, type {}, comment {}", affectedAppId, type,
comment);
- String cd_type = null;
+ String cdType = null;
+
+ SecureString secureString0 = new SecureString(affectedAppId);
+ SecureString secureString1 = new SecureString(type);
+ SecureString secureString2 = new SecureString(comment);
+ if ( !dataValidator.isValid(secureString0)
+ ||!dataValidator.isValid(secureString1)
+ ||!dataValidator.isValid(secureString2)){
+ return;
+ }
+
try {
EPUser user = EPUserUtils.getUserSession(request);
/* Check type of Activity CD */
- if (type.equals("app")) {
- cd_type = AuditLog.CD_ACTIVITY_APP_ACCESS;
- } else if (type.equals("tab")) {
- cd_type = AuditLog.CD_ACTIVITY_TAB_ACCESS;
- } else if (type.equals("functional")) {
- cd_type = AuditLog.CD_ACTIVITY_FUNCTIONAL_ACCESS;
- } else if (type.equals("leftMenu")) {
- cd_type = AuditLog.CD_ACTIVITY_LEFT_MENU_ACCESS;
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,
+ switch (type) {
+ case "app":
+ cdType = AuditLog.CD_ACTIVITY_APP_ACCESS;
+ break;
+ case "tab":
+ cdType = AuditLog.CD_ACTIVITY_TAB_ACCESS;
+ break;
+ case "functional":
+ cdType = AuditLog.CD_ACTIVITY_FUNCTIONAL_ACCESS;
+ break;
+ case "leftMenu":
+ cdType = AuditLog.CD_ACTIVITY_LEFT_MENU_ACCESS;
+ break;
+ default:
+ logger.error(EELFLoggerDelegate.errorLogger,
"Storing auditLog failed! Activity CD type is not correct.");
+ break;
}
/* Store the audit log only if it contains valid Activity CD */
- if (cd_type != null) {
+ if (cdType != null) {
AuditLog auditLog = new AuditLog();
- auditLog.setActivityCode(cd_type);
+ auditLog.setActivityCode(cdType);
/*
* Check affectedAppId and comment and see if these two values
* are valid
*/
- if (comment != null && !comment.equals("") && !comment.equals("undefined"))
+ if (comment != null && !comment.isEmpty() && !"undefined".equals(comment))
auditLog.setComments(
EcompPortalUtils.truncateString(comment, PortalConstants.AUDIT_LOG_COMMENT_SIZE));
- if (affectedAppId != null && !affectedAppId.equals("") && !affectedAppId.equals("undefined"))
+ if (affectedAppId != null && !affectedAppId.isEmpty() && !"undefined".equals(affectedAppId))
auditLog.setAffectedRecordId(affectedAppId);
long userId = EPUserUtils.getUserId(request);
auditLog.setUserId(userId);
@@ -140,7 +162,7 @@ public class AuditLogController extends EPRestrictedBaseController {
MDC.put(SystemProperties.MDC_TIMER, timeDifference);
MDC.put(EPCommonSystemProperties.STATUS_CODE, "COMPLETE");
logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage(
- "AuditLogController.auditLog", cd_type, user.getOrgUserId(), affectedAppId, comment));
+ "AuditLogController.auditLog", cdType, user.getOrgUserId(), affectedAppId, comment));
MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperController.java
index fe2c349f..969605ce 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperController.java
@@ -36,6 +36,8 @@
*/
package org.onap.portalapp.portal.controller;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.swagger.annotations.ApiOperation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
@@ -44,13 +46,13 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.jar.Attributes;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
import org.onap.aaf.cadi.aaf.AAFPermission;
import org.onap.portalapp.annotation.ApiVersion;
import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
@@ -67,6 +69,8 @@ import org.onap.portalapp.portal.transport.EpNotificationItem;
import org.onap.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
import org.onap.portalapp.portal.transport.FunctionalMenuItem;
import org.onap.portalapp.portal.transport.OnboardingApp;
+import org.onap.portalapp.validation.DataValidator;
+import org.onap.portalapp.validation.SecureString;
import org.onap.portalsdk.core.domain.Role;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
@@ -76,6 +80,7 @@ import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
+import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
@@ -85,18 +90,15 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import io.swagger.annotations.ApiOperation;
-
@RestController
@RequestMapping("/auxapi")
-@org.springframework.context.annotation.Configuration
+@Configuration
@EnableAspectJAutoProxy
@EPAuditLog
public class AuxApiRequestMapperController implements ApplicationContextAware, BasicAuthenticationController {
private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AuxApiRequestMapperController.class);
+ private DataValidator dataValidator = new DataValidator();
ApplicationContext context = null;
int minorVersion = 0;
@@ -108,6 +110,13 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@RequestMapping(value = { "/v3/user/{loginId}" }, method = RequestMethod.GET, produces = "application/json")
public String getUser(HttpServletRequest request, HttpServletResponse response,
@PathVariable("loginId") String loginId) throws Exception {
+ if (loginId!=null){
+ SecureString secureLoginId = new SecureString(loginId);
+ if (!dataValidator.isValid(secureLoginId))
+ return "Provided data is not valid";
+ }
+
+
Map<String, Object> res = getMethod(request, response);
String answer = null;
try {
@@ -198,6 +207,12 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@RequestMapping(value = { "/v3/function/{code}" }, method = RequestMethod.GET, produces = "application/json")
public CentralV2RoleFunction getRoleFunction(HttpServletRequest request, HttpServletResponse response,
@PathVariable("code") String code) throws Exception {
+ if (code!=null){
+ SecureString secureCode = new SecureString(code);
+ if (!dataValidator.isValid(secureCode))
+ return new CentralV2RoleFunction();
+ }
+
Map<String, Object> res = getMethod(request, response);
CentralV2RoleFunction roleFunction = null;
try {
@@ -213,15 +228,24 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@RequestMapping(value = { "/v3/roleFunction" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response,
@RequestBody String roleFunc) throws Exception {
- PortalRestResponse<String> result = null;
+ if (roleFunc!=null){
+ SecureString secureRoleFunc = new SecureString(roleFunc);
+ if(!dataValidator.isValid(secureRoleFunc))
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Provided data is not valid", "Failed");
+ }
+ Optional<PortalRestResponse<String>> result = null;
Map<String, Object> res = getMethod(request, response);
try {
- result = (PortalRestResponse<String>) invokeMethod(res, request, response, roleFunc);
- return result;
+ result = Optional.ofNullable((PortalRestResponse<String>) invokeMethod(res, request, response));
+ if (!result.isPresent()){
+ logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed", new Exception("saveRoleFunction failed"));
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "saveRoleFunction failed", "Failed");
+ }
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
}
+ return result.get();
}
@SuppressWarnings("unchecked")
@@ -230,6 +254,13 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
public PortalRestResponse<String> deleteRoleFunction(HttpServletRequest request, HttpServletResponse response,
@PathVariable("code") String code) throws Exception {
PortalRestResponse<String> result = null;
+
+ if (code!=null){
+ SecureString secureCode = new SecureString(code);
+ if(!dataValidator.isValid(secureCode))
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Provided data is not valid", "Failed");
+ }
+
Map<String, Object> res = getMethod(request, response);
try {
result = (PortalRestResponse<String>) invokeMethod(res, request, response, code);
@@ -252,7 +283,7 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
return result;
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
}
}
@@ -276,6 +307,14 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
public String getEcompUser(HttpServletRequest request, HttpServletResponse response,
@PathVariable("loginId") String loginId) throws Exception {
Map<String, Object> res = getMethod(request, response);
+
+ if (loginId!=null){
+ SecureString secureLoginId = new SecureString(loginId);
+
+ if (!dataValidator.isValid(secureLoginId))
+ return null;
+ }
+
String answer = null;
try {
answer = (String) invokeMethod(res, request, response, loginId);
@@ -319,6 +358,14 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@RequestMapping(value = { "/v3/extendSessionTimeOuts" }, method = RequestMethod.POST)
public Boolean extendSessionTimeOuts(HttpServletRequest request, HttpServletResponse response,
@RequestParam String sessionMap) throws Exception {
+
+ if (sessionMap!=null){
+ SecureString secureSessionMap = new SecureString(sessionMap);
+ if (!dataValidator.isValid(secureSessionMap)){
+ return null;
+ }
+ }
+
Map<String, Object> res = getMethod(request, response);
Boolean ans = null;
try {
@@ -347,6 +394,12 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, HttpServletResponse response,
@RequestBody Analytics analyticsMap) throws Exception {
+
+ if (analyticsMap!=null){
+ if (!dataValidator.isValid(analyticsMap))
+ return new PortalAPIResponse(false, "analyticsScript is not valid");
+ }
+
Map<String, Object> res = getMethod(request, response);
PortalAPIResponse ans = new PortalAPIResponse(true, "error");
try {
@@ -364,16 +417,19 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
"/v3/upload/portal/functions" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> bulkUploadFunctions(HttpServletRequest request, HttpServletResponse response)
throws Exception {
- PortalRestResponse<String> result = null;
+ Optional<PortalRestResponse<String>> result = null;
Map<String, Object> res = getMethod(request, response);
try {
- result = (PortalRestResponse<String>) invokeMethod(res, request, response);
- return result;
+ result = Optional.ofNullable((PortalRestResponse<String>) invokeMethod(res, request, response));
+ if (!result.isPresent()){
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to bulkUploadFunctions", new Exception("Failed to bulkUploadFunctions"));
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed");
+ }
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e);
return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
}
-
+ return result.get();
}
@SuppressWarnings("unchecked")
@@ -381,11 +437,15 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@RequestMapping(value = { "/v3/upload/portal/roles" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> bulkUploadRoles(HttpServletRequest request, HttpServletResponse response)
throws Exception {
- PortalRestResponse<String> result = null;
+ Optional<PortalRestResponse<String>> result;
Map<String, Object> res = getMethod(request, response);
try {
- result = (PortalRestResponse<String>) invokeMethod(res, request, response);
- return result;
+ result = Optional.ofNullable((PortalRestResponse<String>) invokeMethod(res, request, response));
+ if (!result.isPresent()){
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to bulkUploadRoles", new Exception("Failed to bulkUploadRoles"));
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed");
+ }
+ return result.get();
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e);
return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
@@ -398,11 +458,15 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
"/v3/upload/portal/roleFunctions" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> bulkUploadRoleFunctions(HttpServletRequest request, HttpServletResponse response)
throws Exception {
- PortalRestResponse<String> result = null;
+ Optional<PortalRestResponse<String>> result;
Map<String, Object> res = getMethod(request, response);
try {
- result = (PortalRestResponse<String>) invokeMethod(res, request, response);
- return result;
+ result = Optional.ofNullable((PortalRestResponse<String>) invokeMethod(res, request, response));
+ if (!result.isPresent()){
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to bulkUploadRoleFunctions", new Exception("Failed to bulkUploadRoleFunctions"));
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoleFunctions", "Failed");
+ }
+ return result.get();
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoleFunctions failed", e);
return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
@@ -415,11 +479,15 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
"/v3/upload/portal/userRoles" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> bulkUploadUserRoles(HttpServletRequest request, HttpServletResponse response)
throws Exception {
- PortalRestResponse<String> result = null;
+ Optional<PortalRestResponse<String>> result;
Map<String, Object> res = getMethod(request, response);
try {
- result = (PortalRestResponse<String>) invokeMethod(res, request, response);
- return result;
+ result = Optional.ofNullable((PortalRestResponse<String>) invokeMethod(res, request, response));
+ if (!result.isPresent()){
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to bulkUploadUserRoles", new Exception("Failed to bulkUploadUserRoles"));
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadUserRoles", "Failed");
+ }
+ return result.get();
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadUserRoles failed", e);
return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
@@ -433,11 +501,15 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
"/v3/upload/portal/userRole/{roleId}" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> bulkUploadUsersSingleRole(HttpServletRequest request,
HttpServletResponse response, @PathVariable Long roleId) throws Exception {
- PortalRestResponse<String> result = null;
+ Optional<PortalRestResponse<String>> result = null;
Map<String, Object> res = getMethod(request, response);
try {
- result = (PortalRestResponse<String>) invokeMethod(res, request, response, roleId);
- return result;
+ result = Optional.ofNullable((PortalRestResponse<String>) invokeMethod(res, request, response));
+ if (!result.isPresent()){
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to bulkUploadUsersSingleRole", new Exception("Failed to bulkUploadUsersSingleRole"));
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadUsersSingleRole", "Failed");
+ }
+ return result.get();
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadUsersSingleRole failed", e);
return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
@@ -450,11 +522,15 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
"/v3/upload/partner/functions" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> bulkUploadPartnerFunctions(HttpServletRequest request,
HttpServletResponse response) throws Exception {
- PortalRestResponse<String> result = null;
+ Optional<PortalRestResponse<String>> result = null;
Map<String, Object> res = getMethod(request, response);
try {
- result = (PortalRestResponse<String>) invokeMethod(res, request, response);
- return result;
+ result = Optional.ofNullable((PortalRestResponse<String>) invokeMethod(res, request, response));
+ if (!result.isPresent()){
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to bulkUploadPartnerRoleFunctions", new Exception("Failed to bulkUploadPartnerRoleFunctions"));
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadPartnerRoleFunctions", "Failed");
+ }
+ return result.get();
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions failed", e);
return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
@@ -467,11 +543,15 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@RequestMapping(value = { "/v3/upload/partner/roles" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> bulkUploadPartnerRoles(HttpServletRequest request, HttpServletResponse response,
@RequestBody List<Role> upload) throws Exception {
- PortalRestResponse<String> result = null;
+ Optional<PortalRestResponse<String>> result = null;
Map<String, Object> res = getMethod(request, response);
try {
- result = (PortalRestResponse<String>) invokeMethod(res, request, response, upload);
- return result;
+ result = Optional.ofNullable((PortalRestResponse<String>) invokeMethod(res, request, response));
+ if (!result.isPresent()){
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to bulkUploadRoles", new Exception("Failed to bulkUploadRoles"));
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed");
+ }
+ return result.get();
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoles failed", e);
return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
@@ -484,11 +564,15 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
"/v3/upload/partner/roleFunctions" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> bulkUploadPartnerRoleFunctions(HttpServletRequest request,
HttpServletResponse response) throws Exception {
- PortalRestResponse<String> result = null;
+ Optional<PortalRestResponse<String>> result = null;
Map<String, Object> res = getMethod(request, response);
try {
- result = (PortalRestResponse<String>) invokeMethod(res, request, response);
- return result;
+ result = Optional.ofNullable((PortalRestResponse<String>) invokeMethod(res, request, response));
+ if (!result.isPresent()){
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to bulkUploadPartnerRoleFunctions", new Exception("Failed to bulkUploadPartnerRoleFunctions"));
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadPartnerRoleFunctions", "Failed");
+ }
+ return result.get();
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions failed", e);
return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
@@ -715,6 +799,12 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@RequestMapping(value = { "/v3/userProfile" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> postUserProfile(HttpServletRequest request,
@RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
+
+ if (extSysUser!=null){
+ if (!dataValidator.isValid(extSysUser))
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ExternalSystemUser is not valid", "Failed");
+ }
+
PortalRestResponse<String> result = null;
Map<String, Object> res = getMethod(request, response);
try {
@@ -731,6 +821,12 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@RequestMapping(value = { "/v3/userProfile" }, method = RequestMethod.PUT, produces = "application/json")
public PortalRestResponse<String> putUserProfile(HttpServletRequest request,
@RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
+
+ if (extSysUser!=null){
+ if (!dataValidator.isValid(extSysUser))
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ExternalSystemUser is not valid", "Failed");
+ }
+
PortalRestResponse<String> result = null;
Map<String, Object> res = getMethod(request, response);
try {
@@ -747,6 +843,12 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@RequestMapping(value = { "/v3/userProfile" }, method = RequestMethod.DELETE, produces = "application/json")
public PortalRestResponse<String> deleteUserProfile(HttpServletRequest request,
@RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
+
+ if (extSysUser!=null){
+ if (!dataValidator.isValid(extSysUser))
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ExternalSystemUser is not valid", "Failed");
+ }
+
PortalRestResponse<String> result = null;
Map<String, Object> res = getMethod(request, response);
try {
@@ -763,6 +865,13 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@RequestMapping(value = { "/v3/ticketevent" }, method = RequestMethod.POST)
public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response,
@RequestBody String ticketEventJson) throws Exception {
+
+ if (ticketEventJson!=null){
+ SecureString secureTicketEventJson = new SecureString(ticketEventJson);
+ if (!dataValidator.isValid(secureTicketEventJson))
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ticketEventJson is not valid", "Failed");
+ }
+
PortalRestResponse<String> result = null;
Map<String, Object> res = getMethod(request, response);
try {
@@ -780,6 +889,12 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@ResponseBody
public PortalRestResponse<String> postPortalAdmin(HttpServletRequest request, HttpServletResponse response,
@RequestBody EPUser epUser) {
+
+ if (epUser!=null){
+ if (!dataValidator.isValid(epUser))
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "EPUser is not valid", "Failed");
+ }
+
PortalRestResponse<String> result = null;
Map<String, Object> res = getMethod(request, response);
try {
@@ -812,6 +927,12 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@ResponseBody
public PortalRestResponse<String> postOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
@RequestBody OnboardingApp newOnboardApp) {
+
+ if (newOnboardApp!=null){
+ if (!dataValidator.isValid(newOnboardApp))
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "OnboardingApp is not valid", "Failed");
+ }
+
PortalRestResponse<String> result = new PortalRestResponse<>();
Map<String, Object> res = getMethod(request, response);
try {
@@ -830,7 +951,13 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@ResponseBody
public PortalRestResponse<String> putOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
@PathVariable("appId") Long appId, @RequestBody OnboardingApp oldOnboardApp) {
- PortalRestResponse<String> result = new PortalRestResponse<>();
+
+ if (oldOnboardApp!=null){
+ if (!dataValidator.isValid(oldOnboardApp))
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "OnboardingApp is not valid", "Failed");
+ }
+
+ PortalRestResponse<String> result;
Map<String, Object> res = getMethod(request, response);
try {
result = (PortalRestResponse<String>) invokeMethod(res, request, response, appId, oldOnboardApp);
@@ -845,12 +972,16 @@ public class AuxApiRequestMapperController implements ApplicationContextAware, B
@RequestMapping(value = { "/v3/publishNotification" }, method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public PortalAPIResponse publishNotification(HttpServletRequest request,
- @RequestBody EpNotificationItem notificationItem, HttpServletResponse response) throws Exception {
- PortalAPIResponse result = new PortalAPIResponse(true, "success");
+ @RequestBody EpNotificationItem notificationItem, HttpServletResponse response) {
+
+ if (notificationItem!=null){
+ if (!dataValidator.isValid(notificationItem))
+ return new PortalAPIResponse(false, "EpNotificationItem is not valid");
+ }
+
Map<String, Object> res = getMethod(request, response);
try {
- result = (PortalAPIResponse) invokeMethod(res, request, response, notificationItem);
- return result;
+ return (PortalAPIResponse) invokeMethod(res, request, response, notificationItem);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "publishNotification failed", e);
return new PortalAPIResponse(false, e.getMessage());
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardController.java
index 727d190d..6137aec9 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardController.java
@@ -66,6 +66,8 @@ import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.portal.utils.PortalConstants;
import org.onap.portalapp.util.EPUserUtils;
+import org.onap.portalapp.validation.DataValidator;
+import org.onap.portalapp.validation.SecureString;
import org.onap.portalsdk.core.domain.AuditLog;
import org.onap.portalsdk.core.domain.support.CollaborateList;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
@@ -87,19 +89,23 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/portalApi/dashboard")
public class DashboardController extends EPRestrictedBaseController {
+ private static final DataValidator DATA_VALIDATOR = new DataValidator();
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
-
- @Autowired
private DashboardSearchService searchService;
- @Autowired
private AuditService auditService;
-
- @Autowired
private AdminRolesService adminRolesService;
-
+
+ @Autowired
+ public DashboardController(DashboardSearchService searchService,
+ AuditService auditService, AdminRolesService adminRolesService) {
+ this.searchService = searchService;
+ this.auditService = auditService;
+ this.adminRolesService = adminRolesService;
+ }
+
public enum WidgetCategory {
- EVENTS, NEWS, IMPORTANTRESOURCES;
+ EVENTS, NEWS, IMPORTANTRESOURCES
}
/**
@@ -129,11 +135,15 @@ public class DashboardController extends EPRestrictedBaseController {
@RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json")
public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
@RequestParam String resourceType) {
- if (!isValidResourceType(resourceType))
- return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.ERROR,
- "Unexpected resource type " + resourceType, null);
- return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success",
- searchService.getWidgetData(resourceType));
+ if (!isValidResourceType(resourceType)) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Unexpected resource type " + resourceType, null);
+ }else if (!DATA_VALIDATOR.isValid(new SecureString(resourceType))){
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Unsafe resource type " + resourceType, null);
+ }
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
+ searchService.getWidgetData(resourceType));
}
@@ -147,20 +157,23 @@ public class DashboardController extends EPRestrictedBaseController {
@RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
- if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals(""))
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
- "Category cannot be null or empty");
- if (!isValidResourceType(commonWidgetMeta.getCategory()))
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
- "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
- // validate dates
+ if (!DATA_VALIDATOR.isValid(commonWidgetMeta)){
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Unsafe resource type " + commonWidgetMeta, "ERROR");
+ }else if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
+ "Category cannot be null or empty");
+ }else if (!isValidResourceType(commonWidgetMeta.getCategory())) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
+ }
for (CommonWidget cw : commonWidgetMeta.getItems()) {
String err = validateCommonWidget(cw);
if (err != null)
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
- searchService.saveWidgetDataBulk(commonWidgetMeta));
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
+ searchService.saveWidgetDataBulk(commonWidgetMeta));
}
/**
@@ -175,17 +188,21 @@ public class DashboardController extends EPRestrictedBaseController {
logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
EPUser user = EPUserUtils.getUserSession(request);
if (adminRolesService.isSuperAdmin(user)) {
- if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().isEmpty())
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
- "Category cannot be null or empty");
+ if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().isEmpty()) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
+ "Category cannot be null or empty");
+ }else if (!DATA_VALIDATOR.isValid(commonWidget)){
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Unsafe resource type " + commonWidget, "ERROR");
+ }
String err = validateCommonWidget(commonWidget);
if (err != null)
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
- searchService.saveWidgetData(commonWidget));
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
+ searchService.saveWidgetData(commonWidget));
} else {
EcompPortalUtils.setBadPermissions(user, response, "saveWidgetData");
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed", null);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed", null);
}
}
@@ -235,8 +252,12 @@ public class DashboardController extends EPRestrictedBaseController {
@RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
- searchService.deleteWidgetData(commonWidget));
+ if (!DATA_VALIDATOR.isValid(commonWidget)){
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Unsafe resource type " + commonWidget, "ERROR");
+ }
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
+ searchService.deleteWidgetData(commonWidget));
}
/**
@@ -251,7 +272,10 @@ public class DashboardController extends EPRestrictedBaseController {
@RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
@RequestParam String searchString) {
-
+ if (!DATA_VALIDATOR.isValid(new SecureString(searchString))){
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is not safe",
+ new HashMap<>());
+ }
if (searchString != null)
searchString = searchString.trim();
EPUser user = EPUserUtils.getUserSession(request);
@@ -259,10 +283,10 @@ public class DashboardController extends EPRestrictedBaseController {
if (user == null) {
return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
"searchPortal: User object is null? - check logs",
- new HashMap<String, List<SearchResultItem>>());
+ new HashMap<>());
} else if (searchString == null || searchString.length() == 0) {
return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
- new HashMap<String, List<SearchResultItem>>());
+ new HashMap<>());
} else {
logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
user.getLoginId(), searchString);
@@ -294,7 +318,7 @@ public class DashboardController extends EPRestrictedBaseController {
MDC.put(EPCommonSystemProperties.STATUS_CODE, "ERROR");
MDC.remove(EPCommonSystemProperties.STATUS_CODE);
return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
- new HashMap<String, List<SearchResultItem>>());
+ new HashMap<>());
}
}
@@ -308,7 +332,7 @@ public class DashboardController extends EPRestrictedBaseController {
*/
@RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
public List<String> getActiveUsers(HttpServletRequest request) {
- List<String> activeUsers = null;
+ List<String> activeUsers;
List<String> onlineUsers = new ArrayList<>();
try {
EPUser user = EPUserUtils.getUserSession(request);
@@ -341,7 +365,7 @@ public class DashboardController extends EPRestrictedBaseController {
String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION);
Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
- Map<String, String> results = new HashMap<String,String>();
+ Map<String, String> results = new HashMap<>();
results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));
return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
@@ -362,7 +386,7 @@ public class DashboardController extends EPRestrictedBaseController {
try {
String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);
Integer windowWidth = Integer.valueOf(windowWidthString);
- Map<String, String> results = new HashMap<String,String>();
+ Map<String, String> results = new HashMap<>();
results.put("windowWidth", String.valueOf(windowWidth));
return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
} catch (Exception e) {
@@ -383,7 +407,7 @@ public class DashboardController extends EPRestrictedBaseController {
try {
String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);
Integer windowWidth = Integer.valueOf(windowWidthString);
- Map<String, String> results = new HashMap<String,String>();
+ Map<String, String> results = new HashMap<>();
results.put("windowWidth", String.valueOf(windowWidth));
return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
} catch (Exception e) {
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java
index 5f6818f1..46493d86 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java
@@ -69,6 +69,8 @@ import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.portal.utils.PortalConstants;
+import org.onap.portalapp.validation.DataValidator;
+import org.onap.portalapp.validation.SecureString;
import org.onap.portalsdk.core.domain.AuditLog;
import org.onap.portalsdk.core.domain.Role;
import org.onap.portalsdk.core.domain.User;
@@ -76,7 +78,6 @@ import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.restful.domain.EcompRole;
import org.onap.portalsdk.core.restful.domain.EcompUser;
import org.onap.portalsdk.core.service.AuditService;
-import org.onap.portalsdk.core.service.UserService;
import org.onap.portalsdk.core.service.UserServiceCentalizedImpl;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.portalsdk.core.web.support.UserUtils;
@@ -90,7 +91,6 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -104,36 +104,39 @@ import io.swagger.annotations.ApiOperation;
@EnableAspectJAutoProxy
@EPAuditLog
public class ExternalAccessRolesController implements BasicAuthenticationController {
-
private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
-
private static final String SUCCESSFULLY_DELETED = "Successfully Deleted";
-
private static final String INVALID_UEB_KEY = "Invalid credentials!";
-
private static final String LOGIN_ID = "LoginId";
-
- RestTemplate template = new RestTemplate();
-
- @Autowired
- private AuditService auditService;
-
private static final String UEBKEY = "uebkey";
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesController.class);
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesController.class);
+ private static final DataValidator DATA_VALIDATOR = new DataValidator();
- @Autowired
+ private AuditService auditService;
private ExternalAccessRolesService externalAccessRolesService;
+ private UserServiceCentalizedImpl userservice;
@Autowired
- private UserService userservice = new UserServiceCentalizedImpl();
+ public ExternalAccessRolesController(AuditService auditService,
+ ExternalAccessRolesService externalAccessRolesService,
+ UserServiceCentalizedImpl userservice) {
+ this.auditService = auditService;
+ this.externalAccessRolesService = externalAccessRolesService;
+ this.userservice = userservice;
+ }
+
@ApiOperation(value = "Gets user role for an application.", response = CentralUser.class, responseContainer="List")
@RequestMapping(value = {
"/user/{loginId}" }, method = RequestMethod.GET, produces = "application/json")
public CentralUser getUser(HttpServletRequest request, HttpServletResponse response,
@PathVariable("loginId") String loginId) throws Exception {
-
+ if (!DATA_VALIDATOR.isValid(new SecureString(loginId))){
+ sendErrorResponse(response, new Exception("Data is not valid"));
+ logger.error(EELFLoggerDelegate.errorLogger, "getUser not valid data");
+ return null;
+ }
CentralUser answer = null;
try {
fieldsValidation(request);
@@ -150,6 +153,11 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
"/v1/user/{loginId}" }, method = RequestMethod.GET, produces = "application/json")
public String getV2UserList(HttpServletRequest request, HttpServletResponse response,
@PathVariable("loginId") String loginId) throws Exception {
+ if (!DATA_VALIDATOR.isValid(new SecureString(loginId))){
+ sendErrorResponse(response, new Exception("Data is not valid"));
+ logger.error(EELFLoggerDelegate.errorLogger, "getV2UserList not valid data");
+ return "Data is not valid";
+ }
String answer = null;
try {
fieldsValidation(request);
@@ -300,6 +308,10 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
@PathVariable("code") String code) throws Exception {
CentralV2RoleFunction centralV2RoleFunction = null;
CentralRoleFunction centralRoleFunction = new CentralRoleFunction();
+ if(!DATA_VALIDATOR.isValid(new SecureString(code))){
+ sendErrorResponse(response, new Exception("Data is not valid"));
+ logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction failed", new Exception("Data is not valid"));
+ }
try {
fieldsValidation(request);
centralV2RoleFunction = externalAccessRolesService.getRoleFunction(code, request.getHeader(UEBKEY));
@@ -318,6 +330,10 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
public CentralV2RoleFunction getV2RoleFunction(HttpServletRequest request, HttpServletResponse response,
@PathVariable("code") String code) throws Exception {
CentralV2RoleFunction centralV2RoleFunction = null;
+ if(!DATA_VALIDATOR.isValid(new SecureString(code))){
+ sendErrorResponse(response, new Exception("Data is not valid"));
+ logger.error(EELFLoggerDelegate.errorLogger, "getV2RoleFunction failed", new Exception("Data is not valid"));
+ }
try {
fieldsValidation(request);
centralV2RoleFunction = externalAccessRolesService.getRoleFunction(code, request.getHeader(UEBKEY));
@@ -334,16 +350,20 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
@ApiOperation(value = "Saves role function for an application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/roleFunction" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response,
- @RequestBody String roleFunc) throws Exception {
+ @RequestBody String roleFunc) {
String status = "Successfully saved!";
+ if(!DATA_VALIDATOR.isValid(new SecureString(roleFunc))){
+ logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Failed to roleFunc, not valid data.", "Failed");
+ }
try {
fieldsValidation(request);
- String data = roleFunc;
- ObjectMapper mapper = new ObjectMapper();
+ ObjectMapper mapper = new ObjectMapper();
List<EPApp> applicationList = externalAccessRolesService.getApp(request.getHeader(UEBKEY));
EPApp requestedApp = applicationList.get(0);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
+ CentralV2RoleFunction availableRoleFunction = mapper.readValue(roleFunc, CentralV2RoleFunction.class);
CentralV2RoleFunction domainRoleFunction = null;
boolean isCentralV2Version = false;
if(availableRoleFunction.getType()!=null && availableRoleFunction.getAction()!= null) {
@@ -405,8 +425,8 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
MDC.remove(SystemProperties.MDC_TIMER);
} else {
logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed");
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
- "Failed to saveRoleFunction for '" + availableRoleFunction.getCode() + "'", "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Failed to saveRoleFunction for '" + availableRoleFunction.getCode() + "'", "Failed");
}
} catch (Exception e) {
if (e.getMessage() == null ||e.getMessage().contains(INVALID_UEB_KEY)) {
@@ -415,15 +435,20 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, status, "Success");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, status, "Success");
}
@ApiOperation(value = "Deletes role function for an application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/roleFunction/{code}" }, method = RequestMethod.DELETE, produces = "application/json")
public PortalRestResponse<String> deleteRoleFunction(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("code") String code) throws Exception {
+ @PathVariable("code") String code) {
+ if(!DATA_VALIDATOR.isValid(new SecureString(code))){
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Failed to deleteRoleFunction, not valid data.", "Failed");
+ }
try {
fieldsValidation(request);
EPUser user = externalAccessRolesService.getUser(request.getHeader(LOGIN_ID)).get(0);
@@ -454,8 +479,8 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
MDC.remove(SystemProperties.MDC_TIMER);
} else {
logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed");
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
- "Failed to deleteRoleFunction for '" + code + "'", "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Failed to deleteRoleFunction for '" + code + "'", "Failed");
}
} catch (Exception e) {
if (e.getMessage().contains(INVALID_UEB_KEY)) {
@@ -473,7 +498,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
@ApiOperation(value = "Saves role for an application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/role" }, method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> saveRole(HttpServletRequest request, HttpServletResponse response,
- @RequestBody Role role) throws Exception {
+ @RequestBody Role role) {
try {
fieldsValidation(request);
ExternalRequestFieldsValidator saveRoleResult = null;
@@ -526,15 +551,20 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Successfully Saved", "Success");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully Saved", "Success");
}
@ApiOperation(value = "Deletes role for an application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/deleteRole/{code}" }, method = RequestMethod.DELETE, produces = "application/json")
public PortalRestResponse<String> deleteRole(HttpServletRequest request, HttpServletResponse response,
- @PathVariable String code) throws Exception {
+ @PathVariable String code) {
+ if(!DATA_VALIDATOR.isValid(new SecureString(code))){
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Failed to deleteRole, not valid data.", "Failed");
+ }
try {
fieldsValidation(request);
boolean deleteResponse = externalAccessRolesService.deleteRoleForApplication(code,
@@ -566,8 +596,8 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
MDC.remove(SystemProperties.MDC_TIMER);
} else {
logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed");
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
- "Failed to deleteRole for '" + code + "'", "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "Failed to deleteRole for '" + code + "'", "Failed");
}
} catch (Exception e) {
if (e.getMessage().contains(INVALID_UEB_KEY)) {
@@ -576,9 +606,9 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, SUCCESSFULLY_DELETED, "Success");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESSFULLY_DELETED, "Success");
}
@ApiOperation(value = "Gets active roles for an application.", response = CentralRole.class, responseContainer = "Json")
@@ -615,7 +645,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
@ApiOperation(value = "deletes user roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/deleteDependcyRoleRecord/{roleId}" }, method = RequestMethod.DELETE, produces = "application/json")
public PortalRestResponse<String> deleteDependencyRoleRecord(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("roleId") Long roleId) throws Exception {
+ @PathVariable("roleId") Long roleId) {
ExternalRequestFieldsValidator removeResult = null;
try {
fieldsValidation(request);
@@ -642,7 +672,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
@ApiOperation(value = "deletes roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/v2/deleteRole/{roleId}" }, method = RequestMethod.DELETE, produces = "application/json")
public PortalRestResponse<String> deleteRole(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("roleId") Long roleId) throws Exception {
+ @PathVariable("roleId") Long roleId) {
ExternalRequestFieldsValidator removeResult = null;
try {
fieldsValidation(request);
@@ -668,63 +698,63 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
@ApiOperation(value = "Bulk upload functions for an application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/upload/portal/functions" }, method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> bulkUploadFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ public PortalRestResponse<String> bulkUploadFunctions(HttpServletRequest request, HttpServletResponse response) {
Integer result = 0;
try {
result = externalAccessRolesService.bulkUploadFunctions(request.getHeader(UEBKEY));
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed");
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Successfully added: "+result, "Success");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
}
@ApiOperation(value = "Bulk upload roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/upload/portal/roles" }, method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> bulkUploadRoles(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ public PortalRestResponse<String> bulkUploadRoles(HttpServletRequest request, HttpServletResponse response) {
Integer result = 0;
try {
result = externalAccessRolesService.bulkUploadRoles(request.getHeader(UEBKEY));
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed");
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Successfully added: "+result, "Success");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
}
@ApiOperation(value = "Bulk upload role functions for an application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/upload/portal/roleFunctions" }, method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> bulkUploadRoleFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ public PortalRestResponse<String> bulkUploadRoleFunctions(HttpServletRequest request, HttpServletResponse response) {
Integer result = 0;
try {
result = externalAccessRolesService.bulkUploadRolesFunctions(request.getHeader(UEBKEY));
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoleFunctions failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoleFunctions", "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoleFunctions", "Failed");
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Successfully added: "+result, "Success");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
}
@ApiOperation(value = "Bulk upload user roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/upload/portal/userRoles" }, method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> bulkUploadUserRoles(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ public PortalRestResponse<String> bulkUploadUserRoles(HttpServletRequest request, HttpServletResponse response) {
Integer result = 0;
try {
result = externalAccessRolesService.bulkUploadUserRoles(request.getHeader(UEBKEY));
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadUserRoles failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadUserRoles", "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadUserRoles", "Failed");
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Successfully added: "+result, "Success");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
}
@ApiOperation(value = "Bulk upload users for renamed role of an application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/upload/portal/userRole/{roleId}" }, method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> bulkUploadUsersSingleRole(HttpServletRequest request, HttpServletResponse response, @PathVariable Long roleId) throws Exception {
+ public PortalRestResponse<String> bulkUploadUsersSingleRole(HttpServletRequest request, HttpServletResponse response, @PathVariable Long roleId) {
Integer result = 0;
try {
String roleName = request.getHeader("RoleName");
@@ -732,50 +762,53 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadUsersSingleRole failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadUsersSingleRole", "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadUsersSingleRole", "Failed");
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Successfully added: "+result, "Success");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
}
@ApiOperation(value = "Bulk upload functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/upload/partner/functions" }, method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> bulkUploadPartnerFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ public PortalRestResponse<String> bulkUploadPartnerFunctions(HttpServletRequest request, HttpServletResponse response) {
Integer addedFunctions = 0;
try {
addedFunctions = externalAccessRolesService.bulkUploadPartnerFunctions(request.getHeader(UEBKEY));
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed");
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Successfully added: '"+addedFunctions+"' functions", "Success");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK,
+ "Successfully added: '" + addedFunctions + "' functions", "Success");
}
@ApiOperation(value = "Bulk upload roles for an partner application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/upload/partner/roles" }, method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> bulkUploadPartnerRoles(HttpServletRequest request, HttpServletResponse response, @RequestBody List<Role> upload) throws Exception {
+ public PortalRestResponse<String> bulkUploadPartnerRoles(HttpServletRequest request, HttpServletResponse response, @RequestBody List<Role> upload) {
try {
externalAccessRolesService.bulkUploadPartnerRoles(request.getHeader(UEBKEY), upload);
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed");
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Successfully added", "Success");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added", "Success");
}
@ApiOperation(value = "Bulk upload role functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json")
@RequestMapping(value = { "/upload/partner/roleFunctions" }, method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> bulkUploadPartnerRoleFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ public PortalRestResponse<String> bulkUploadPartnerRoleFunctions(HttpServletRequest request, HttpServletResponse response) {
Integer addedRoleFunctions = 0;
try {
addedRoleFunctions = externalAccessRolesService.bulkUploadPartnerRoleFunctions(request.getHeader(UEBKEY));
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadPartnerRoleFunctions", "Failed");
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadPartnerRoleFunctions",
+ "Failed");
}
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Successfully added: '"+addedRoleFunctions + "' role functions", "Success");
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK,
+ "Successfully added: '" + addedRoleFunctions + "' role functions", "Success");
}
@ApiOperation(value = "Gets all functions along with global functions", response = List.class, responseContainer = "Json")
@@ -856,6 +889,10 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
@RequestMapping(value = { "/v2/user/{loginId}" }, method = RequestMethod.GET, produces = "application/json")
public String getEcompUser(HttpServletRequest request, HttpServletResponse response,
@PathVariable("loginId") String loginId) throws Exception {
+ if(!DATA_VALIDATOR.isValid(new SecureString(loginId))){
+ sendErrorResponse(response, new Exception("getEcompUser failed"));
+ logger.error(EELFLoggerDelegate.errorLogger, "getEcompUser failed", new Exception("getEcompUser failed"));
+ }
EcompUser user = new EcompUser();
ObjectMapper mapper = new ObjectMapper();
String answer = null;
@@ -868,7 +905,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl
user = UserUtils.convertToEcompUser(ecompUser);
List<EcompRole> missingRolesOfUser = externalAccessRolesService.missingUserApplicationRoles(request.getHeader(UEBKEY), loginId, user.getRoles());
if (missingRolesOfUser.size() > 0) {
- Set<EcompRole> roles = new TreeSet<EcompRole>(missingRolesOfUser);
+ Set<EcompRole> roles = new TreeSet<>(missingRolesOfUser);
user.getRoles().addAll(roles);
}
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/LanguageController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/LanguageController.java
index 383e4720..508b1be2 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/LanguageController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/LanguageController.java
@@ -15,15 +15,16 @@
*/
package org.onap.portalapp.portal.controller;
-import com.alibaba.fastjson.JSONObject;
-import org.onap.portalapp.portal.domain.Language;
-import org.onap.portalapp.portal.service.LanguageService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import java.util.List;
+import org.onap.portalapp.portal.service.LanguageService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import com.alibaba.fastjson.JSONObject;
@RestController
@RequestMapping("/auxapi")
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java
index b50d1cf4..9a525b51 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java
@@ -523,7 +523,7 @@ public class RoleManageController extends EPRestrictedBaseController {
EPApp requestedApp = appService.getApp(appId);
if (isAuthorizedUser(user, requestedApp)) {
fieldsValidation(requestedApp);
- if (requestedApp.getCentralAuth()) {
+ if (requestedApp.getCentralAuth() && roleFunc!=null) {
String code = roleFunc.getType() + PIPE + roleFunc.getCode() + PIPE + roleFunc.getAction();
CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
requestedApp.getUebKey());
@@ -679,7 +679,7 @@ public class RoleManageController extends EPRestrictedBaseController {
}
@RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET)
- public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException {
+ public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) {
if(userId!=null) {
SecureString secureString = new SecureString(userId);
@@ -817,7 +817,7 @@ public class RoleManageController extends EPRestrictedBaseController {
private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
- || (adminRolesService.isSuperAdmin(user) && requestedApp.getId() == PortalConstants.PORTAL_APP_ID)))
+ || (adminRolesService.isSuperAdmin(user) && requestedApp.getId().equals(PortalConstants.PORTAL_APP_ID))))
return true;
return false;
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesController.java
index c976629a..a319c6b3 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesController.java
@@ -79,7 +79,7 @@ public class RolesController implements BasicAuthenticationController {
private ExternalAccessRolesService externalAccessRolesService;
@Autowired
- ExternalAccessRolesController externalAccessRolesController = new ExternalAccessRolesController();
+ ExternalAccessRolesController externalAccessRolesController;
@ApiOperation(value = "Gets roles for an application which is upgraded to newer version.", response = CentralV2Role.class, responseContainer = "Json")
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java
index af34176c..69f25683 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java
@@ -41,7 +41,6 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@@ -49,12 +48,12 @@ import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import lombok.NoArgsConstructor;
import org.json.simple.JSONObject;
import org.onap.portalapp.controller.EPRestrictedBaseController;
import org.onap.portalapp.portal.domain.EPUser;
import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.onap.portalapp.portal.exceptions.RoleFunctionException;
import org.onap.portalapp.portal.logging.aop.EPAuditLog;
import org.onap.portalapp.portal.logging.logic.EPLogUtil;
import org.onap.portalapp.portal.scheduler.SchedulerProperties;
@@ -70,7 +69,6 @@ import org.onap.portalapp.portal.service.AdminRolesService;
import org.onap.portalapp.portal.utils.PortalConstants;
import org.onap.portalapp.util.EPUserUtils;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.onap.portalsdk.core.service.DataAccessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@@ -87,62 +85,66 @@ import org.springframework.web.bind.annotation.RestController;
@Configuration
@EnableAspectJAutoProxy
@EPAuditLog
+@NoArgsConstructor
public class SchedulerController extends EPRestrictedBaseController {
+ private static final String USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL = "User is unauthorized to make this call";
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerController.class);
+ private static final DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z");
- @Autowired
private SchedulerRestInterface schedulerRestController;
-
- @Autowired
private AdminRolesService adminRolesService;
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerController.class);
-
- /** The request date format. */
- public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z");
+ @Autowired
+ public SchedulerController(SchedulerRestInterface schedulerRestController,
+ AdminRolesService adminRolesService) {
+ this.schedulerRestController = schedulerRestController;
+ this.adminRolesService = adminRolesService;
+ }
@RequestMapping(value = "/get_time_slots/{scheduler_request}", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> getTimeSlots(HttpServletRequest request,
- @PathVariable("scheduler_request") String scheduler_request) throws Exception {
+ @PathVariable("scheduler_request") String schedulerRequest) throws Exception {
if (checkIfUserISValidToMakeSchedule(request)) {
try {
Date startingTime = new Date();
String startTimeRequest = requestDateFormat.format(startingTime);
logger.debug(EELFLoggerDelegate.debugLogger,
"Controller Scheduler GET Timeslots for startTimeRequest: ", startTimeRequest);
- logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {} ", scheduler_request);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {} ", schedulerRequest);
String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_GET_TIME_SLOTS)
- + scheduler_request;
+ + schedulerRequest;
- GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(scheduler_request, path, scheduler_request);
+ GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(path, schedulerRequest);
Date endTime = new Date();
String endTimeRequest = requestDateFormat.format(endTime);
logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - GET for EndTimeRequest = {}",
endTimeRequest);
- return (new ResponseEntity<String>(schedulerResWrapper.getResponse(),
- HttpStatus.valueOf(schedulerResWrapper.getStatus())));
+ return (new ResponseEntity<>(schedulerResWrapper.getResponse(),
+ HttpStatus.valueOf(schedulerResWrapper.getStatus())));
} catch (Exception e) {
GetTimeSlotsWrapper schedulerResWrapper = new GetTimeSlotsWrapper();
schedulerResWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
schedulerResWrapper.setEntity(e.getMessage());
logger.error(EELFLoggerDelegate.errorLogger, "Exception with getTimeslots", e);
- return (new ResponseEntity<String>(schedulerResWrapper.getResponse(),
- HttpStatus.INTERNAL_SERVER_ERROR));
+ return (new ResponseEntity<>(schedulerResWrapper.getResponse(),
+ HttpStatus.INTERNAL_SERVER_ERROR));
}
}else{
- return (new ResponseEntity<String>("User is unauthorized to make this call", HttpStatus.UNAUTHORIZED));
+ return (new ResponseEntity<>(USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL, HttpStatus.UNAUTHORIZED));
}
}
- protected GetTimeSlotsWrapper getTimeSlots(String request, String path, String uuid) throws Exception {
+ protected GetTimeSlotsWrapper getTimeSlots(String path, String uuid) throws Exception {
try {
// STARTING REST API CALL AS AN FACTORY INSTACE
logger.debug(EELFLoggerDelegate.debugLogger, "Get Time Slots Request START");
- GetTimeSlotsRestObject<String> restObjStr = new GetTimeSlotsRestObject<String>();
- String str = new String();
+ GetTimeSlotsRestObject<String> restObjStr = new GetTimeSlotsRestObject<>();
+ String str = "";
restObjStr.set(str);
@@ -169,7 +171,7 @@ public class SchedulerController extends EPRestrictedBaseController {
@SuppressWarnings("unchecked")
@RequestMapping(value = "/post_create_new_vnf_change", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<String> postCreateNewVNFChange(HttpServletRequest request,
- @RequestBody JSONObject scheduler_request) throws Exception {
+ @RequestBody JSONObject schedulerRequest) throws Exception {
if (checkIfUserISValidToMakeSchedule(request)) {
try {
Date startingTime = new Date();
@@ -181,34 +183,34 @@ public class SchedulerController extends EPRestrictedBaseController {
// Generating uuid
String uuid = UUID.randomUUID().toString();
- scheduler_request.put("scheduleId", uuid);
+ schedulerRequest.put("scheduleId", uuid);
logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid);
// adding uuid to the request payload
- scheduler_request.put("scheduleId", uuid);
- logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {}", scheduler_request.toString());
+ schedulerRequest.put("scheduleId", uuid);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {}", schedulerRequest.toString());
String path = SchedulerProperties
.getProperty(SchedulerProperties.SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL) + uuid;
- PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(scheduler_request, path, uuid);
+ PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(schedulerRequest, path, uuid);
Date endTime = new Date();
String endTimeRequest = requestDateFormat.format(endTime);
logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - POST= {}", endTimeRequest);
- return new ResponseEntity<String>(responseWrapper.getResponse(),
- HttpStatus.valueOf(responseWrapper.getStatus()));
+ return new ResponseEntity<>(responseWrapper.getResponse(),
+ HttpStatus.valueOf(responseWrapper.getStatus()));
} catch (Exception e) {
PostCreateNewVnfWrapper responseWrapper = new PostCreateNewVnfWrapper();
responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
responseWrapper.setEntity(e.getMessage());
logger.error(EELFLoggerDelegate.errorLogger, "Exception with postCreateNewVNFChange ", e);
- return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
+ return (new ResponseEntity<>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
}
}else{
- return (new ResponseEntity<String>("User is unauthorized to make this call",HttpStatus.UNAUTHORIZED));
+ return (new ResponseEntity<>(USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL, HttpStatus.UNAUTHORIZED));
}
}
@@ -219,11 +221,11 @@ public class SchedulerController extends EPRestrictedBaseController {
try {
// STARTING REST API CALL AS AN FACTORY INSTACE
- PostCreateNewVnfRestObject<String> restObjStr = new PostCreateNewVnfRestObject<String>();
- String str = new String();
+ PostCreateNewVnfRestObject<String> restObjStr = new PostCreateNewVnfRestObject<>();
+ String str = "";
restObjStr.set(str);
- schedulerRestController.<String>Post(str, request, path, restObjStr);
+ schedulerRestController.Post(str, request, path, restObjStr);
int status = restObjStr.getStatusCode();
if (status >= 200 && status <= 299) {
@@ -249,7 +251,7 @@ public class SchedulerController extends EPRestrictedBaseController {
@RequestMapping(value = "/submit_vnf_change_timeslots", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<String> postSubmitVnfChangeTimeslots(HttpServletRequest request,
- @RequestBody JSONObject scheduler_request) throws Exception {
+ @RequestBody JSONObject schedulerRequest) throws Exception {
if (checkIfUserISValidToMakeSchedule(request)) {
try {
Date startingTime = new Date();
@@ -258,17 +260,17 @@ public class SchedulerController extends EPRestrictedBaseController {
startTimeRequest);
// Generating uuid
- String uuid = (String) scheduler_request.get("scheduleId");
+ String uuid = (String) schedulerRequest.get("scheduleId");
logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid);
- scheduler_request.remove("scheduleId");
+ schedulerRequest.remove("scheduleId");
logger.debug(EELFLoggerDelegate.debugLogger, "Original Request for the schedulerId= {} ",
- scheduler_request.toString());
+ schedulerRequest.toString());
String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)
.replace("{scheduleId}", uuid);
- PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = postSubmitSchedulingRequest(scheduler_request, path,
+ PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = postSubmitSchedulingRequest(schedulerRequest, path,
uuid);
Date endTime = new Date();
@@ -276,17 +278,17 @@ public class SchedulerController extends EPRestrictedBaseController {
logger.debug(EELFLoggerDelegate.debugLogger, " Controller Scheduler - POST Submit for end time request= {}",
endTimeRequest);
- return (new ResponseEntity<String>(responseWrapper.getResponse(),HttpStatus.valueOf(responseWrapper.getStatus())));
+ return (new ResponseEntity<>(responseWrapper.getResponse(), HttpStatus.valueOf(responseWrapper.getStatus())));
} catch (Exception e) {
PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = new PostSubmitVnfChangeTimeSlotsWrapper();
responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
responseWrapper.setEntity(e.getMessage());
logger.error(EELFLoggerDelegate.errorLogger, "Exception with Post submit Vnf change Timeslots", e);
- return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
+ return (new ResponseEntity<>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
}
}else{
- return (new ResponseEntity<String>("User is unauthorized to make this call",HttpStatus.UNAUTHORIZED));
+ return (new ResponseEntity<>(USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL, HttpStatus.UNAUTHORIZED));
}
}
@@ -296,11 +298,11 @@ public class SchedulerController extends EPRestrictedBaseController {
try {
// STARTING REST API CALL AS AN FACTORY INSTACE
- PostSubmitVnfChangeRestObject<String> restObjStr = new PostSubmitVnfChangeRestObject<String>();
- String str = new String();
+ PostSubmitVnfChangeRestObject<String> restObjStr = new PostSubmitVnfChangeRestObject<>();
+ String str = "";
restObjStr.set(str);
- schedulerRestController.<String>Post(str, request, path, restObjStr);
+ schedulerRestController.Post(str, request, path, restObjStr);
int status = restObjStr.getStatusCode();
if (status >= 200 && status <= 299) {
@@ -362,19 +364,19 @@ public class SchedulerController extends EPRestrictedBaseController {
throw new Exception(entry.getKey() + errorMsg);
}
logger.debug(EELFLoggerDelegate.debugLogger, " portalRestResponse - getSchedulerConstant= {}", map);
- portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.OK, "success",
- map);
+ portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
+ map);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed", e);
- portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR,
- e.getMessage(), null);
+ portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), null);
}
}
else{
logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed: User unauthorized to make this call");
- portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR, "failed : Unauthorized", null);
+ portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "failed : Unauthorized", null);
}
return portalRestResponse;
}
@@ -397,8 +399,6 @@ public class SchedulerController extends EPRestrictedBaseController {
EPUser user = EPUserUtils.getUserSession(request);
String portalApiPath = getPath(request);
Set<String> functionCodeList = adminRolesService.getAllAppsFunctionsOfUser(user.getId().toString());
- boolean isValidUser = EPUserUtils.matchRoleFunctions(portalApiPath, functionCodeList);
-// boolean isValidUser = functionCodeList.stream().anyMatch(x -> functionCodeList.contains(portalApiPath));
- return isValidUser;
+ return EPUserUtils.matchRoleFunctions(portalApiPath, functionCodeList);
}
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SharedContextRestController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SharedContextRestController.java
index ba77c56f..9e3428e6 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SharedContextRestController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SharedContextRestController.java
@@ -48,10 +48,13 @@ import javax.servlet.http.HttpServletResponse;
import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController;
import org.onap.portalapp.portal.domain.SharedContext;
+import org.onap.portalapp.portal.exceptions.NotValidDataException;
import org.onap.portalapp.portal.logging.aop.EPAuditLog;
import org.onap.portalapp.portal.service.SharedContextService;
import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
import org.onap.portalapp.portal.utils.PortalConstants;
+import org.onap.portalapp.validation.DataValidator;
+import org.onap.portalapp.validation.SecureString;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
@@ -85,33 +88,20 @@ import io.swagger.annotations.ApiOperation;
@EnableAspectJAutoProxy
@EPAuditLog
public class SharedContextRestController extends EPRestrictedRESTfulBaseController {
+ private static final DataValidator dataValidator = new DataValidator();
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class);
+ private static final ObjectMapper mapper = new ObjectMapper();
- /**
- * Model for a one-element JSON object returned by many methods.
- */
- class SharedContextJsonResponse {
- String response;
- }
-
- /**
- * Access to the database
- */
- @Autowired
private SharedContextService contextService;
- /**
- * Logger for debug etc.
- */
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class);
-
- /**
- * Reusable JSON (de)serializer
- */
- private final ObjectMapper mapper = new ObjectMapper();
+ @Autowired
+ public SharedContextRestController(SharedContextService contextService) {
+ this.contextService = contextService;
+ }
/**
* Gets a value for the specified context and key (RESTful service method).
- *
+ *
* @param request
* HTTP servlet request
* @param context_id
@@ -127,13 +117,18 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
@RequestMapping(value = { "/get" }, method = RequestMethod.GET, produces = "application/json")
public String getContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
throws Exception {
-
logger.debug(EELFLoggerDelegate.debugLogger, "getContext for ID " + context_id + ", key " + ckey);
if (context_id == null || ckey == null)
throw new Exception("Received null for context_id and/or ckey");
+ SecureString secureContextId = new SecureString(context_id);
+ SecureString secureCKey = new SecureString(ckey);
+
+ if(!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey)){
+ throw new NotValidDataException("Received not valid for context_id and/or ckey");
+ }
SharedContext context = contextService.getSharedContext(context_id, ckey);
- String jsonResponse = "";
+ String jsonResponse;
if (context == null)
jsonResponse = convertResponseToJSON(context);
else
@@ -144,7 +139,7 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
/**
* Gets user information for the specified context (RESTful service method).
- *
+ *
* @param request
* HTTP servlet request
* @param context_id
@@ -162,8 +157,11 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id);
if (context_id == null)
throw new Exception("Received null for context_id");
+ SecureString secureContextId = new SecureString(context_id);
+ if (!dataValidator.isValid(secureContextId))
+ throw new NotValidDataException("context_id is not valid");
- List<SharedContext> listSharedContext = new ArrayList<SharedContext>();
+ List<SharedContext> listSharedContext = new ArrayList<>();
SharedContext firstNameContext = contextService.getSharedContext(context_id,
EPCommonSystemProperties.USER_FIRST_NAME);
SharedContext lastNameContext = contextService.getSharedContext(context_id,
@@ -179,14 +177,13 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
listSharedContext.add(emailContext);
if (orgUserIdContext != null)
listSharedContext.add(orgUserIdContext);
- String jsonResponse = convertResponseToJSON(listSharedContext);
- return jsonResponse;
+ return convertResponseToJSON(listSharedContext);
}
/**
* Tests for presence of the specified key in the specified context (RESTful
* service method).
- *
+ *
* @param request
* HTTP servlet request
* @param context_id
@@ -208,19 +205,24 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
if (context_id == null || ckey == null)
throw new Exception("Received null for contextId and/or key");
+ SecureString secureContextId = new SecureString(context_id);
+ SecureString secureCKey = new SecureString(ckey);
+
+ if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey))
+ throw new NotValidDataException("Not valid data for contextId and/or key");
+
String response = null;
SharedContext context = contextService.getSharedContext(context_id, ckey);
if (context != null)
response = "exists";
- String jsonResponse = convertResponseToJSON(response);
- return jsonResponse;
+ return convertResponseToJSON(response);
}
/**
* Removes the specified key in the specified context (RESTful service
* method).
- *
+ *
* @param request
* HTTP servlet request
* @param context_id
@@ -242,6 +244,12 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
if (context_id == null || ckey == null)
throw new Exception("Received null for contextId and/or key");
+ SecureString secureContextId = new SecureString(context_id);
+ SecureString secureCKey = new SecureString(ckey);
+
+ if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey))
+ throw new NotValidDataException("Not valid data for contextId and/or key");
+
SharedContext context = contextService.getSharedContext(context_id, ckey);
String response = null;
if (context != null) {
@@ -249,14 +257,13 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
response = "removed";
}
- String jsonResponse = convertResponseToJSON(response);
- return jsonResponse;
+ return convertResponseToJSON(response);
}
/**
* Clears all key-value pairs in the specified context (RESTful service
* method).
- *
+ *
* @param request
* HTTP servlet request
* @param context_id
@@ -275,16 +282,20 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
if (context_id == null)
throw new Exception("clearContext: Received null for contextId");
+ SecureString secureContextId = new SecureString(context_id);
+
+ if (!dataValidator.isValid(secureContextId))
+ throw new NotValidDataException("Not valid data for contextId");
+
int count = contextService.deleteSharedContexts(context_id);
- String jsonResponse = convertResponseToJSON(Integer.toString(count));
- return jsonResponse;
+ return convertResponseToJSON(Integer.toString(count));
}
/**
* Sets a context value for the specified context and key (RESTful service
* method). Creates the context if no context with the specified ID-key pair
* exists, overwrites the value if it exists already.
- *
+ *
* @param request
* HTTP servlet request
* @param userJson
@@ -302,6 +313,11 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
@ApiOperation(value = "Sets a context value for the specified context and key. Creates the context if no context with the specified ID-key pair exists, overwrites the value if it exists already.", response = SharedContextJsonResponse.class)
@RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json")
public String setContext(HttpServletRequest request, @RequestBody String userJson) throws Exception {
+ if (userJson !=null){
+ SecureString secureUserJson = new SecureString(userJson);
+ if (!dataValidator.isValid(secureUserJson))
+ throw new NotValidDataException("Not valid data for userJson");
+ }
@SuppressWarnings("unchecked")
Map<String, Object> userData = mapper.readValue(userJson, Map.class);
@@ -313,7 +329,7 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
throw new Exception("setContext: received null for contextId and/or key");
logger.debug(EELFLoggerDelegate.debugLogger, "setContext: ID " + contextId + ", key " + key + "->" + value);
- String response = null;
+ String response;
SharedContext existing = contextService.getSharedContext(contextId, key);
if (existing == null) {
contextService.addSharedContext(contextId, key, value);
@@ -322,53 +338,49 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
contextService.saveSharedContext(existing);
}
response = existing == null ? "added" : "replaced";
- String jsonResponse = convertResponseToJSON(response);
- return jsonResponse;
+ return convertResponseToJSON(response);
}
/**
* Creates a two-element JSON object tagged "response".
- *
+ *
* @param responseBody
* @return JSON object as String
* @throws JsonProcessingException
*/
private String convertResponseToJSON(String responseBody) throws JsonProcessingException {
- Map<String, String> responseMap = new HashMap<String, String>();
+ Map<String, String> responseMap = new HashMap<>();
responseMap.put("response", responseBody);
- String response = mapper.writeValueAsString(responseMap);
- return response;
+ return mapper.writeValueAsString(responseMap);
}
/**
* Converts a list of SharedContext objects to a JSON array.
- *
+ *
* @param contextList
* @return JSON array as String
* @throws JsonProcessingException
*/
private String convertResponseToJSON(List<SharedContext> contextList) throws JsonProcessingException {
- String jsonArray = mapper.writeValueAsString(contextList);
- return jsonArray;
+ return mapper.writeValueAsString(contextList);
}
/**
* Creates a JSON object with the content of the shared context; null is ok.
- *
+ *
* @param context
* @return tag "response" with collection of context object's fields
* @throws JsonProcessingException
*/
private String convertResponseToJSON(SharedContext context) throws JsonProcessingException {
- Map<String, Object> responseMap = new HashMap<String, Object>();
+ Map<String, Object> responseMap = new HashMap<>();
responseMap.put("response", context);
- String responseBody = mapper.writeValueAsString(responseMap);
- return responseBody;
+ return mapper.writeValueAsString(responseMap);
}
/**
* Handles any exception thrown by a method in this controller.
- *
+ *
* @param e
* Exception
* @param response
@@ -382,3 +394,7 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
}
}
+class SharedContextJsonResponse {
+ String response;
+}
+
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WidgetsController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WidgetsController.java
index f2bba8b8..45035a25 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WidgetsController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WidgetsController.java
@@ -52,10 +52,13 @@ import org.onap.portalapp.portal.service.PersUserWidgetService;
import org.onap.portalapp.portal.service.WidgetService;
import org.onap.portalapp.portal.transport.FieldsValidator;
import org.onap.portalapp.portal.transport.OnboardingWidget;
+import org.onap.portalapp.portal.transport.WidgetCatalogPersonalization;
import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.util.EPUserUtils;
+import org.onap.portalapp.validation.DataValidator;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
@@ -64,30 +67,36 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
-@org.springframework.context.annotation.Configuration
+@Configuration
@EnableAspectJAutoProxy
@EPAuditLog
public class WidgetsController extends EPRestrictedBaseController {
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsController.class);
-
- @Autowired
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsController.class);
+ private static final DataValidator dataValidator = new DataValidator();
+
private AdminRolesService adminRolesService;
- @Autowired
private WidgetService widgetService;
- @Autowired
private PersUserWidgetService persUserWidgetService;
+ @Autowired
+ public WidgetsController(AdminRolesService adminRolesService,
+ WidgetService widgetService, PersUserWidgetService persUserWidgetService) {
+ this.adminRolesService = adminRolesService;
+ this.widgetService = widgetService;
+ this.persUserWidgetService = persUserWidgetService;
+ }
+
@RequestMapping(value = { "/portalApi/widgets" }, method = RequestMethod.GET, produces = "application/json")
public List<OnboardingWidget> getOnboardingWidgets(HttpServletRequest request, HttpServletResponse response) {
EPUser user = EPUserUtils.getUserSession(request);
List<OnboardingWidget> onboardingWidgets = null;
-
+
if (user == null || user.isGuest()) {
EcompPortalUtils.setBadPermissions(user, response, "getOnboardingWidgets");
} else {
String getType = request.getHeader("X-Widgets-Type");
- if (!StringUtils.isEmpty(getType) && (getType.equals("managed") || getType.equals("all"))) {
- onboardingWidgets = widgetService.getOnboardingWidgets(user, getType.equals("managed"));
+ if (!StringUtils.isEmpty(getType) && ("managed".equals(getType) || "all".equals(getType))) {
+ onboardingWidgets = widgetService.getOnboardingWidgets(user, "managed".equals(getType));
} else {
logger.debug(EELFLoggerDelegate.debugLogger, "WidgetsController.getOnboardingApps - request must contain header 'X-Widgets-Type' with 'all' or 'managed'");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
@@ -112,6 +121,14 @@ public class WidgetsController extends EPRestrictedBaseController {
@RequestBody OnboardingWidget onboardingWidget, HttpServletResponse response) {
EPUser user = EPUserUtils.getUserSession(request);
FieldsValidator fieldsValidator = null;
+ if (onboardingWidget!=null){
+ if(!dataValidator.isValid(onboardingWidget)){
+ fieldsValidator = new FieldsValidator();
+ fieldsValidator.setHttpStatusCode((long)HttpServletResponse.SC_NOT_ACCEPTABLE);
+ return fieldsValidator;
+ }
+ }
+
if (userHasPermissions(user, response, "putOnboardingWidget")) {
onboardingWidget.id = widgetId; // !
onboardingWidget.normalize();
@@ -119,7 +136,7 @@ public class WidgetsController extends EPRestrictedBaseController {
response.setStatus(fieldsValidator.httpStatusCode.intValue());
}
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/widgets/" + widgetId, "GET result =", response.getStatus());
-
+
return fieldsValidator;
}
@@ -127,15 +144,23 @@ public class WidgetsController extends EPRestrictedBaseController {
@RequestMapping(value = { "/portalApi/widgets" }, method = { RequestMethod.POST }, produces = "application/json")
public FieldsValidator postOnboardingWidget(HttpServletRequest request, @RequestBody OnboardingWidget onboardingWidget, HttpServletResponse response) {
EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null; ;
-
+ FieldsValidator fieldsValidator = null;
+
+ if (onboardingWidget!=null){
+ if(!dataValidator.isValid(onboardingWidget)){
+ fieldsValidator = new FieldsValidator();
+ fieldsValidator.setHttpStatusCode((long)HttpServletResponse.SC_NOT_ACCEPTABLE);
+ return fieldsValidator;
+ }
+ }
+
if (userHasPermissions(user, response, "postOnboardingWidget")) {
onboardingWidget.id = null; // !
onboardingWidget.normalize();
fieldsValidator = widgetService.setOnboardingWidget(user, onboardingWidget);
response.setStatus(fieldsValidator.httpStatusCode.intValue());
}
-
+
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/widgets", "POST result =", response.getStatus());
return fieldsValidator;
}
@@ -143,17 +168,17 @@ public class WidgetsController extends EPRestrictedBaseController {
@RequestMapping(value = { "/portalApi/widgets/{widgetId}" }, method = { RequestMethod.DELETE }, produces = "application/json")
public FieldsValidator deleteOnboardingWidget(HttpServletRequest request, @PathVariable("widgetId") Long widgetId, HttpServletResponse response) {
EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null; ;
-
+ FieldsValidator fieldsValidator = null;
+
if (userHasPermissions(user, response, "deleteOnboardingWidget")) {
fieldsValidator = widgetService.deleteOnboardingWidget(user, widgetId);
response.setStatus(fieldsValidator.httpStatusCode.intValue());
}
-
+
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/widgets/" + widgetId, "DELETE result =", response.getStatus());
return fieldsValidator;
}
-
+
/**
* service to accept a user's action made on the application
* catalog.
@@ -167,9 +192,18 @@ public class WidgetsController extends EPRestrictedBaseController {
*/
@RequestMapping(value = { "portalApi/widgetCatalogSelection" }, method = RequestMethod.PUT, produces = "application/json")
public FieldsValidator putWidgetCatalogSelection(HttpServletRequest request,
- @RequestBody org.onap.portalapp.portal.transport.WidgetCatalogPersonalization persRequest, HttpServletResponse response) throws IOException {
+ @RequestBody WidgetCatalogPersonalization persRequest, HttpServletResponse response) throws IOException {
FieldsValidator result = new FieldsValidator();
EPUser user = EPUserUtils.getUserSession(request);
+
+ if (persRequest!=null){
+ if(!dataValidator.isValid(persRequest)){
+ result.httpStatusCode = (long)HttpServletResponse.SC_NOT_ACCEPTABLE;
+ return result;
+ }
+ }
+
+
try {
if (persRequest.getWidgetId() == null || user == null) {
EcompPortalUtils.setBadPermissions(user, response, "putWidgetCatalogSelection");
@@ -180,7 +214,7 @@ public class WidgetsController extends EPRestrictedBaseController {
logger.error(EELFLoggerDelegate.errorLogger, "Failed in putAppCatalogSelection", e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
}
- result.httpStatusCode = new Long(HttpServletResponse.SC_OK);
+ result.httpStatusCode = (long) HttpServletResponse.SC_OK;
return result;
}
} \ No newline at end of file
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ecomp/model/AppContactUsItem.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ecomp/model/AppContactUsItem.java
index c7c8ebcc..2d52626f 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ecomp/model/AppContactUsItem.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ecomp/model/AppContactUsItem.java
@@ -40,6 +40,7 @@ package org.onap.portalapp.portal.ecomp.model;
import javax.persistence.Entity;
import javax.persistence.Id;
+import org.hibernate.validator.constraints.SafeHtml;
import org.onap.portalsdk.core.domain.support.DomainVo;
import com.fasterxml.jackson.annotation.JsonInclude;
@@ -55,11 +56,17 @@ public class AppContactUsItem extends DomainVo {
@Id
private Long appId;
+ @SafeHtml
private String appName;
+ @SafeHtml
private String description;
+ @SafeHtml
private String contactName;
+ @SafeHtml
private String contactEmail;
+ @SafeHtml
private String url;
+ @SafeHtml
private String activeYN;
public Long getAppId() {
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NotValidDataException.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NotValidDataException.java
new file mode 100644
index 00000000..2a26ab31
--- /dev/null
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NotValidDataException.java
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ *
+ */
+
+package org.onap.portalapp.portal.exceptions;
+
+public class NotValidDataException extends Exception {
+
+ public NotValidDataException(String msg) {
+ super(msg);
+ }
+
+ @Override
+ public String toString() {
+ return "NotValidDataException{}: " + this.getMessage();
+ }
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java
index 18aac6f4..6950bdda 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java
@@ -40,25 +40,19 @@
package org.onap.portalapp.portal.service;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
import java.util.stream.Collectors;
-
import javax.annotation.PostConstruct;
-
import org.apache.cxf.common.util.StringUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.json.JSONArray;
import org.json.JSONObject;
-import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
import org.onap.portalapp.portal.domain.EPApp;
import org.onap.portalapp.portal.domain.EPRole;
import org.onap.portalapp.portal.domain.EPUser;
@@ -71,16 +65,12 @@ import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
import org.onap.portalapp.portal.logging.logic.EPLogUtil;
import org.onap.portalapp.portal.transport.AppNameIdIsAdmin;
import org.onap.portalapp.portal.transport.AppsListWithAdminRole;
-import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
import org.onap.portalapp.portal.transport.ExternalAccessUser;
import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.portal.utils.PortalConstants;
import org.onap.portalapp.util.EPUserUtils;
-import org.onap.portalsdk.core.domain.RoleFunction;
-import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.onap.portalsdk.core.restful.domain.EcompRole;
import org.onap.portalsdk.core.service.DataAccessService;
import org.onap.portalsdk.core.util.SystemProperties;
import org.springframework.beans.factory.annotation.Autowired;
@@ -92,7 +82,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
-
import com.fasterxml.jackson.databind.ObjectMapper;
@Service("adminRolesService")
@@ -106,6 +95,7 @@ public class AdminRolesServiceImpl implements AdminRolesService {
private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
private Long ECOMP_APP_ID = 1L;
public static final String TYPE_APPROVER = "approver";
+ private static final String ADMIN_ACCOUNT= "Is account admin for user {}";
private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesServiceImpl.class);
@@ -458,7 +448,7 @@ public class AdminRolesServiceImpl implements AdminRolesService {
final Map<String, Long> userParams = new HashMap<>();
userParams.put("userId", user.getId());
- logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user {}", user.getId());
+ logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId());
List<Integer> userAdminApps = new ArrayList<>();
userAdminApps =dataAccessService.executeNamedQuery("getAdminAppsForTheUser", userParams, null);
@@ -498,7 +488,7 @@ public class AdminRolesServiceImpl implements AdminRolesService {
Set<String> getRoleFuncListOfPortalSet1=new HashSet<>();
Set<String> roleFunSet = new HashSet<>();
roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")).collect(Collectors.toSet());
- if (roleFunSet.size() > 0)
+ if (!roleFunSet.isEmpty())
for (String roleFunction : roleFunSet) {
String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
getRoleFuncListOfPortalSet1.add(type);
@@ -561,10 +551,10 @@ public class AdminRolesServiceImpl implements AdminRolesService {
try {
final Map<String, Long> userParams = new HashMap<>();
userParams.put("userId", user.getId());
- logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user {}", user.getId());
+ logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId());
List<Integer> userAdminApps = new ArrayList<>();
userAdminApps =dataAccessService.executeNamedQuery("getAdminAppsForTheUser", userParams, null);
- if(userAdminApps.size()>=1){
+ if(!userAdminApps.isEmpty()){
isApplicationAccountAdmin=userAdminApps.contains((int) (long) app.getId());
logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", user.getId(),app.getId());
}
@@ -586,7 +576,7 @@ public class AdminRolesServiceImpl implements AdminRolesService {
Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal);
Set<String> roleFunSet = new HashSet<>();
roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")).collect(Collectors.toSet());
- if (roleFunSet.size() > 0)
+ if (!roleFunSet.isEmpty())
for (String roleFunction : roleFunSet) {
String roleFun = EcompPortalUtils.getFunctionCode(roleFunction);
getRoleFuncListOfPortalSet.remove(roleFunction);
@@ -598,7 +588,6 @@ public class AdminRolesServiceImpl implements AdminRolesService {
finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn));
}
-// List<String> functionsOfUser = new ArrayList<>(getRoleFuncListOfPortal);
return finalRoleFunctionSet;
}
@@ -609,10 +598,10 @@ public class AdminRolesServiceImpl implements AdminRolesService {
try {
final Map<String, Long> userParams = new HashMap<>();
userParams.put("userId", user.getId());
- logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user {}", user.getId());
+ logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId());
List<Integer> userAdminApps = new ArrayList<>();
userAdminApps =dataAccessService.executeNamedQuery("getAllAdminAppsofTheUser", userParams, null);
- if(userAdminApps.size()>=1){
+ if(!userAdminApps.isEmpty()){
isApplicationAccountAdmin=userAdminApps.contains((int) (long) app.getId());
logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", user.getId(),app.getId());
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/Analytics.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/Analytics.java
index 2d85e8f2..f5ca1832 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/Analytics.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/Analytics.java
@@ -38,14 +38,19 @@
package org.onap.portalapp.portal.transport;
import com.fasterxml.jackson.annotation.JsonInclude;
+import org.hibernate.validator.constraints.SafeHtml;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Analytics {
-
+ @SafeHtml
private String action;
+ @SafeHtml
private String page;
+ @SafeHtml
private String function;
+ @SafeHtml
private String userid;
+ @SafeHtml
private String type;
public String getType() {
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java
index 90277877..e9d720e3 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java
@@ -49,6 +49,7 @@ import javax.validation.constraints.Size;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
+import lombok.ToString;
import org.hibernate.validator.constraints.SafeHtml;
import org.onap.portalsdk.core.domain.support.DomainVo;
import com.fasterxml.jackson.annotation.JsonInclude;
@@ -62,6 +63,7 @@ import com.fasterxml.jackson.annotation.JsonInclude;
@NoArgsConstructor
@Getter
@Setter
+@ToString
public class CommonWidget extends DomainVo{
private static final long serialVersionUID = 7897021982887364557L;
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java
index 51a02652..0a999495 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java
@@ -39,33 +39,21 @@ package org.onap.portalapp.portal.transport;
import java.util.List;
import javax.validation.Valid;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import lombok.ToString;
import org.hibernate.validator.constraints.SafeHtml;
+@NoArgsConstructor
+@AllArgsConstructor
+@Getter
+@Setter
+@ToString
public class CommonWidgetMeta {
@SafeHtml
private String category;
@Valid
private List<CommonWidget> items;
-
- public CommonWidgetMeta(){
-
- }
-
- public CommonWidgetMeta(String category, List<CommonWidget> items){
- this.category = category;
- this.items = items;
- }
-
- public String getCategory() {
- return category;
- }
- public void setCategory(String category) {
- this.category = category;
- }
- public List<CommonWidget> getItems() {
- return items;
- }
- public void setItems(List<CommonWidget> items) {
- this.items = items;
- }
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPAppsManualPreference.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPAppsManualPreference.java
index 0bd4db3a..1aa42193 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPAppsManualPreference.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPAppsManualPreference.java
@@ -37,18 +37,24 @@
*/
package org.onap.portalapp.portal.transport;
+import org.hibernate.validator.constraints.SafeHtml;
+
public class EPAppsManualPreference {
private Long appid;
private int col;
+ @SafeHtml
private String headerText;
+ @SafeHtml
private String imageLink;
private int order;
private boolean restrictedApp;
private int row;
private int sizeX;
private int sizeY;
+ @SafeHtml
private String subHeaderText;
+ @SafeHtml
private String url;
private boolean addRemoveApps;
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPAppsSortPreference.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPAppsSortPreference.java
index 85a6a03b..796f67fb 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPAppsSortPreference.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPAppsSortPreference.java
@@ -37,10 +37,14 @@
*/
package org.onap.portalapp.portal.transport;
+import org.hibernate.validator.constraints.SafeHtml;
+
public class EPAppsSortPreference {
private int index;
+ @SafeHtml
private String value;
+ @SafeHtml
private String title;
public int getIndex() {
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPWidgetsSortPreference.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPWidgetsSortPreference.java
index 03b7c141..e1f5c292 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPWidgetsSortPreference.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EPWidgetsSortPreference.java
@@ -38,15 +38,19 @@
package org.onap.portalapp.portal.transport;
import java.util.List;
+import org.hibernate.validator.constraints.SafeHtml;
public class EPWidgetsSortPreference {
private int SizeX;
private int SizeY;
+ @SafeHtml
private String headerText;
+ @SafeHtml
private String url;
private Long widgetid;
private List<Object> attrb;
+ @SafeHtml
private String widgetIdentifier;
private int row;
private int col;
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingWidget.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingWidget.java
index 4f0a7d60..40460796 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingWidget.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingWidget.java
@@ -42,6 +42,7 @@ import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
+import org.hibernate.validator.constraints.SafeHtml;
@Entity
public class OnboardingWidget implements Serializable {
@@ -53,12 +54,14 @@ public class OnboardingWidget implements Serializable {
public Long id;
@Column(name = "WDG_NAME")
+ @SafeHtml
public String name;
@Column(name = "APP_ID")
public Long appId;
@Column(name = "APP_NAME")
+ @SafeHtml
public String appName;
@Column(name = "WDG_WIDTH")
@@ -68,15 +71,16 @@ public class OnboardingWidget implements Serializable {
public Integer height;
@Column(name = "WDG_URL")
+ @SafeHtml
public String url;
public void normalize() {
this.name = (this.name == null) ? "" : this.name.trim();
this.appName = (this.appName == null) ? "" : this.appName.trim();
if (this.width == null)
- this.width = new Integer(0);
+ this.width = 0;
if (this.height == null)
- this.height = new Integer(0);
+ this.height = 0;
this.url = (this.url == null) ? "" : this.url.trim();
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/DataValidator.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/DataValidator.java
index 46a60c81..9fe3a887 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/DataValidator.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/DataValidator.java
@@ -47,15 +47,25 @@ import org.springframework.stereotype.Component;
@Component
public class DataValidator {
- private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
+ private volatile static ValidatorFactory VALIDATOR_FACTORY;
- public <E> Set<ConstraintViolation<E>> getConstraintViolations(E classToValid){
+ public DataValidator() {
+ if (VALIDATOR_FACTORY == null) {
+ synchronized (DataValidator.class) {
+ if (VALIDATOR_FACTORY == null) {
+ VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
+ }
+ }
+ }
+ }
+
+ public <E> Set<ConstraintViolation<E>> getConstraintViolations(E classToValid) {
Validator validator = VALIDATOR_FACTORY.getValidator();
Set<ConstraintViolation<E>> constraintViolations = validator.validate(classToValid);
return constraintViolations;
}
- public <E> boolean isValid(E classToValid){
+ public <E> boolean isValid(E classToValid) {
Set<ConstraintViolation<E>> constraintViolations = getConstraintViolations(classToValid);
return constraintViolations.isEmpty();
}
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java
index b08a8769..f2b2d3da 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java
@@ -78,7 +78,7 @@ public class AppContactUsControllerTest extends MockitoTestSuite{
AppContactUsService contactUsService = new AppContactUsServiceImpl();
@InjectMocks
- AppContactUsController appContactUsController = new AppContactUsController();
+ AppContactUsController appContactUsController;
@Before
public void setup() {
@@ -233,6 +233,25 @@ public class AppContactUsControllerTest extends MockitoTestSuite{
}
@Test
+ public void saveXSSTest() throws Exception {
+ PortalRestResponse<String> actualSaveAppContactUS = null;
+
+ AppContactUsItem contactUs = new AppContactUsItem();
+ contactUs.setAppId((long) 1);
+ contactUs.setAppName("<meta content=\"&NewLine; 1 &NewLine;; JAVASCRIPT&colon; alert(1)\" http-equiv=\"refresh\"/>");
+ contactUs.setDescription("Test");
+ contactUs.setContactName("Test");
+ contactUs.setContactEmail("person@onap.org");
+ contactUs.setUrl("Test_URL");
+ contactUs.setActiveYN("Y");
+
+ Mockito.when(contactUsService.saveAppContactUs(contactUs)).thenReturn("FAILURE");
+ actualSaveAppContactUS = appContactUsController.save(contactUs);
+ assertEquals("AppName is not valid.", actualSaveAppContactUS.getResponse());
+ assertEquals("failure", actualSaveAppContactUS.getMessage());
+ }
+
+ @Test
public void saveExceptionTest() throws Exception {
PortalRestResponse<String> actualSaveAppContactUS = null;
@@ -270,6 +289,19 @@ public class AppContactUsControllerTest extends MockitoTestSuite{
}
@Test
+ public void saveAllXSSTest() throws Exception {
+
+ List<AppContactUsItem> contactUs = mockResponse();
+ AppContactUsItem appContactUsItem = new AppContactUsItem();
+ appContactUsItem.setActiveYN("<script/&Tab; src='https://dl.dropbox.com/u/13018058/js.js' /&Tab;></script>");
+ contactUs.add(appContactUsItem);
+ PortalRestResponse<String> actualSaveAppContactUS = null;
+ Mockito.when(contactUsService.saveAppContactUs(contactUs)).thenReturn("failure");
+ actualSaveAppContactUS = appContactUsController.save(contactUs);
+ assertEquals("failure", actualSaveAppContactUS.getMessage());
+ }
+
+ @Test
public void saveAllExceptionTest() throws Exception {
List<AppContactUsItem> contactUs = mockResponse();
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java
index 4df1c2ac..58745d22 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java
@@ -58,7 +58,6 @@ import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.onap.portalapp.portal.controller.AppsController;
import org.onap.portalapp.portal.core.MockEPUser;
import org.onap.portalapp.portal.domain.AdminUserApplications;
import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel;
@@ -82,7 +81,6 @@ import org.onap.portalapp.portal.transport.EPWidgetsSortPreference;
import org.onap.portalapp.portal.transport.FieldsValidator;
import org.onap.portalapp.portal.transport.LocalRole;
import org.onap.portalapp.portal.transport.OnboardingApp;
-import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.util.EPUserUtils;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.portalsdk.core.web.support.AppUtils;
@@ -100,7 +98,7 @@ import org.springframework.web.client.HttpClientErrorException;
public class AppsControllerTest extends MockitoTestSuite{
@InjectMocks
- AppsController appsController = new AppsController();
+ AppsController appsController;
@Mock
AdminRolesService adminRolesService = new AdminRolesServiceImpl();
@@ -369,6 +367,38 @@ public class AppsControllerTest extends MockitoTestSuite{
}
@Test
+ public void putUserAppsSortingManualXSSTest() {
+ EPUser user = mockUser.mockEPUser();
+ EPAppsManualPreference preference = new EPAppsManualPreference();
+ preference.setHeaderText("<script>alert(\"hellox worldss\");</script>");
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ List<EPAppsManualPreference> ePAppsManualPreference = new ArrayList<>();
+ FieldsValidator expectedFieldValidator = new FieldsValidator();
+ expectedFieldValidator.setHttpStatusCode((long)HttpServletResponse.SC_NOT_ACCEPTABLE);
+ ePAppsManualPreference.add(preference);
+ Mockito.when(appService.saveAppsSortManual(ePAppsManualPreference, user)).thenReturn(expectedFieldValidator);
+ FieldsValidator actualFieldValidator = appsController.putUserAppsSortingManual(mockedRequest, ePAppsManualPreference,
+ mockedResponse);
+ assertEquals(actualFieldValidator, expectedFieldValidator);
+ }
+
+ @Test
+ public void putUserWidgetsSortManualXSSTest() {
+ EPUser user = mockUser.mockEPUser();
+ EPWidgetsSortPreference preference = new EPWidgetsSortPreference();
+ preference.setHeaderText("<script>alert(\"hellox worldss\");</script>");
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ List<EPWidgetsSortPreference> ePAppsManualPreference = new ArrayList<>();
+ FieldsValidator expectedFieldValidator = new FieldsValidator();
+ expectedFieldValidator.setHttpStatusCode((long)HttpServletResponse.SC_NOT_ACCEPTABLE);
+ ePAppsManualPreference.add(preference);
+ Mockito.when(appService.saveWidgetsSortManual(ePAppsManualPreference, user)).thenReturn(expectedFieldValidator);
+ FieldsValidator actualFieldValidator = appsController.putUserWidgetsSortManual(mockedRequest, ePAppsManualPreference,
+ mockedResponse);
+ assertEquals(expectedFieldValidator, actualFieldValidator);
+ }
+
+ @Test
public void putUserAppsSortingManualExceptionTest() throws IOException {
EPUser user = mockUser.mockEPUser();
Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
@@ -404,7 +434,7 @@ public class AppsControllerTest extends MockitoTestSuite{
}
@Test
- public void putUserWidgetsSortPrefTest() throws IOException {
+ public void putUserWidgetsSortPrefTest() {
EPUser user = mockUser.mockEPUser();
Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
List<EPWidgetsSortPreference> ePWidgetsSortPreference = new ArrayList<EPWidgetsSortPreference>();
@@ -421,6 +451,24 @@ public class AppsControllerTest extends MockitoTestSuite{
}
@Test
+ public void putUserWidgetsSortPrefXSSTest() {
+ EPUser user = mockUser.mockEPUser();
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ List<EPWidgetsSortPreference> ePWidgetsSortPreference = new ArrayList<>();
+ EPWidgetsSortPreference preference = new EPWidgetsSortPreference();
+ preference.setHeaderText("<script>alert(\"hellox worldss\");</script>");
+ ePWidgetsSortPreference.add(preference);
+ FieldsValidator expectedFieldValidator = new FieldsValidator();
+ expectedFieldValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE);
+ FieldsValidator actualFieldValidator;
+ Mockito.when(appService.deleteUserWidgetSortPref(ePWidgetsSortPreference, user))
+ .thenReturn(expectedFieldValidator);
+ actualFieldValidator = appsController.putUserWidgetsSortPref(mockedRequest, ePWidgetsSortPreference,
+ mockedResponse);
+ assertEquals(actualFieldValidator, expectedFieldValidator);
+ }
+
+ @Test
public void putUserWidgetsSortPrefExceptionTest() throws IOException {
EPUser user = mockUser.mockEPUser();
Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
@@ -476,6 +524,23 @@ public class AppsControllerTest extends MockitoTestSuite{
}
@Test
+ public void putUserAppsSortingPreferenceXSSTest() {
+ EPUser user = mockUser.mockEPUser();
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ EPAppsSortPreference userAppsValue = new EPAppsSortPreference();
+ userAppsValue.setTitle("</script><script>alert(1)</script>");
+ FieldsValidator expectedFieldValidator = new FieldsValidator();
+ expectedFieldValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE);
+ expectedFieldValidator.setFields(null);
+ expectedFieldValidator.setErrorCode(null);
+ FieldsValidator actualFieldValidator;
+ Mockito.when(appService.saveAppsSortPreference(userAppsValue, user)).thenReturn(expectedFieldValidator);
+ actualFieldValidator = appsController.putUserAppsSortingPreference(mockedRequest, userAppsValue,
+ mockedResponse);
+ assertEquals(actualFieldValidator, expectedFieldValidator);
+ }
+
+ @Test
public void putUserAppsSortingPreferenceExceptionTest() throws IOException {
EPUser user = mockUser.mockEPUser();
Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuditLogControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuditLogControllerTest.java
index d8ed8c84..dfee854e 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuditLogControllerTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuditLogControllerTest.java
@@ -66,7 +66,7 @@ public class AuditLogControllerTest {
AuditService auditService;
@InjectMocks
- AuditLogController auditLogController = new AuditLogController();
+ AuditLogController auditLogController;
@Before
public void setup() {
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java
index e7303313..8ef2d32a 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java
@@ -45,10 +45,8 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -68,6 +66,7 @@ import org.onap.portalapp.portal.transport.Analytics;
import org.onap.portalapp.portal.transport.EpNotificationItem;
import org.onap.portalapp.portal.transport.OnboardingApp;
import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@@ -114,6 +113,21 @@ public class AuxApiRequestMapperControllerTest {
Mockito.when(mockedRequest.getMethod()).thenReturn("GET");
assertNull(auxApiRequestMapperController.getUser(mockedRequest, mockedResponse, "test12"));
}
+
+ @Test
+ public void getUserXSSTest() throws Exception {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/roles");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", rolesController);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("GET");
+ String expected = "Provided data is not valid";
+ String actual = auxApiRequestMapperController.getUser(mockedRequest, mockedResponse, "“><script>alert(“XSS”)</script>");
+ assertEquals(expected, actual);
+ }
@Test
public void getUserTestWithException() throws Exception {
@@ -233,6 +247,7 @@ public class AuxApiRequestMapperControllerTest {
assertNull(auxApiRequestMapperController.getRoleFunction(mockedRequest, mockedResponse, "test"));
}
+
@Test
public void saveRoleFunctionTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/roleFunction");
@@ -248,6 +263,21 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void saveRoleFunctionXSSTest() throws Exception {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/roleFunction");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", rolesController);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
+ PortalRestResponse<String> actual = auxApiRequestMapperController.saveRoleFunction(mockedRequest, mockedResponse, "<script>alert(123)</script>");
+ PortalRestResponse<String> expected = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Provided data is not valid", "Failed");
+ assertEquals(expected, actual);
+ }
+
+ @Test
public void deleteRoleFunctionTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/roleFunction/test");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -261,6 +291,22 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void deleteRoleFunctionXSSTest() throws Exception {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/roleFunction/test");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", rolesController);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("DELETE");
+ PortalRestResponse<String> actual = auxApiRequestMapperController.deleteRoleFunction(mockedRequest, mockedResponse,
+ "<svg><script x:href='https://dl.dropbox.com/u/13018058/js.js' {Opera}");
+ PortalRestResponse<String> expected = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Provided data is not valid", "Failed");
+ assertEquals(expected, actual);
+ }
+
+ @Test
public void deleteRoleTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/deleteRole/1");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -300,6 +346,19 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void getEcompUserXSSTest() throws Exception {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v4/user/test");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", rolesController);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("GET");
+ assertNull(auxApiRequestMapperController.getEcompUser(mockedRequest, mockedResponse, "<script>alert(‘XSS’)</script>"));
+ }
+
+ @Test
public void getEcompRolesOfApplicationTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v4/roles");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -340,6 +399,20 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void extendSessionTimeOutsXSSTest() throws Exception {
+ String sessionMap = "<script>alert(“XSS”)</script>";
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/extendSessionTimeOuts");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", sessionCommunicationController);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
+ assertNull(auxApiRequestMapperController.extendSessionTimeOuts(mockedRequest, mockedResponse, sessionMap));
+ }
+
+ @Test
public void getAnalyticsScriptTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/analytics");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -367,6 +440,23 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void storeAnalyticsScriptXSSTest() throws Exception {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/storeAnalytics");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", webAnalyticsExtAppController);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
+ Analytics analyticsMap = new Analytics();
+ analyticsMap.setPage("<script>alert(“XSS”);</script>");
+ PortalAPIResponse actual = auxApiRequestMapperController.storeAnalyticsScript(mockedRequest, mockedResponse, analyticsMap);
+ PortalAPIResponse expected = new PortalAPIResponse(true, "analyticsScript is not valid");
+ assertEquals(expected.getMessage(), actual.getMessage());
+ }
+
+ @Test
public void bulkUploadFunctionsTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/upload/portal/functions");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -376,11 +466,11 @@ public class AuxApiRequestMapperControllerTest {
PowerMockito.mockStatic(AopUtils.class);
Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
- PortalRestResponse res = new PortalRestResponse();
- res.setStatus(PortalRestStatusEnum.ERROR);
- res.setMessage("Failed to bulkUploadFunctions");
- res.setResponse("Failed");
- assertEquals(res, auxApiRequestMapperController.bulkUploadFunctions(mockedRequest, mockedResponse));
+ PortalRestResponse expected = new PortalRestResponse();
+ expected.setStatus(PortalRestStatusEnum.ERROR);
+ expected.setMessage("Failed to bulkUploadFunctions");
+ expected.setResponse("Failed");
+ assertEquals(expected, auxApiRequestMapperController.bulkUploadFunctions(mockedRequest, mockedResponse));
}
@Test
@@ -393,11 +483,13 @@ public class AuxApiRequestMapperControllerTest {
PowerMockito.mockStatic(AopUtils.class);
Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
- PortalRestResponse res = new PortalRestResponse();
- res.setStatus(PortalRestStatusEnum.ERROR);
- res.setMessage("Failed to bulkUploadRoles");
- res.setResponse("Failed");
- assertEquals(res, auxApiRequestMapperController.bulkUploadRoles(mockedRequest, mockedResponse));
+ PortalRestResponse expected = new PortalRestResponse();
+ expected.setStatus(PortalRestStatusEnum.ERROR);
+ expected.setMessage("Failed to bulkUploadRoles");
+ expected.setResponse("Failed");
+ PortalRestResponse actual = auxApiRequestMapperController.bulkUploadRoles(mockedRequest, mockedResponse);
+ System.out.println(actual.toString());
+ assertEquals(expected, actual);
}
@Test
@@ -410,11 +502,11 @@ public class AuxApiRequestMapperControllerTest {
PowerMockito.mockStatic(AopUtils.class);
Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
- PortalRestResponse res = new PortalRestResponse();
- res.setStatus(PortalRestStatusEnum.ERROR);
- res.setMessage("Failed to bulkUploadRoleFunctions");
- res.setResponse("Failed");
- assertEquals(res, auxApiRequestMapperController.bulkUploadRoleFunctions(mockedRequest, mockedResponse));
+ PortalRestResponse expected = new PortalRestResponse();
+ expected.setStatus(PortalRestStatusEnum.ERROR);
+ expected.setMessage("Failed to bulkUploadRoleFunctions");
+ expected.setResponse("Failed");
+ assertEquals(expected, auxApiRequestMapperController.bulkUploadRoleFunctions(mockedRequest, mockedResponse));
}
@Test
@@ -427,11 +519,11 @@ public class AuxApiRequestMapperControllerTest {
PowerMockito.mockStatic(AopUtils.class);
Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
- PortalRestResponse res = new PortalRestResponse();
- res.setStatus(PortalRestStatusEnum.ERROR);
- res.setMessage("Failed to bulkUploadUserRoles");
- res.setResponse("Failed");
- assertEquals(res, auxApiRequestMapperController.bulkUploadUserRoles(mockedRequest, mockedResponse));
+ PortalRestResponse expected = new PortalRestResponse();
+ expected.setStatus(PortalRestStatusEnum.ERROR);
+ expected.setMessage("Failed to bulkUploadUserRoles");
+ expected.setResponse("Failed");
+ assertEquals(expected, auxApiRequestMapperController.bulkUploadUserRoles(mockedRequest, mockedResponse));
}
@Test
@@ -444,11 +536,11 @@ public class AuxApiRequestMapperControllerTest {
PowerMockito.mockStatic(AopUtils.class);
Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
- PortalRestResponse res = new PortalRestResponse();
- res.setStatus(PortalRestStatusEnum.ERROR);
- res.setMessage("Failed to bulkUploadUsersSingleRole");
- res.setResponse("Failed");
- assertEquals(res,
+ PortalRestResponse expected = new PortalRestResponse();
+ expected.setStatus(PortalRestStatusEnum.ERROR);
+ expected.setMessage("Failed to bulkUploadUsersSingleRole");
+ expected.setResponse("Failed");
+ assertEquals(expected,
auxApiRequestMapperController.bulkUploadUsersSingleRole(mockedRequest, mockedResponse, (long) 1));
}
@@ -462,11 +554,11 @@ public class AuxApiRequestMapperControllerTest {
PowerMockito.mockStatic(AopUtils.class);
Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
- PortalRestResponse res = new PortalRestResponse();
- res.setStatus(PortalRestStatusEnum.ERROR);
- res.setMessage("Failed to bulkUploadPartnerRoleFunctions");
- res.setResponse("Failed");
- assertEquals(res, auxApiRequestMapperController.bulkUploadPartnerFunctions(mockedRequest, mockedResponse));
+ PortalRestResponse expected = new PortalRestResponse();
+ expected.setStatus(PortalRestStatusEnum.ERROR);
+ expected.setMessage("Failed to bulkUploadPartnerRoleFunctions");
+ expected.setResponse("Failed");
+ assertEquals(expected, auxApiRequestMapperController.bulkUploadPartnerFunctions(mockedRequest, mockedResponse));
}
@Test
@@ -480,11 +572,11 @@ public class AuxApiRequestMapperControllerTest {
Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
List<Role> upload = new ArrayList<>();
- PortalRestResponse res = new PortalRestResponse();
- res.setStatus(PortalRestStatusEnum.ERROR);
- res.setMessage("Failed to bulkUploadRoles");
- res.setResponse("Failed");
- assertEquals(res, auxApiRequestMapperController.bulkUploadPartnerRoles(mockedRequest, mockedResponse, upload));
+ PortalRestResponse expected = new PortalRestResponse();
+ expected.setStatus(PortalRestStatusEnum.ERROR);
+ expected.setMessage("Failed to bulkUploadRoles");
+ expected.setResponse("Failed");
+ assertEquals(expected, auxApiRequestMapperController.bulkUploadPartnerRoles(mockedRequest, mockedResponse, upload));
}
@Test
@@ -497,11 +589,11 @@ public class AuxApiRequestMapperControllerTest {
PowerMockito.mockStatic(AopUtils.class);
Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
- PortalRestResponse res = new PortalRestResponse();
- res.setStatus(PortalRestStatusEnum.ERROR);
- res.setMessage("Failed to bulkUploadPartnerRoleFunctions");
- res.setResponse("Failed");
- assertEquals(res, auxApiRequestMapperController.bulkUploadPartnerRoleFunctions(mockedRequest, mockedResponse));
+ PortalRestResponse expected = new PortalRestResponse();
+ expected.setStatus(PortalRestStatusEnum.ERROR);
+ expected.setMessage("Failed to bulkUploadPartnerRoleFunctions");
+ expected.setResponse("Failed");
+ assertEquals(expected, auxApiRequestMapperController.bulkUploadPartnerRoleFunctions(mockedRequest, mockedResponse));
}
@Test
@@ -532,6 +624,23 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void postUserProfileXSSTest() {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/userProfile");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", rolesApprovalSystemController);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
+ ExternalSystemUser extSysUser = new ExternalSystemUser();
+ extSysUser.setLoginId("<script>alert(“XSS”);</script>");
+ PortalRestResponse<String> actual = auxApiRequestMapperController.postUserProfile(mockedRequest, extSysUser, mockedResponse);
+ PortalRestResponse<String> expected = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ExternalSystemUser is not valid", "Failed");
+ assertEquals(expected, actual);
+ }
+
+ @Test
public void putUserProfileTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/userProfile");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -546,6 +655,23 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void putUserProfileXSSTest() {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/userProfile");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", rolesApprovalSystemController);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
+ ExternalSystemUser extSysUser = new ExternalSystemUser();
+ extSysUser.setLoginId("<script>alert(“XSS”);</script>");
+ PortalRestResponse<String> actual = auxApiRequestMapperController.putUserProfile(mockedRequest, extSysUser, mockedResponse);
+ PortalRestResponse<String> expected = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ExternalSystemUser is not valid", "Failed");
+ assertEquals(expected, actual);
+ }
+
+ @Test
public void deleteUserProfileTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/userProfile");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -560,6 +686,23 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void deleteUserProfileXSSTest() throws Exception {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/userProfile");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", rolesApprovalSystemController);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("DELETE");
+ ExternalSystemUser extSysUser = new ExternalSystemUser();
+ extSysUser.setLoginId("<script>alert(“XSS”);</script>");
+ PortalRestResponse<String> actual = auxApiRequestMapperController.deleteUserProfile(mockedRequest, extSysUser, mockedResponse);
+ PortalRestResponse<String> expected = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ExternalSystemUser is not valid", "Failed");
+ assertEquals(expected, actual);
+ }
+
+ @Test
public void handleRequestTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/ticketevent");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -573,6 +716,21 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void handleRequestXSSTest() throws Exception {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/ticketevent");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", ticketEventVersionController);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
+ PortalRestResponse<String> actual = auxApiRequestMapperController.handleRequest(mockedRequest, mockedResponse, "<script>alert(“XSS”);</script>");
+ PortalRestResponse<String> expected = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ticketEventJson is not valid", "Failed");
+ assertEquals(expected, actual);
+ }
+
+ @Test
public void postPortalAdminTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/portalAdmin");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -587,6 +745,23 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void postPortalAdminXSSTest() throws Exception {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/portalAdmin");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", appsControllerExternalVersionRequest);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
+ EPUser epUser = new EPUser();
+ epUser.setLoginId("<script>alert(/XSS”)</script>");
+ PortalRestResponse<String> actual = auxApiRequestMapperController.postPortalAdmin(mockedRequest, mockedResponse, epUser);
+ PortalRestResponse<String> expected = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "EPUser is not valid", "Failed");
+ assertEquals(expected, actual);
+ }
+
+ @Test
public void getOnboardAppExternalTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/onboardApp/1");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -614,6 +789,23 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void postOnboardAppExternalXSSTest() throws Exception {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/onboardApp");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", appsControllerExternalVersionRequest);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
+ OnboardingApp newOnboardApp = new OnboardingApp();
+ newOnboardApp.setUebKey("&#00;</form><input type&#61;\"date\" onfocus=\"alert(1)\">");
+ PortalRestResponse<String> actual = auxApiRequestMapperController.postOnboardAppExternal(mockedRequest, mockedResponse, newOnboardApp);
+ PortalRestResponse<String> expected = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "OnboardingApp is not valid", "Failed");
+ assertEquals(expected, actual);
+ }
+
+ @Test
public void putOnboardAppExternalTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/onboardApp/1");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -629,6 +821,24 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void putOnboardAppExternalXSSTest() throws Exception {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/onboardApp/1");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", appsControllerExternalVersionRequest);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("PUT");
+ OnboardingApp newOnboardApp = new OnboardingApp();
+ newOnboardApp.setUebTopicName("&#13;<blink/&#13; onmouseover=pr&#x6F;mp&#116;(1)>OnMouseOver {Firefox & Opera}");
+ PortalRestResponse<String> actual = auxApiRequestMapperController.putOnboardAppExternal(mockedRequest, mockedResponse, (long) 1,
+ newOnboardApp);
+ PortalRestResponse<String> expected = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "OnboardingApp is not valid", "Failed");
+ assertEquals(expected, actual);
+ }
+
+ @Test
public void publishNotificationTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/publishNotification");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
@@ -643,6 +853,24 @@ public class AuxApiRequestMapperControllerTest {
}
@Test
+ public void publishNotificationXSSTest() throws Exception {
+ Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/publishNotification");
+ Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
+ Map<String, Object> beans = new HashMap<>();
+ beans.put("bean1", externalAppsRestfulVersionController);
+ Mockito.when(context.getBeansWithAnnotation(ApiVersion.class)).thenReturn(beans);
+ PowerMockito.mockStatic(AopUtils.class);
+ Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false);
+ Mockito.when(mockedRequest.getMethod()).thenReturn("POST");
+ EpNotificationItem notificationItem = new EpNotificationItem();
+ notificationItem.setIsForAllRoles("</svg>''<svg><script 'AQuickBrownFoxJumpsOverTheLazyDog'>alert&#x28;1&#x29; {Opera}");
+ PortalAPIResponse actual = auxApiRequestMapperController.publishNotification(mockedRequest, notificationItem, mockedResponse);
+ PortalAPIResponse expected = new PortalAPIResponse(false, "EpNotificationItem is not valid");
+ assertEquals(expected.getMessage(), actual.getMessage());
+ assertEquals(expected.getStatus(), actual.getStatus());
+ }
+
+ @Test
public void getFavoritesForUserTest() throws Exception {
Mockito.when(mockedRequest.getRequestURI()).thenReturn("/auxapi/v3/getFavorites");
Mockito.when(mockedRequest.getHeader("MinorVersion")).thenReturn("0");
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java
index 417568da..cd130e9f 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java
@@ -57,10 +57,8 @@ import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.onap.portalapp.portal.controller.DashboardController;
import org.onap.portalapp.portal.core.MockEPUser;
import org.onap.portalapp.portal.domain.EPUser;
-import org.onap.portalapp.portal.domain.EcompAuditLog;
import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
import org.onap.portalapp.portal.ecomp.model.SearchResultItem;
@@ -72,13 +70,10 @@ import org.onap.portalapp.portal.service.DashboardSearchServiceImpl;
import org.onap.portalapp.portal.transport.CommonWidget;
import org.onap.portalapp.portal.transport.CommonWidgetMeta;
import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
-import org.onap.portalapp.portal.utils.EcompPortalUtils;
-import org.onap.portalapp.portal.utils.PortalConstants;
import org.onap.portalapp.util.EPUserUtils;
import org.onap.portalsdk.core.domain.AuditLog;
import org.onap.portalsdk.core.domain.support.CollaborateList;
import org.onap.portalsdk.core.service.AuditService;
-import org.onap.portalsdk.core.service.AuditServiceImpl;
import org.onap.portalsdk.core.util.SystemProperties;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
@@ -92,12 +87,9 @@ public class DashboardControllerTest {
@Mock
DashboardSearchService searchService = new DashboardSearchServiceImpl();
-
- /*@Mock
- AuditService auditService = new AuditServiceImpl();*/
-
+
@InjectMocks
- DashboardController dashboardController = new DashboardController();
+ DashboardController dashboardController;
@Mock
AdminRolesService adminRolesService = new AdminRolesServiceImpl();
@@ -129,7 +121,7 @@ public class DashboardControllerTest {
commonWidget.setHref("testhref");
commonWidget.setTitle("testTitle");
commonWidget.setContent("testcontent");
- commonWidget.setEventDate("testDate");
+ commonWidget.setEventDate("2017-03-24");
commonWidget.setSortOrder(1);
widgetList.add(commonWidget);
commonWidgetMeta.setItems(widgetList);
@@ -163,8 +155,21 @@ public class DashboardControllerTest {
PortalRestResponse<CommonWidgetMeta> actualResponse = dashboardController.getWidgetData(mockedRequest, resourceType);
assertEquals(expectedData,actualResponse);
- }
-
+ }
+
+ @Test
+ public void getWidgetDataTestXSS() {
+
+ String resourceType = "“><script>alert(“XSS”)</script>";
+ PortalRestResponse<CommonWidgetMeta> expectedData = new PortalRestResponse<>();
+ expectedData.setStatus(PortalRestStatusEnum.ERROR);
+ expectedData.setMessage("Unexpected resource type “><script>alert(“XSS”)</script>");
+ expectedData.setResponse(null);
+
+ PortalRestResponse<CommonWidgetMeta> actualResponse = dashboardController.getWidgetData(mockedRequest, resourceType);
+ assertEquals(expectedData, actualResponse);
+ }
+
@Test
public void getWidgetDataWithValidResourceTest() throws IOException {
String resourceType = "EVENTS";
@@ -194,6 +199,20 @@ public class DashboardControllerTest {
PortalRestResponse<String> actualResponse = dashboardController.saveWidgetDataBulk(commonWidgetMeta);
assertEquals(expectedData,actualResponse);
}
+
+ @Test
+ public void saveWidgetDataBulkXSSTest() {
+ CommonWidgetMeta commonWidgetMeta= mockCommonWidgetMeta();
+ commonWidgetMeta.setCategory("<script>alert(‘XSS’)</script>");
+
+ PortalRestResponse<String> expectedData = new PortalRestResponse<>();
+ expectedData.setStatus(PortalRestStatusEnum.ERROR);
+ expectedData.setResponse("ERROR");
+ expectedData.setMessage("Unsafe resource type " + commonWidgetMeta.toString());
+
+ PortalRestResponse<String> actualResponse = dashboardController.saveWidgetDataBulk(commonWidgetMeta);
+ assertEquals(expectedData,actualResponse);
+ }
@Test
public void saveWidgetUnexpectedDataBulkTest() throws IOException {
@@ -261,6 +280,24 @@ public class DashboardControllerTest {
assertEquals(expectedData,actualResponse);
}
+
+ @Test
+ public void saveWidgetDataXSSTest() {
+
+ CommonWidget commonWidget = mockCommonWidget();
+ commonWidget.setId((long)1);
+ commonWidget.setContent("test");
+ commonWidget.setCategory("<form><a href=\"javascript:\\u0061lert&#x28;1&#x29;\">X");
+ PortalRestResponse<String> expectedData = new PortalRestResponse<String>();
+ expectedData.setStatus(PortalRestStatusEnum.ERROR);
+ expectedData.setResponse("ERROR");
+ expectedData.setMessage("Unsafe resource type " + commonWidget.toString());
+
+ Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true);
+ PortalRestResponse<String> actualResponse = dashboardController.saveWidgetData(commonWidget, mockedRequest, mockedResponse);
+ assertEquals(expectedData,actualResponse);
+
+ }
@Test
public void saveWidgetDataTitleTest() throws IOException {
@@ -268,6 +305,7 @@ public class DashboardControllerTest {
commonWidget.setId((long)1);
commonWidget.setContent("test");
commonWidget.setTitle("test");
+ commonWidget.setEventDate("2017-05-06");
PortalRestResponse<String> expectedData = new PortalRestResponse<String>();
expectedData.setStatus(PortalRestStatusEnum.ERROR);
expectedData.setMessage("Invalid category: test");
@@ -280,7 +318,8 @@ public class DashboardControllerTest {
@Test
public void saveWidgetDataErrorTest() throws IOException {
- CommonWidget commonWidget = mockCommonWidget();
+ CommonWidget commonWidget = mockCommonWidget();
+ commonWidget.setEventDate("2017-03-05");
PortalRestResponse<String> expectedData = new PortalRestResponse<String>();
expectedData.setStatus(PortalRestStatusEnum.ERROR);
expectedData.setMessage("Invalid category: test");
@@ -323,7 +362,7 @@ public class DashboardControllerTest {
public void deleteWidgetDataTest() throws IOException {
CommonWidget commonWidget = mockCommonWidget();
-
+ commonWidget.setEventDate("2017-03-25");
PortalRestResponse<String> expectedData = new PortalRestResponse<String>();
expectedData.setStatus(PortalRestStatusEnum.OK);
expectedData.setMessage("success");
@@ -335,6 +374,20 @@ public class DashboardControllerTest {
assertEquals(expectedData,actualResponse);
}
+
+ @Test
+ public void deleteWidgetDataXSSTest() {
+
+ CommonWidget commonWidget = mockCommonWidget();
+ commonWidget.setCategory("<svg><script x:href='https://dl.dropbox.com/u/13018058/js.js' {Opera}");
+ PortalRestResponse<String> expectedData = new PortalRestResponse<>();
+ expectedData.setStatus(PortalRestStatusEnum.ERROR);
+ expectedData.setMessage("Unsafe resource type " + commonWidget.toString());
+ expectedData.setResponse("ERROR");
+ PortalRestResponse<String> actualResponse = dashboardController.deleteWidgetData(commonWidget);
+ assertEquals(expectedData,actualResponse);
+
+ }
@Test
public void getActiveUsersTest(){
@@ -541,6 +594,23 @@ public class DashboardControllerTest {
PortalRestResponse<Map<String, List<SearchResultItem>>> actualResponse = dashboardController.searchPortal(mockedRequest, null);
assertTrue(actualResponse.getStatus().compareTo(PortalRestStatusEnum.ERROR) == 0);
}
+
+ @Test
+ public void searchPortalXSSTest(){
+ EPUser user = null;
+ String searchString = "\n"
+ + "<form><textarea &#13; onkeyup='\\u0061\\u006C\\u0065\\u0072\\u0074&#x28;1&#x29;'>";
+ PowerMockito.mockStatic(EPUserUtils.class);
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<>();
+ expectedResult.setMessage("searchPortal: String string is not safe");
+ expectedResult.setResponse(new HashMap<>());
+ expectedResult.setStatus(PortalRestStatusEnum.ERROR);
+
+ PortalRestResponse<Map<String, List<SearchResultItem>>> actualResponse = dashboardController.searchPortal(mockedRequest, searchString);
+ assertEquals(expectedResult, actualResponse);
+ }
+
@Test
public void searchPortalTestWithException(){
EPUser user = mockUser.mockEPUser();
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java
index b476a72d..3373ef92 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java
@@ -103,7 +103,7 @@ public class ExternalAccessRolesControllerTest {
@Mock
ExternalAccessRolesService externalAccessRolesService = new ExternalAccessRolesServiceImpl();
@InjectMocks
- ExternalAccessRolesController externalAccessRolesController = new ExternalAccessRolesController();
+ ExternalAccessRolesController externalAccessRolesController;
@Mock
UserService userservice = new UserServiceCentalizedImpl();
@Mock
@@ -186,6 +186,18 @@ public class ExternalAccessRolesControllerTest {
}
@Test
+ public void getUserXSSTest() throws Exception {
+ String loginId = "<script ~~~>alert(0%0)</script ~~~>";
+ String expected = getXSSKeyJson();
+ StringWriter sw = new StringWriter();
+ PrintWriter writer = new PrintWriter(sw);
+ Mockito.when(mockedResponse.getWriter()).thenReturn(writer);
+ externalAccessRolesController.getUser(mockedRequest, mockedResponse, loginId);
+ String actual = sw.getBuffer().toString().trim();
+ assertEquals(expected, actual);
+ }
+
+ @Test
public void getV2UserListTest() throws Exception {
String expectedCentralUser = "test";
String loginId = "test";
@@ -223,8 +235,8 @@ public class ExternalAccessRolesControllerTest {
@Test
public void getRolesForAppCentralRoleTest() throws Exception {
- List<CentralRole> expectedCentralRoleList = new ArrayList<CentralRole>();
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<CentralRole> expectedCentralRoleList = new ArrayList<>();
+ List<EPApp> applicationList = new ArrayList<>();
List<CentralV2Role> centralV2RoleList = new ArrayList<>();
List<CentralRole> centralRoleList = new ArrayList<>();
EPApp app = mockApp();
@@ -246,7 +258,7 @@ public class ExternalAccessRolesControllerTest {
@Test(expected = NullPointerException.class)
public void getRolesForAppCentralRoleExceptionTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
List<CentralV2Role> centralV2RoleList = new ArrayList<>();
List<CentralRole> centralRoleList = new ArrayList<>();
EPApp app = mockApp();
@@ -268,8 +280,8 @@ public class ExternalAccessRolesControllerTest {
@Test
public void getV2RolesForAppTest() throws Exception {
- List<CentralRole> expectedCentralRoleList = new ArrayList<CentralRole>();
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<CentralRole> expectedCentralRoleList = new ArrayList<>();
+ List<EPApp> applicationList = new ArrayList<>();
List<CentralV2Role> centralV2Role = new ArrayList<>();
EPApp app = mockApp();
app.setCentralAuth(true);
@@ -288,8 +300,8 @@ public class ExternalAccessRolesControllerTest {
@Test(expected = NullPointerException.class)
public void getV2RolesForAppExceptionTest() throws Exception {
- List<CentralRole> expectedCentralRoleList = new ArrayList<CentralRole>();
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<CentralRole> expectedCentralRoleList = new ArrayList<>();
+ List<EPApp> applicationList = new ArrayList<>();
List<CentralV2Role> centralV2Role = new ArrayList<>();
EPApp app = mockApp();
app.setCentralAuth(true);
@@ -308,7 +320,7 @@ public class ExternalAccessRolesControllerTest {
@Test(expected = NullPointerException.class)
public void getRolesForAppTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
List<CentralV2Role> answer = new ArrayList<>();
EPApp app = mockApp();
applicationList.add(app);
@@ -320,7 +332,7 @@ public class ExternalAccessRolesControllerTest {
@Test(expected = NullPointerException.class)
public void getRolesForAppExceptionTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
applicationList.add(app);
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList);
@@ -332,9 +344,9 @@ public class ExternalAccessRolesControllerTest {
@Test
public void getRoleFunctionsListTest() throws Exception {
- List<CentralRole> expectedCentralRoleList = new ArrayList<CentralRole>();
- List<CentralRoleFunction> roleFuncList = new ArrayList<CentralRoleFunction>();
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<CentralRole> expectedCentralRoleList = new ArrayList<>();
+ List<CentralRoleFunction> roleFuncList = new ArrayList<>();
+ List<EPApp> applicationList = new ArrayList<>();
List<CentralV2RoleFunction> centralV2RoleFunction = new ArrayList<>();
EPApp app = mockApp();
app.setCentralAuth(true);
@@ -366,8 +378,8 @@ public class ExternalAccessRolesControllerTest {
@Test
public void getV2RoleFunctionsListTest() throws Exception {
- List<CentralV2RoleFunction> expectedCentralV2RoleFunctionList = new ArrayList<CentralV2RoleFunction>();
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<CentralV2RoleFunction> expectedCentralV2RoleFunctionList = new ArrayList<>();
+ List<EPApp> applicationList = new ArrayList<>();
List<CentralV2RoleFunction> centralV2RoleFunction = new ArrayList<>();
EPApp app = mockApp();
app.setCentralAuth(true);
@@ -398,7 +410,7 @@ public class ExternalAccessRolesControllerTest {
@Test
public void getRoleInfoValidationTest() throws Exception {
CentralRole expectedCentralRole = null;
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
long roleId = 1;
CentralV2Role centralV2Role = new CentralV2Role();
EPApp app = mockApp();
@@ -446,7 +458,7 @@ public class ExternalAccessRolesControllerTest {
public void getV2RoleInfoValidationTest() throws Exception {
CentralV2Role expectedCentralRole = new CentralV2Role();
expectedCentralRole.setActive(false);
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
long roleId = 1;
CentralV2Role centralV2Role = new CentralV2Role();
EPApp app = mockApp();
@@ -491,10 +503,10 @@ public class ExternalAccessRolesControllerTest {
}
@Test
- public void getV2RoleFunctionTest() throws HttpClientErrorException, Exception {
+ public void getV2RoleFunctionTest() throws Exception {
CentralV2RoleFunction expectedCentralV2RoleFunction = new CentralV2RoleFunction();
expectedCentralV2RoleFunction.setCode("test");
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
String code = "test";
CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction();
centralV2RoleFunction.setCode("test");
@@ -512,10 +524,11 @@ public class ExternalAccessRolesControllerTest {
assertEquals(actualCentralV2RoleFunction.getCode(), expectedCentralV2RoleFunction.getCode());
}
+
@Test
- public void getV2RoleFunctionNullCheckTest() throws HttpClientErrorException, Exception {
+ public void getV2RoleFunctionNullCheckTest() throws Exception {
CentralV2RoleFunction expectedCentralV2RoleFunction = new CentralV2RoleFunction();
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
String code = "test";
CentralV2RoleFunction centralV2RoleFunction = null;
EPApp app = mockApp();
@@ -586,13 +599,40 @@ public class ExternalAccessRolesControllerTest {
}
@Test
+ public void getRoleFunctionXSSTest() throws Exception {
+ String expected = getXSSKeyJson();
+ EPApp mockApp = mockApp();
+ mockApp.setCentralAuth(true);
+ List<EPApp> mockAppList = new ArrayList<>();
+ mockAppList.add(mockApp);
+ StringWriter sw = new StringWriter();
+ PrintWriter writer = new PrintWriter(sw);
+ Mockito.when(mockedResponse.getWriter()).thenReturn(writer);
+ CentralV2RoleFunction roleFunction1 = new CentralV2RoleFunction();
+ CentralRoleFunction roleFunction2 = new CentralRoleFunction();
+ roleFunction1.setCode("test2");
+ String code = "<script>alert(‘XSS’)</script>";
+ Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn(uebKey);
+ Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader("uebkey"))).thenReturn(mockAppList);
+ ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.FOUND);
+ Mockito.when(externalAccessRolesService.getNameSpaceIfExists(mockAppList.get(0))).thenReturn(response);
+ Mockito.when(externalAccessRolesService.getRoleFunction(code, mockedRequest.getHeader("uebkey")))
+ .thenReturn(roleFunction1);
+ CentralRoleFunction returnedValue = externalAccessRolesController.getRoleFunction(mockedRequest, mockedResponse,
+ code);
+ assertEquals(returnedValue, roleFunction2);
+ String result = sw.getBuffer().toString().trim();
+ assertEquals(expected, result);
+ }
+
+ @Test
public void saveRoleFunctionIfIsNotDeletedTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
applicationList.add(app);
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList);
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage(null);
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -609,13 +649,13 @@ public class ExternalAccessRolesControllerTest {
@Test
public void saveRoleFunctionExceptionTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
app.setCentralAuth(true);
applicationList.add(app);
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList);
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage(null);
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -627,10 +667,9 @@ public class ExternalAccessRolesControllerTest {
assertEquals(portalRestResponse, expectedportalRestResponse);
}
- @SuppressWarnings("static-access")
@Test
public void saveRoleFunctionTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPUser user = mockUser.mockEPUser();
List<EPUser> userList = new ArrayList<>();
userList.add(user);
@@ -648,7 +687,7 @@ public class ExternalAccessRolesControllerTest {
saveRoleFunc.setAppId(app.getId());
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList);
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully saved!");
expectedportalRestResponse.setResponse("Success");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK);
@@ -670,13 +709,54 @@ public class ExternalAccessRolesControllerTest {
}
@Test
+ public void saveRoleFunctionXSSTest() throws Exception {
+ List<EPApp> applicationList = new ArrayList<>();
+ EPUser user = mockUser.mockEPUser();
+ List<EPUser> userList = new ArrayList<>();
+ userList.add(user);
+ EPApp app = mockApp();
+ app.setCentralAuth(true);
+ applicationList.add(app);
+ JSONObject roleFunc = new JSONObject();
+ roleFunc.put("type", "<script>alert(“XSS”)</script> ");
+ roleFunc.put("code", "test_instance");
+ roleFunc.put("action", "test_action");
+ roleFunc.put("name", "test_name");
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ CentralV2RoleFunction saveRoleFunc = mapper.readValue(roleFunc.toString(), CentralV2RoleFunction.class);
+ saveRoleFunc.setAppId(app.getId());
+ Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList);
+ PortalRestResponse<String> portalRestResponse = null;
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
+ expectedportalRestResponse.setMessage("Failed to roleFunc, not valid data.");
+ expectedportalRestResponse.setResponse("Failed");
+ expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
+ Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn(uebKey);
+ Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader("uebkey"))).thenReturn(applicationList);
+ ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.FOUND);
+ Mockito.when(externalAccessRolesService.getNameSpaceIfExists(applicationList.get(0))).thenReturn(response);
+ Mockito.when(externalAccessRolesService.getRoleFunction("test_type|test_instance|test_action", app.getUebKey()))
+ .thenReturn(null);
+ Mockito.when(externalAccessRolesService.saveCentralRoleFunction(Matchers.any(CentralV2RoleFunction.class),
+ Matchers.any(EPApp.class))).thenReturn(true);
+ Mockito.when(externalAccessRolesService.getUser(mockedRequest.getHeader(Matchers.anyString())))
+ .thenReturn(userList);
+ Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(Matchers.anyString())))
+ .thenReturn(applicationList);
+ portalRestResponse = externalAccessRolesController.saveRoleFunction(mockedRequest, mockedResponse,
+ roleFunc.toString());
+ assertEquals(expectedportalRestResponse, portalRestResponse);
+ }
+
+ @Test
public void deleteRoleFunctionTest() throws Exception {
PowerMockito.mockStatic(EcompPortalUtils.class);
PowerMockito.mockStatic(SystemProperties.class);
PowerMockito.mockStatic(EPCommonSystemProperties.class);
PowerMockito.mockStatic(PortalConstants.class);
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully Deleted");
expectedportalRestResponse.setResponse("Success");
EPUser user = mockUser.mockEPUser();
@@ -700,6 +780,36 @@ public class ExternalAccessRolesControllerTest {
}
@Test
+ public void deleteRoleFunctionXSSTest() throws Exception {
+ PowerMockito.mockStatic(EcompPortalUtils.class);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPCommonSystemProperties.class);
+ PowerMockito.mockStatic(PortalConstants.class);
+ PortalRestResponse<String> portalRestResponse = null;
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
+ expectedportalRestResponse.setMessage("Failed to deleteRoleFunction, not valid data.");
+ expectedportalRestResponse.setResponse("Failed");
+ expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
+ EPUser user = mockUser.mockEPUser();
+ List<EPUser> userList = new ArrayList<>();
+ userList.add(user);
+ EPApp app = mockApp();
+ app.setCentralAuth(true);
+ List<EPApp> appList = new ArrayList<>();
+ appList.add(app);
+ String code = "<script>alert(‘XSS’)</script>";
+ Mockito.when(mockedRequest.getHeader("LoginId")).thenReturn("guestT");
+ Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn(uebKey);
+ Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader("uebkey"))).thenReturn(appList);
+ ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.FOUND);
+ Mockito.when(externalAccessRolesService.getNameSpaceIfExists(appList.get(0))).thenReturn(response);
+ Mockito.when(externalAccessRolesService.getUser(mockedRequest.getHeader("LoginId"))).thenReturn(userList);
+ Mockito.when(externalAccessRolesService.deleteCentralRoleFunction(code, app)).thenReturn(true);
+ portalRestResponse = externalAccessRolesController.deleteRoleFunction(mockedRequest, mockedResponse, code);
+ assertEquals(portalRestResponse, expectedportalRestResponse);
+ }
+
+ @Test
public void getActiveRolesTest() throws Exception {
String reason = getInvalidKeyJson();
StringWriter sw = new StringWriter();
@@ -717,9 +827,9 @@ public class ExternalAccessRolesControllerTest {
List<CentralRole> expectedRolesList = null;
EPApp app = mockApp();
app.setCentralAuth(true);
- List<EPApp> appList = new ArrayList<EPApp>();
+ List<EPApp> appList = new ArrayList<>();
appList.add(app);
- List<CentralV2Role> cenRoles = new ArrayList<CentralV2Role>();
+ List<CentralV2Role> cenRoles = new ArrayList<>();
Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn(uebKey);
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader("uebkey"))).thenReturn(appList);
ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.FOUND);
@@ -757,10 +867,19 @@ public class ExternalAccessRolesControllerTest {
return reason;
}
+ private String getXSSKeyJson() throws JsonProcessingException {
+ final Map<String, String> uebkeyResponse = new HashMap<>();
+ String reason = "";
+ ObjectMapper mapper = new ObjectMapper();
+ uebkeyResponse.put("error", "Data is not valid");
+ reason = mapper.writeValueAsString(uebkeyResponse);
+ return reason;
+ }
+
@Test
- public void deleteDependcyRoleRecordExceptionTest() throws Exception {
+ public void deleteDependcyRoleRecordExceptionTest() {
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Invalid credentials!");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -776,7 +895,7 @@ public class ExternalAccessRolesControllerTest {
Mockito.when(externalAccessRolesService.bulkUploadFunctions(mockedRequest.getHeader(uebKey)))
.thenReturn(result);
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully added: 0");
expectedportalRestResponse.setResponse("Success");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK);
@@ -789,7 +908,7 @@ public class ExternalAccessRolesControllerTest {
Mockito.when(externalAccessRolesService.bulkUploadFunctions(mockedRequest.getHeader(uebKey)))
.thenThrow(httpClientErrorException);
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Failed to bulkUploadFunctions");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -801,7 +920,7 @@ public class ExternalAccessRolesControllerTest {
public void bulkUploadRolesTest() throws Exception {
Integer result = 0;
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully added: 0");
expectedportalRestResponse.setResponse("Success");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK);
@@ -815,7 +934,7 @@ public class ExternalAccessRolesControllerTest {
Mockito.when(externalAccessRolesService.bulkUploadRoles(mockedRequest.getHeader(uebKey)))
.thenThrow(httpClientErrorException);
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Failed to bulkUploadRoles");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -827,7 +946,7 @@ public class ExternalAccessRolesControllerTest {
public void bulkUploadRoleFunctionsTest() throws Exception {
Integer result = 0;
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully added: 0");
expectedportalRestResponse.setResponse("Success");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK);
@@ -842,7 +961,7 @@ public class ExternalAccessRolesControllerTest {
Mockito.when(externalAccessRolesService.bulkUploadRolesFunctions(mockedRequest.getHeader(uebKey)))
.thenThrow(httpClientErrorException);
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Failed to bulkUploadRoleFunctions");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -854,7 +973,7 @@ public class ExternalAccessRolesControllerTest {
public void bulkUploadUserRolesTest() throws Exception {
Integer result = 0;
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully added: 0");
expectedportalRestResponse.setResponse("Success");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK);
@@ -869,7 +988,7 @@ public class ExternalAccessRolesControllerTest {
Mockito.when(externalAccessRolesService.bulkUploadUserRoles(mockedRequest.getHeader(uebKey)))
.thenThrow(httpClientErrorException);
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Failed to bulkUploadUserRoles");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -878,9 +997,9 @@ public class ExternalAccessRolesControllerTest {
}
@Test
- public void bulkUploadPartnerFunctionsTest() throws Exception {
+ public void bulkUploadPartnerFunctionsTest() {
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully added: '0' functions");
expectedportalRestResponse.setResponse("Success");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK);
@@ -889,9 +1008,9 @@ public class ExternalAccessRolesControllerTest {
}
@Test
- public void bulkUploadPartnerRolesTest() throws Exception {
+ public void bulkUploadPartnerRolesTest() {
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully added");
expectedportalRestResponse.setResponse("Success");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK);
@@ -902,9 +1021,9 @@ public class ExternalAccessRolesControllerTest {
}
@Test
- public void bulkUploadPartnerRolesExceptionTest() throws Exception {
+ public void bulkUploadPartnerRolesExceptionTest() {
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully added");
expectedportalRestResponse.setResponse("Success");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK);
@@ -942,10 +1061,10 @@ public class ExternalAccessRolesControllerTest {
}
@Test
- public void saveRoleExceptionTest() throws Exception {
+ public void saveRoleExceptionTest() {
Role role = new Role();
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Invalid credentials!");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -954,10 +1073,10 @@ public class ExternalAccessRolesControllerTest {
}
@Test
- public void deleteRoleExceptionTest() throws Exception {
+ public void deleteRoleExceptionTest() {
String role = "TestNew";
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Invalid credentials!");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -966,9 +1085,9 @@ public class ExternalAccessRolesControllerTest {
}
@Test
- public void bulkUploadPartnerRoleFunctionsTest() throws Exception {
+ public void bulkUploadPartnerRoleFunctionsTest() {
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully added: '0' role functions");
expectedportalRestResponse.setResponse("Success");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK);
@@ -986,7 +1105,7 @@ public class ExternalAccessRolesControllerTest {
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
Mockito.when(mockedResponse.getWriter()).thenReturn(writer);
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
app.setCentralAuth(true);
applicationList.add(app);
@@ -1012,7 +1131,7 @@ public class ExternalAccessRolesControllerTest {
@Test(expected = NullPointerException.class)
public void deleteRoleV2Test() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
applicationList.add(app);
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList);
@@ -1020,7 +1139,7 @@ public class ExternalAccessRolesControllerTest {
"Success");
Mockito.when(externalAccessRolesService.deleteDependencyRoleRecord(Matchers.anyLong(), Matchers.anyString(),
Matchers.anyString())).thenReturn(externalRequestFieldsValidator);
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully Deleted");
expectedportalRestResponse.setResponse("Success");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK);
@@ -1031,12 +1150,12 @@ public class ExternalAccessRolesControllerTest {
@Test
public void deleteRoleV2InvalidUebKeyTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
applicationList.add(app);
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey)))
.thenThrow(new Exception("Invalid credentials!"));
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Invalid credentials!");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -1047,12 +1166,12 @@ public class ExternalAccessRolesControllerTest {
@Test
public void deleteRoleV2InvalidUebKeyWithDiffErrorTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
applicationList.add(app);
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey)))
.thenThrow(new Exception("test"));
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("test");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -1063,7 +1182,7 @@ public class ExternalAccessRolesControllerTest {
@Test(expected = NullPointerException.class)
public void deleteRoleV2ExceptionTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
applicationList.add(app);
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList);
@@ -1071,7 +1190,7 @@ public class ExternalAccessRolesControllerTest {
"failed");
Mockito.when(externalAccessRolesService.deleteDependencyRoleRecord(Matchers.anyLong(), Matchers.anyString(),
Matchers.anyString())).thenReturn(externalRequestFieldsValidator);
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Failed to deleteRole");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -1082,7 +1201,7 @@ public class ExternalAccessRolesControllerTest {
@Test
public void getEpUserNullTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
app.setUebKey("uebKey");
app.setCentralAuth(true);
@@ -1095,7 +1214,7 @@ public class ExternalAccessRolesControllerTest {
@Test
public void getEpUserTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
app.setUebKey("uebKey");
app.setCentralAuth(true);
@@ -1103,7 +1222,7 @@ public class ExternalAccessRolesControllerTest {
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList);
ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK);
Mockito.when(externalAccessRolesService.getNameSpaceIfExists(app)).thenReturn(response);
- String user = "{\"id\":null,\"created\":null,\"modified\":null,\"createdId\":null,\"modifiedId\":null,\"rowNum\":null,\"auditUserId\":null,\"auditTrail\":null,\"orgId\":null,\"managerId\":null,\"firstName\":\"test\",\"middleInitial\":null,\"lastName\":null,\"phone\":null,\"fax\":null,\"cellular\":null,\"email\":null,\"addressId\":null,\"alertMethodCd\":null,\"hrid\":null,\"orgUserId\":null,\"orgCode\":null,\"address1\":null,\"address2\":null,\"city\":null,\"state\":null,\"zipCode\":null,\"country\":null,\"orgManagerUserId\":null,\"locationClli\":null,\"businessCountryCode\":null,\"businessCountryName\":null,\"businessUnit\":null,\"businessUnitName\":null,\"department\":null,\"departmentName\":null,\"companyCode\":null,\"company\":null,\"zipCodeSuffix\":null,\"jobTitle\":null,\"commandChain\":null,\"siloStatus\":null,\"costCenter\":null,\"financialLocCode\":null,\"loginId\":null,\"loginPwd\":null,\"lastLoginDate\":null,\"active\":false,\"internal\":false,\"selectedProfileId\":null,\"timeZoneId\":null,\"online\":false,\"chatId\":null,\"userApps\":[],\"pseudoRoles\":[],\"defaultUserApp\":null,\"roles\":[],\"fullName\":\"test null\"}";
+ String user = "{\"id\":null,\"created\":null,\"modified\":null,\"createdId\":null,\"modifiedId\":null,\"rowNum\":null,\"auditUserId\":null,\"auditTrail\":null,\"orgId\":null,\"managerId\":null,\"firstName\":\"test\",\"middleInitial\":null,\"lastName\":null,\"phone\":null,\"fax\":null,\"cellular\":null,\"email\":null,\"addressId\":null,\"alertMethodCd\":null,\"hrid\":null,\"orgUserId\":null,\"orgCode\":null,\"address1\":null,\"address2\":null,\"city\":null,\"state\":null,\"zipCode\":null,\"country\":null,\"orgManagerUserId\":null,\"locationClli\":null,\"businessCountryCode\":null,\"businessCountryName\":null,\"businessUnit\":null,\"businessUnitName\":null,\"department\":null,\"departmentName\":null,\"companyCode\":null,\"company\":null,\"zipCodeSuffix\":null,\"jobTitle\":null,\"commandChain\":null,\"siloStatus\":null,\"costCenter\":null,\"financialLocCode\":null,\"loginId\":null,\"loginPwd\":null,\"lastLoginDate\":null,\"active\":false,\"internal\":false,\"selectedProfileId\":null,\"timeZoneId\":null,\"online\":false,\"chatId\":null,\"userApps\":[],\"pseudoRoles\":[],\"roles\":[]}";
Mockito.when(externalAccessRolesService.getV2UserWithRoles("test12", mockedRequest.getHeader(uebKey)))
.thenReturn(user);
User EPuser = new User();
@@ -1115,7 +1234,7 @@ public class ExternalAccessRolesControllerTest {
@Test
public void getEpUserExceptionTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
app.setCentralAuth(true);
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList);
@@ -1127,7 +1246,7 @@ public class ExternalAccessRolesControllerTest {
@Test
public void getEPRolesOfApplicationTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
app.setUebKey("uebKey");
app.setCentralAuth(true);
@@ -1152,7 +1271,7 @@ public class ExternalAccessRolesControllerTest {
@Test
public void getEPRolesOfApplicationNullTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
app.setUebKey("uebKey");
app.setCentralAuth(true);
@@ -1171,7 +1290,7 @@ public class ExternalAccessRolesControllerTest {
@Test
public void getEPRolesOfApplicationExceptionTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
app.setCentralAuth(true);
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList);
@@ -1188,7 +1307,7 @@ public class ExternalAccessRolesControllerTest {
PowerMockito.mockStatic(EPCommonSystemProperties.class);
PowerMockito.mockStatic(PortalConstants.class);
PortalRestResponse<String> actualPortalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully Saved");
expectedportalRestResponse.setResponse("Success");
EPUser user = mockUser.mockEPUser();
@@ -1220,7 +1339,7 @@ public class ExternalAccessRolesControllerTest {
PowerMockito.mockStatic(EPCommonSystemProperties.class);
PowerMockito.mockStatic(PortalConstants.class);
PortalRestResponse<String> actualPortalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully Saved");
expectedportalRestResponse.setResponse("Success");
EPUser user = mockUser.mockEPUser();
@@ -1252,7 +1371,7 @@ public class ExternalAccessRolesControllerTest {
PowerMockito.mockStatic(EPCommonSystemProperties.class);
PowerMockito.mockStatic(PortalConstants.class);
PortalRestResponse<String> actualPortalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully Saved");
expectedportalRestResponse.setResponse("Failed");
EPUser user = mockUser.mockEPUser();
@@ -1279,7 +1398,7 @@ public class ExternalAccessRolesControllerTest {
@Test(expected = NullPointerException.class)
public void saveRoleNullExceptionTest() throws Exception {
- List<EPApp> applicationList = new ArrayList<EPApp>();
+ List<EPApp> applicationList = new ArrayList<>();
EPApp app = mockApp();
applicationList.add(app);
Role role = new Role();
@@ -1288,7 +1407,7 @@ public class ExternalAccessRolesControllerTest {
"failed");
Mockito.when(externalAccessRolesService.deleteDependencyRoleRecord(Matchers.anyLong(), Matchers.anyString(),
Matchers.anyString())).thenReturn(externalRequestFieldsValidator);
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Failed to deleteRole");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
@@ -1304,7 +1423,7 @@ public class ExternalAccessRolesControllerTest {
PowerMockito.mockStatic(EPCommonSystemProperties.class);
PowerMockito.mockStatic(PortalConstants.class);
PortalRestResponse<String> actualPortalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Successfully Deleted");
expectedportalRestResponse.setResponse("Success");
EPUser user = mockUser.mockEPUser();
@@ -1329,13 +1448,44 @@ public class ExternalAccessRolesControllerTest {
}
@Test
+ public void deleteRoleXSSTest() throws Exception {
+ PowerMockito.mockStatic(EcompPortalUtils.class);
+ PowerMockito.mockStatic(SystemProperties.class);
+ PowerMockito.mockStatic(EPCommonSystemProperties.class);
+ PowerMockito.mockStatic(PortalConstants.class);
+ PortalRestResponse<String> actualPortalRestResponse = null;
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
+ expectedportalRestResponse.setMessage("Failed to deleteRole, not valid data.");
+ expectedportalRestResponse.setResponse("Failed");
+ expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
+ EPUser user = mockUser.mockEPUser();
+ List<EPUser> userList = new ArrayList<>();
+ userList.add(user);
+ EPApp app = mockApp();
+ app.setCentralAuth(true);
+ List<EPApp> appList = new ArrayList<>();
+ appList.add(app);
+ String code = "<img src=xss onerror=alert(1)>";
+ boolean deleteResponse = true;
+ Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn(uebKey);
+ Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader("uebkey"))).thenReturn(appList);
+ ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.FOUND);
+ Mockito.when(externalAccessRolesService.getNameSpaceIfExists(appList.get(0))).thenReturn(response);
+ Mockito.when(externalAccessRolesService.getUser(mockedRequest.getHeader("LoginId"))).thenReturn(userList);
+ Mockito.when(externalAccessRolesService.deleteRoleForApplication(code, mockedRequest.getHeader("uebkey")))
+ .thenReturn(deleteResponse);
+ actualPortalRestResponse = externalAccessRolesController.deleteRole(mockedRequest, mockedResponse, code);
+ assertEquals(actualPortalRestResponse.getStatus(), expectedportalRestResponse.getStatus());
+ }
+
+ @Test
public void deleteRoleNegativeTest() throws Exception {
PowerMockito.mockStatic(EcompPortalUtils.class);
PowerMockito.mockStatic(SystemProperties.class);
PowerMockito.mockStatic(EPCommonSystemProperties.class);
PowerMockito.mockStatic(PortalConstants.class);
PortalRestResponse<String> actualPortalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Failed to delete Role for 'test");
expectedportalRestResponse.setResponse("Failed");
EPUser user = mockUser.mockEPUser();
@@ -1363,13 +1513,13 @@ public class ExternalAccessRolesControllerTest {
public void deleteDependcyRoleRecordTest() throws Exception {
ExternalRequestFieldsValidator removeResult = new ExternalRequestFieldsValidator(true, "success");
PortalRestResponse<String> portalRestResponse = null;
- PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>();
+ PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>();
expectedportalRestResponse.setMessage("Invalid credentials!");
expectedportalRestResponse.setResponse("Failed");
expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR);
long roleId = 123;
String LoginId = "loginId";
- List<EPApp> appList = new ArrayList<EPApp>();
+ List<EPApp> appList = new ArrayList<>();
Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn(uebKey);
Mockito.when(mockedRequest.getHeader("LoginId")).thenReturn(LoginId);
Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader("uebkey"))).thenReturn(appList);
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java
index b1816ec6..5d323012 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java
@@ -48,7 +48,6 @@ import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.formula.functions.T;
import org.json.simple.JSONObject;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
@@ -56,7 +55,6 @@ import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.onap.portalapp.portal.controller.SchedulerController;
import org.onap.portalapp.portal.core.MockEPUser;
import org.onap.portalapp.portal.domain.EPUser;
import org.onap.portalapp.portal.framework.MockitoTestSuite;
@@ -84,7 +82,7 @@ public class SchedulerControllerTest {
AdminRolesService adminRolesService;
@InjectMocks
- SchedulerController schedulerController = new SchedulerController();
+ SchedulerController schedulerController;
@Before
public void setup() {
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SharedContextRestControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SharedContextRestControllerTest.java
index 1607f423..49cccae5 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SharedContextRestControllerTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SharedContextRestControllerTest.java
@@ -38,24 +38,19 @@ package org.onap.portalapp.portal.controller;
*/
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import java.io.IOException;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.drools.core.command.assertion.AssertEquals;
import org.json.JSONObject;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -64,24 +59,15 @@ import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.onap.portalapp.portal.controller.SharedContextRestClient;
-import org.onap.portalapp.portal.controller.SharedContextTestProperties;
import org.onap.portalapp.portal.core.MockEPUser;
-import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
import org.onap.portalapp.portal.domain.SharedContext;
+import org.onap.portalapp.portal.exceptions.NotValidDataException;
import org.onap.portalapp.portal.framework.MockitoTestSuite;
-import org.onap.portalapp.portal.scheduler.SchedulerProperties;
import org.onap.portalapp.portal.service.SharedContextService;
import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
-import org.onap.portalsdk.core.util.SystemProperties;
-import org.onap.portalsdk.core.web.support.UserUtils;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Tests the endpoints exposed by the Shared Context controller in Portal.
@@ -95,7 +81,7 @@ public class SharedContextRestControllerTest {
SharedContextService contextService;
@InjectMocks
- SharedContextRestController sharedContextRestController=new SharedContextRestController();
+ SharedContextRestController sharedContextRestController=new SharedContextRestController(contextService);
@Before
public void setup() {
@@ -220,11 +206,31 @@ public class SharedContextRestControllerTest {
public void getContextTestWithException() throws Exception{
sharedContextRestController.getContext(mockedRequest, null,null);
}
+
+ @Test(expected=NotValidDataException.class)
+ public void getContextTestNotValidDataException() throws Exception{
+ sharedContextRestController.getContext(mockedRequest, "<script>alert(\"hellox worldss\");</script>","test");
+ }
+
+ @Test(expected=NotValidDataException.class)
+ public void getContextTest2NotValidDataException() throws Exception{
+ sharedContextRestController.getContext(mockedRequest, "test","“><script>alert(“XSS”)</script>");
+ }
+
+ @Test(expected=NotValidDataException.class)
+ public void getContextTest3NotValidDataException() throws Exception{
+ sharedContextRestController.getContext(mockedRequest, "<ScRipT>alert(\"XSS\");</ScRipT>","“><script>alert(“XSS”)</script>");
+ }
- @Test(expected=Exception.class)
+ @Test(expected= Exception.class)
public void getUserContextTest() throws Exception{
sharedContextRestController.getUserContext(mockedRequest, null);
}
+
+ @Test(expected= NotValidDataException.class)
+ public void getUserContextXSSTest() throws Exception{
+ sharedContextRestController.getUserContext(mockedRequest, "<svg><script x:href='https://dl.dropbox.com/u/13018058/js.js' {Opera}");
+ }
@Test
public void getUserContextTestWithContext() throws Exception{
@@ -257,6 +263,16 @@ public class SharedContextRestControllerTest {
Mockito.when(contextService.getSharedContext(Matchers.any(),Matchers.any())).thenReturn(sharedContext);
sharedContextRestController.checkContext(mockedRequest, null,null);
}
+
+ @Test(expected=NotValidDataException.class)
+ public void checkContextTestWithContextXSSl() throws Exception{
+ SharedContext sharedContext=new SharedContext();
+ sharedContext.setContext_id("test_contextid");
+ sharedContext.setCkey("test_ckey");
+ Mockito.when(contextService.getSharedContext(Matchers.any(),Matchers.any())).thenReturn(sharedContext);
+ sharedContextRestController.checkContext(mockedRequest,
+ "<ScRipT 5-0*3+9/3=>prompt(1)</ScRipT giveanswerhere=?","<script>alert(123);</script>");
+ }
@Test
public void removeContextTest() throws Exception{
@@ -283,6 +299,20 @@ public class SharedContextRestControllerTest {
assertNotNull(actual);
}
+
+ @Test(expected=NotValidDataException.class)
+ public void removeContextTestWithContextXSS() throws Exception{
+ SharedContext sharedContext=new SharedContext();
+ sharedContext.setContext_id("test_contextid");
+ sharedContext.setCkey("test_ckey");
+ Mockito.when(contextService.getSharedContext(Matchers.any(),Matchers.any())).thenReturn(sharedContext);
+
+ //Mockito.when(contextService.deleteSharedContext(sharedContext));
+ String actual=sharedContextRestController.removeContext(mockedRequest,
+ "<script>alert(“XSS”)</script> ","<script>alert(/XSS/)</script>");
+ assertNotNull(actual);
+
+ }
@Test(expected=Exception.class)
public void clearContextTestwithContextIdNull() throws Exception{
@@ -293,6 +323,16 @@ public class SharedContextRestControllerTest {
assertNotNull(actual);
}
+
+ @Test(expected=NotValidDataException.class)
+ public void clearContextTestwithContextXSS() throws Exception{
+
+ Mockito.when(contextService.deleteSharedContexts(Matchers.any())).thenReturn(12);
+
+ String actual=sharedContextRestController.clearContext(mockedRequest,"<script>alert(123)</script>");
+ assertNotNull(actual);
+
+ }
@Test
public void clearContextTest() throws Exception{
@@ -350,4 +390,27 @@ public class SharedContextRestControllerTest {
String actual=sharedContextRestController.setContext(mockedRequest,testUserJson.toString());
}
+
+ @Test(expected=NotValidDataException.class)
+ public void setContextTestWithContextXSS() throws Exception{
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String, Object> userData = new HashMap<String, Object>();
+ userData.put("context_id", "test_contextId");
+ userData.put("ckey", "<script>alert(‘XSS’)</script>");
+ userData.put("cvalue", "test_cvalue");
+ //String testUserJson=Matchers.anyString();
+ JSONObject testUserJson = new JSONObject();
+ testUserJson.put("context_id", "test1ContextId");
+ testUserJson.put("ckey", "testCkey");
+ testUserJson.put("cvalue", "<script>alert(‘XSS’)</script>");
+ Map<String, Object> userData1 = mapper.readValue(testUserJson.toString(), Map.class);
+ SharedContext sharedContext=new SharedContext();
+ sharedContext.setContext_id("test_contextid");
+ sharedContext.setCkey("test_ckey");
+ Mockito.when(contextService.getSharedContext(Matchers.any(),Matchers.any())).thenReturn(sharedContext);
+ // Mockito.when(mapper.readValue("true", Map.class)).thenReturn(userData);
+ String actual=sharedContextRestController.setContext(mockedRequest,testUserJson.toString());
+
+ }
+
}
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsControllerTest.java
index c6bd8001..f69ac99e 100644
--- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsControllerTest.java
+++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsControllerTest.java
@@ -68,7 +68,7 @@ import org.springframework.web.client.RestClientException;
public class WidgetsControllerTest extends MockitoTestSuite{
@InjectMocks
- WidgetsController widgetsController = new WidgetsController();
+ WidgetsController widgetsController;
@Mock
private AdminRolesService rolesService;
@@ -150,7 +150,7 @@ public class WidgetsControllerTest extends MockitoTestSuite{
OnboardingWidget onboardingWidget=new OnboardingWidget();
onboardingWidget.id=12L;
onboardingWidget.normalize();
- //Mockito.doNothing().when(onboardingWidget).normalize();
+ //Mockito.doNothing().when(onboardingWidget).normalize();
FieldsValidator expectedFieldValidator = new FieldsValidator();
List<FieldName> fields = new ArrayList<>();
@@ -161,6 +161,24 @@ public class WidgetsControllerTest extends MockitoTestSuite{
actualFieldsValidator = widgetsController.putOnboardingWidget(mockedRequest, 12L, onboardingWidget, mockedResponse);
}
+
+ @Test
+ public void putOnboardingWidgetXSSTest() {
+ FieldsValidator actualFieldsValidator = null;
+ EPUser user = mockUser.mockEPUser();
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ OnboardingWidget onboardingWidget=new OnboardingWidget();
+ onboardingWidget.id=12L;
+ onboardingWidget.name = "<script>alert(/XSS”)</script>";
+ onboardingWidget.normalize();
+ FieldsValidator expectedFieldValidator = new FieldsValidator();
+ expectedFieldValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE);
+ Mockito.when(widgetService.setOnboardingWidget(user, onboardingWidget)).thenReturn(expectedFieldValidator);
+ actualFieldsValidator = widgetsController.putOnboardingWidget(mockedRequest, 12L, onboardingWidget, mockedResponse);
+
+ assertEquals(expectedFieldValidator, actualFieldsValidator);
+
+ }
@Test
public void putOnboardingWidgetWithUserPermissionTest() {
@@ -172,7 +190,7 @@ public class WidgetsControllerTest extends MockitoTestSuite{
OnboardingWidget onboardingWidget=new OnboardingWidget();
onboardingWidget.id=12L;
onboardingWidget.normalize();
- //Mockito.doNothing().when(onboardingWidget).normalize();
+ //Mockito.doNothing().when(onboardingWidget).normalize();
FieldsValidator expectedFieldValidator = new FieldsValidator();
List<FieldName> fields = new ArrayList<>();
@@ -209,6 +227,31 @@ public class WidgetsControllerTest extends MockitoTestSuite{
assertEquals(expectedFieldValidator.getErrorCode(), actualFieldsValidator.getErrorCode());
assertEquals(expectedFieldValidator.getFields(), actualFieldsValidator.getFields());
}
+
+ @Test
+ public void postOnboardingWidgetXSSTest(){
+ EPUser user=mockUser.mockEPUser();
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ FieldsValidator actualFieldsValidator = null;
+ Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user);
+ Mockito.when(rolesService.isSuperAdmin(user)).thenReturn(true);
+ Mockito.when(rolesService.isAccountAdmin(user)).thenReturn(true);
+ OnboardingWidget onboardingWidget=new OnboardingWidget();
+ onboardingWidget.id=12L;
+ onboardingWidget.appName="<script>alert(/XSS”)</script>";
+ onboardingWidget.normalize();
+ FieldsValidator expectedFieldValidator = new FieldsValidator();
+ List<FieldName> fields = new ArrayList<>();
+
+ expectedFieldValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE);
+ expectedFieldValidator.setFields(fields);
+ expectedFieldValidator.setErrorCode(null);
+ Mockito.when(widgetService.setOnboardingWidget(user, onboardingWidget)).thenReturn(expectedFieldValidator);
+ actualFieldsValidator = widgetsController.postOnboardingWidget(mockedRequest, onboardingWidget, mockedResponse);
+ assertEquals(expectedFieldValidator.getHttpStatusCode(), actualFieldsValidator.getHttpStatusCode());
+ assertEquals(expectedFieldValidator.getErrorCode(), actualFieldsValidator.getErrorCode());
+ assertEquals(expectedFieldValidator.getFields(), actualFieldsValidator.getFields());
+ }
@Test
public void postOnboardingWidgetTestwiThoutUserPermission() {
@@ -218,7 +261,7 @@ public class WidgetsControllerTest extends MockitoTestSuite{
OnboardingWidget onboardingWidget=new OnboardingWidget();
onboardingWidget.id=12L;
onboardingWidget.normalize();
- //Mockito.doNothing().when(onboardingWidget).normalize();
+ //Mockito.doNothing().when(onboardingWidget).normalize();
FieldsValidator expectedFieldValidator = new FieldsValidator();
List<FieldName> fields = new ArrayList<>();