From 592ce20ec359928373de2e7f06214c8f8ad73c20 Mon Sep 17 00:00:00 2001
From: RehanRaza
Date: Tue, 14 Jan 2020 10:42:52 +0100
Subject: [PATCH] Fix formatting in the dashboard
Change-Id: I3e7718fee18e38697aa1ac4ac1f08d6aee499d92
Signed-off-by: RehanRaza
---
.../webapp-backend/eclipse-formatter.xml | 0
dashboard/webapp-backend/pom.xml | 28 ++
.../ric/portal/dashboard/DashboardApplication.java | 48 +--
.../ric/portal/dashboard/DashboardConstants.java | 36 +-
.../ric/portal/dashboard/DashboardUserManager.java | 283 ++++++++-------
.../dashboard/config/AdminConfiguration.java | 32 +-
.../dashboard/config/PortalApiConfiguration.java | 40 +--
.../dashboard/config/SpringContextCache.java | 16 +-
.../dashboard/config/SwaggerConfiguration.java | 48 +--
.../dashboard/config/WebSecurityConfiguration.java | 132 +++----
.../CustomResponseEntityExceptionHandler.java | 72 ++--
.../dashboard/controller/Html5PathsController.java | 53 +--
.../dashboard/controller/PolicyController.java | 237 +++++++------
.../controller/SimpleErrorController.java | 63 ++--
.../dashboard/k8sapi/SimpleKubernetesClient.java | 35 +-
.../portal/dashboard/model/EcompUserDetails.java | 80 ++---
.../ric/portal/dashboard/model/ErrorTransport.java | 206 +++++------
.../ric/portal/dashboard/model/PolicyInfo.java | 12 +-
.../portal/dashboard/model/PolicyInstances.java | 2 +-
.../ric/portal/dashboard/model/PolicyType.java | 48 +--
.../ric/portal/dashboard/model/PolicyTypes.java | 2 +-
.../portal/dashboard/model/SuccessTransport.java | 80 ++---
.../dashboard/policyagentapi/PolicyAgentApi.java | 6 +-
.../policyagentapi/PolicyAgentApiImpl.java | 65 ++--
.../dashboard/portalapi/IPortalSdkDecryptor.java | 24 +-
.../dashboard/portalapi/PortalAuthManager.java | 150 ++++----
.../portalapi/PortalAuthenticationFilter.java | 378 ++++++++++-----------
.../portalapi/PortalRestCentralServiceImpl.java | 74 ++--
.../dashboard/portalapi/PortalSdkDecryptorAes.java | 8 +-
.../dashboard/portalapi/PortalSdkDecryptorPkc.java | 6 +-
.../dashboard/util/HttpsURLConnectionUtils.java | 74 ++--
.../ric/portal/dashboard/DashboardTestServer.java | 38 +--
.../config/PolicyControllerMockConfiguration.java | 276 +++++++--------
.../config/PortalApIMockConfiguration.java | 66 ++--
.../config/WebSecurityMockConfiguration.java | 66 ++--
.../controller/AbstractControllerTest.java | 120 +++----
.../dashboard/controller/DefaultContextTest.java | 14 +-
.../controller/PortalRestCentralServiceTest.java | 139 ++++----
38 files changed, 1541 insertions(+), 1516 deletions(-)
rename policy-agent/java-formatter.xml => dashboard/webapp-backend/eclipse-formatter.xml (100%)
diff --git a/policy-agent/java-formatter.xml b/dashboard/webapp-backend/eclipse-formatter.xml
similarity index 100%
rename from policy-agent/java-formatter.xml
rename to dashboard/webapp-backend/eclipse-formatter.xml
diff --git a/dashboard/webapp-backend/pom.xml b/dashboard/webapp-backend/pom.xml
index 80bb585f..f089180e 100644
--- a/dashboard/webapp-backend/pom.xml
+++ b/dashboard/webapp-backend/pom.xml
@@ -36,6 +36,8 @@ limitations under the License.
2.9.22.7.1
+ 2.8.1
+ 1.18.00
@@ -175,6 +177,32 @@ limitations under the License.
org.springframework.bootspring-boot-maven-plugin
+
+ net.revelc.code.formatter
+ formatter-maven-plugin
+ ${formatter-maven-plugin.version}
+
+ ${project.basedir}/eclipse-formatter.xml
+
+
+
+
+ com.diffplug.spotless
+ spotless-maven-plugin
+ ${spotless-maven-plugin.version}
+
+
+
+
+ com,java,javax,org
+
+
+
+
+ org.codehaus.mojo
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardApplication.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardApplication.java
index 333c5322..2550b8ed 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardApplication.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardApplication.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -34,27 +34,27 @@ import org.springframework.context.annotation.ComponentScan;
@ComponentScan("org.oransc.ric.portal.dashboard")
public class DashboardApplication {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
-
- public static void main(String[] args) throws IOException {
- SpringApplication.run(DashboardApplication.class, args);
- // Ensure this appears on the console by using level WARN
- logger.warn("main: version '{}' successful start",
- getImplementationVersion(MethodHandles.lookup().lookupClass()));
- }
-
- /**
- * Gets version details for the specified class.
- *
- * @param clazz
- * Class to get the version
- *
- * @return the value of the MANIFEST.MF property Implementation-Version as
- * written by maven when packaged in a jar; 'unknown' otherwise.
- */
- public static String getImplementationVersion(Class> clazz) {
- String classPath = clazz.getResource(clazz.getSimpleName() + ".class").toString();
- return classPath.startsWith("jar") ? clazz.getPackage().getImplementationVersion() : "unknown-not-jar";
- }
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ public static void main(String[] args) throws IOException {
+ SpringApplication.run(DashboardApplication.class, args);
+ // Ensure this appears on the console by using level WARN
+ logger.warn("main: version '{}' successful start",
+ getImplementationVersion(MethodHandles.lookup().lookupClass()));
+ }
+
+ /**
+ * Gets version details for the specified class.
+ *
+ * @param clazz
+ * Class to get the version
+ *
+ * @return the value of the MANIFEST.MF property Implementation-Version as
+ * written by maven when packaged in a jar; 'unknown' otherwise.
+ */
+ public static String getImplementationVersion(Class> clazz) {
+ String classPath = clazz.getResource(clazz.getSimpleName() + ".class").toString();
+ return classPath.startsWith("jar") ? clazz.getPackage().getImplementationVersion() : "unknown-not-jar";
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardConstants.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardConstants.java
index b82aa647..4b5d9a4a 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardConstants.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardConstants.java
@@ -21,24 +21,24 @@ package org.oransc.ric.portal.dashboard;
public abstract class DashboardConstants {
- private DashboardConstants() {
- // Sonar insists on hiding the constructor
- }
+ private DashboardConstants() {
+ // Sonar insists on hiding the constructor
+ }
- public static final String ENDPOINT_PREFIX = "/api";
- // Factor out method names used in multiple controllers
- public static final String VERSION_METHOD = "version";
- public static final String APP_NAME_AC = "AC";
- public static final String APP_NAME_MC = "MC";
- // The role names are defined by ONAP Portal.
- // The prefix "ROLE_" is required by Spring.
- // These are used in Java code annotations that require constants.
- public static final String ROLE_NAME_STANDARD = "Standard_User";
- public static final String ROLE_NAME_ADMIN = "System_Administrator";
- private static final String ROLE_PREFIX = "ROLE_";
- public static final String ROLE_ADMIN = ROLE_PREFIX + ROLE_NAME_ADMIN;
- public static final String ROLE_STANDARD = ROLE_PREFIX + ROLE_NAME_STANDARD;
- public static final String POLICY_CONTROLLER_USERNAME = "admin";
- public static final String POLICY_CONTROLLER_PASSWORD = "Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U";
+ public static final String ENDPOINT_PREFIX = "/api";
+ // Factor out method names used in multiple controllers
+ public static final String VERSION_METHOD = "version";
+ public static final String APP_NAME_AC = "AC";
+ public static final String APP_NAME_MC = "MC";
+ // The role names are defined by ONAP Portal.
+ // The prefix "ROLE_" is required by Spring.
+ // These are used in Java code annotations that require constants.
+ public static final String ROLE_NAME_STANDARD = "Standard_User";
+ public static final String ROLE_NAME_ADMIN = "System_Administrator";
+ private static final String ROLE_PREFIX = "ROLE_";
+ public static final String ROLE_ADMIN = ROLE_PREFIX + ROLE_NAME_ADMIN;
+ public static final String ROLE_STANDARD = ROLE_PREFIX + ROLE_NAME_STANDARD;
+ public static final String POLICY_CONTROLLER_USERNAME = "admin";
+ public static final String POLICY_CONTROLLER_PASSWORD = "Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U";
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardUserManager.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardUserManager.java
index c5fd1014..ffb7396f 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardUserManager.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardUserManager.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -19,6 +19,11 @@
*/
package org.oransc.ric.portal.dashboard;
+import com.fasterxml.jackson.core.JsonGenerationException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
@@ -33,152 +38,146 @@ import org.onap.portalsdk.core.restful.domain.EcompUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.fasterxml.jackson.core.JsonGenerationException;
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
/**
* Provides simple user-management services.
- *
+ *
* This first implementation serializes user details to a file.
- *
+ *
* TODO: migrate to a database.
*/
public class DashboardUserManager {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
-
- // This default value is only useful for development and testing.
- public static final String USER_FILE_PATH = "dashboard-users.json";
-
- private final File userFile;
- private final List users;
-
- /**
- * Development/test-only constructor that uses default file path.
- *
- * @param clear
- * If true, start empty and remove any existing file.
- *
- * @throws IOException
- * On file error
- */
- public DashboardUserManager(boolean clear) throws IOException {
- this(USER_FILE_PATH);
- if (clear) {
- logger.debug("ctor: removing file {}", userFile.getAbsolutePath());
- File f = new File(DashboardUserManager.USER_FILE_PATH);
- if (f.exists())
- f.delete();
- users.clear();
- }
- }
-
- /**
- * Constructur that accepts a file path
- *
- * @param userFilePath
- * File path
- * @throws IOException
- * If file cannot be read
- */
- public DashboardUserManager(final String userFilePath) throws IOException {
- logger.debug("ctor: userfile {}", userFilePath);
- if (userFilePath == null)
- throw new IllegalArgumentException("Missing or empty user file property");
- userFile = new File(userFilePath);
- logger.debug("ctor: managing users in file {}", userFile.getAbsolutePath());
- if (userFile.exists()) {
- final ObjectMapper mapper = new ObjectMapper();
- users = mapper.readValue(userFile, new TypeReference>() {
- });
- } else {
- users = new ArrayList<>();
- }
- }
-
- /**
- * Gets the current users.
- *
- * @return List of EcompUser objects, possibly empty
- */
- public List getUsers() {
- return this.users;
- }
-
- /**
- * Gets the user with the specified login Id
- *
- * @param loginId
- * Desired login Id
- * @return User object; null if Id is not known
- */
- public EcompUser getUser(String loginId) {
- for (EcompUser u : this.users) {
- if (u.getLoginId().equals(loginId)) {
- logger.debug("getUser: match on {}", loginId);
- return u;
- }
- }
- logger.debug("getUser: no match on {}", loginId);
- return null;
- }
-
- private void saveUsers() throws JsonGenerationException, JsonMappingException, IOException {
- final ObjectMapper mapper = new ObjectMapper();
- mapper.writeValue(userFile, users);
- }
-
- /*
- * Allow at most one thread to create a user at one time.
- */
- public synchronized void createUser(EcompUser user) throws PortalAPIException {
- logger.debug("createUser: loginId is " + user.getLoginId());
- if (users.contains(user))
- throw new PortalAPIException("User exists: " + user.getLoginId());
- users.add(user);
- try {
- saveUsers();
- } catch (Exception ex) {
- throw new PortalAPIException("Save failed", ex);
- }
- }
-
- /*
- * Allow at most one thread to modify a user at one time. We still have
- * last-edit-wins of course.
- */
- public synchronized void updateUser(String loginId, EcompUser user) throws PortalAPIException {
- logger.debug("editUser: loginId is " + loginId);
- int index = users.indexOf(user);
- if (index < 0)
- throw new PortalAPIException("User does not exist: " + user.getLoginId());
- users.remove(index);
- users.add(user);
- try {
- saveUsers();
- } catch (Exception ex) {
- throw new PortalAPIException("Save failed", ex);
- }
- }
-
- // Test infrastructure
- public static void main(String[] args) throws Exception {
- DashboardUserManager dum = new DashboardUserManager(false);
- EcompUser user = new EcompUser();
- user.setActive(true);
- user.setLoginId("demo");
- user.setFirstName("First");
- user.setLastName("Last");
- EcompRole role = new EcompRole();
- role.setId(1L);
- role.setName(DashboardConstants.ROLE_NAME_ADMIN);
- Set roles = new HashSet<>();
- roles.add(role);
- user.setRoles(roles);
- dum.createUser(user);
- logger.debug("Created user {}", user);
- }
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ // This default value is only useful for development and testing.
+ public static final String USER_FILE_PATH = "dashboard-users.json";
+
+ private final File userFile;
+ private final List users;
+
+ /**
+ * Development/test-only constructor that uses default file path.
+ *
+ * @param clear
+ * If true, start empty and remove any existing file.
+ *
+ * @throws IOException
+ * On file error
+ */
+ public DashboardUserManager(boolean clear) throws IOException {
+ this(USER_FILE_PATH);
+ if (clear) {
+ logger.debug("ctor: removing file {}", userFile.getAbsolutePath());
+ File f = new File(DashboardUserManager.USER_FILE_PATH);
+ if (f.exists())
+ f.delete();
+ users.clear();
+ }
+ }
+
+ /**
+ * Constructur that accepts a file path
+ *
+ * @param userFilePath
+ * File path
+ * @throws IOException
+ * If file cannot be read
+ */
+ public DashboardUserManager(final String userFilePath) throws IOException {
+ logger.debug("ctor: userfile {}", userFilePath);
+ if (userFilePath == null)
+ throw new IllegalArgumentException("Missing or empty user file property");
+ userFile = new File(userFilePath);
+ logger.debug("ctor: managing users in file {}", userFile.getAbsolutePath());
+ if (userFile.exists()) {
+ final ObjectMapper mapper = new ObjectMapper();
+ users = mapper.readValue(userFile, new TypeReference>() {});
+ } else {
+ users = new ArrayList<>();
+ }
+ }
+
+ /**
+ * Gets the current users.
+ *
+ * @return List of EcompUser objects, possibly empty
+ */
+ public List getUsers() {
+ return this.users;
+ }
+
+ /**
+ * Gets the user with the specified login Id
+ *
+ * @param loginId
+ * Desired login Id
+ * @return User object; null if Id is not known
+ */
+ public EcompUser getUser(String loginId) {
+ for (EcompUser u : this.users) {
+ if (u.getLoginId().equals(loginId)) {
+ logger.debug("getUser: match on {}", loginId);
+ return u;
+ }
+ }
+ logger.debug("getUser: no match on {}", loginId);
+ return null;
+ }
+
+ private void saveUsers() throws JsonGenerationException, JsonMappingException, IOException {
+ final ObjectMapper mapper = new ObjectMapper();
+ mapper.writeValue(userFile, users);
+ }
+
+ /*
+ * Allow at most one thread to create a user at one time.
+ */
+ public synchronized void createUser(EcompUser user) throws PortalAPIException {
+ logger.debug("createUser: loginId is " + user.getLoginId());
+ if (users.contains(user))
+ throw new PortalAPIException("User exists: " + user.getLoginId());
+ users.add(user);
+ try {
+ saveUsers();
+ } catch (Exception ex) {
+ throw new PortalAPIException("Save failed", ex);
+ }
+ }
+
+ /*
+ * Allow at most one thread to modify a user at one time. We still have
+ * last-edit-wins of course.
+ */
+ public synchronized void updateUser(String loginId, EcompUser user) throws PortalAPIException {
+ logger.debug("editUser: loginId is " + loginId);
+ int index = users.indexOf(user);
+ if (index < 0)
+ throw new PortalAPIException("User does not exist: " + user.getLoginId());
+ users.remove(index);
+ users.add(user);
+ try {
+ saveUsers();
+ } catch (Exception ex) {
+ throw new PortalAPIException("Save failed", ex);
+ }
+ }
+
+ // Test infrastructure
+ public static void main(String[] args) throws Exception {
+ DashboardUserManager dum = new DashboardUserManager(false);
+ EcompUser user = new EcompUser();
+ user.setActive(true);
+ user.setLoginId("demo");
+ user.setFirstName("First");
+ user.setLastName("Last");
+ EcompRole role = new EcompRole();
+ role.setId(1L);
+ role.setName(DashboardConstants.ROLE_NAME_ADMIN);
+ Set roles = new HashSet<>();
+ roles.add(role);
+ user.setRoles(roles);
+ dum.createUser(user);
+ logger.debug("Created user {}", user);
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/AdminConfiguration.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/AdminConfiguration.java
index 696d74f6..8c646fec 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/AdminConfiguration.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/AdminConfiguration.java
@@ -38,21 +38,21 @@ import org.springframework.context.annotation.Profile;
@Profile("!test")
public class AdminConfiguration {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
-
- // Populated by the autowired constructor
- private final String userfile;
-
- @Autowired
- public AdminConfiguration(@Value("${userfile}") final String userfile) {
- logger.debug("ctor userfile '{}'", userfile);
- this.userfile = userfile;
- }
-
- @Bean
- // The bean (method) name must be globally unique
- public DashboardUserManager userManager() throws IOException {
- return new DashboardUserManager(userfile);
- }
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ // Populated by the autowired constructor
+ private final String userfile;
+
+ @Autowired
+ public AdminConfiguration(@Value("${userfile}") final String userfile) {
+ logger.debug("ctor userfile '{}'", userfile);
+ this.userfile = userfile;
+ }
+
+ @Bean
+ // The bean (method) name must be globally unique
+ public DashboardUserManager userManager() throws IOException {
+ return new DashboardUserManager(userfile);
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/PortalApiConfiguration.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/PortalApiConfiguration.java
index f318cad5..520f27ff 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/PortalApiConfiguration.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/PortalApiConfiguration.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -34,24 +34,24 @@ import org.springframework.context.annotation.Profile;
@Profile("!test")
public class PortalApiConfiguration {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- /**
- * Instantiates the EPSDK-FW servlet that implements the API called by Portal.
- * Needed because this app is not configured to scan the EPSDK-FW packages;
- * there's also a chance that Spring-Boot does not automatically
- * process @WebServlet annotations.
- *
- * @return Servlet registration bean for the Portal Rest API proxy servlet.
- */
- @Bean
- public ServletRegistrationBean portalApiProxyServletBean() {
- logger.debug("portalApiProxyServletBean");
- PortalRestAPIProxy servlet = new PortalRestAPIProxy();
- final ServletRegistrationBean servletBean = new ServletRegistrationBean<>(servlet,
- PortalApiConstants.API_PREFIX + "/*");
- servletBean.setName("PortalRestApiProxyServlet");
- return servletBean;
- }
+ /**
+ * Instantiates the EPSDK-FW servlet that implements the API called by Portal.
+ * Needed because this app is not configured to scan the EPSDK-FW packages;
+ * there's also a chance that Spring-Boot does not automatically
+ * process @WebServlet annotations.
+ *
+ * @return Servlet registration bean for the Portal Rest API proxy servlet.
+ */
+ @Bean
+ public ServletRegistrationBean portalApiProxyServletBean() {
+ logger.debug("portalApiProxyServletBean");
+ PortalRestAPIProxy servlet = new PortalRestAPIProxy();
+ final ServletRegistrationBean servletBean =
+ new ServletRegistrationBean<>(servlet, PortalApiConstants.API_PREFIX + "/*");
+ servletBean.setName("PortalRestApiProxyServlet");
+ return servletBean;
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/SpringContextCache.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/SpringContextCache.java
index 3a877824..a2f3d8f8 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/SpringContextCache.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/SpringContextCache.java
@@ -30,15 +30,15 @@ import org.springframework.stereotype.Component;
@Component
public class SpringContextCache implements ApplicationContextAware {
- private static ApplicationContext applicationContext = null;
+ private static ApplicationContext applicationContext = null;
- @Override
- public void setApplicationContext(final ApplicationContext appContext) throws BeansException {
- applicationContext = appContext;
- }
+ @Override
+ public void setApplicationContext(final ApplicationContext appContext) throws BeansException {
+ applicationContext = appContext;
+ }
- public static ApplicationContext getApplicationContext() {
- return applicationContext;
- }
+ public static ApplicationContext getApplicationContext() {
+ return applicationContext;
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/SwaggerConfiguration.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/SwaggerConfiguration.java
index b4bb0a31..435414af 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/SwaggerConfiguration.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/SwaggerConfiguration.java
@@ -40,29 +40,29 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
public class SwaggerConfiguration {
- /**
- * @return new Docket
- */
- @Bean
- public Docket api() {
- return new Docket(DocumentationType.SWAGGER_2).select() //
- .apis(RequestHandlerSelectors.basePackage(DashboardApplication.class.getPackage().getName())) //
- .paths(PathSelectors.any()) //
- .build() //
- .apiInfo(apiInfo());
- }
+ /**
+ * @return new Docket
+ */
+ @Bean
+ public Docket api() {
+ return new Docket(DocumentationType.SWAGGER_2).select() //
+ .apis(RequestHandlerSelectors.basePackage(DashboardApplication.class.getPackage().getName())) //
+ .paths(PathSelectors.any()) //
+ .build() //
+ .apiInfo(apiInfo());
+ }
- private ApiInfo apiInfo() {
- final String version = DashboardApplication.class.getPackage().getImplementationVersion();
- return new ApiInfoBuilder() //
- .title("RIC Dashboard backend") //
- .description("Proxies access to RIC services.")//
- .termsOfServiceUrl("Terms of service") //
- .contact(new Contact("RIC Dashboard Dev Team", //
- "http://no-docs-yet.org/", //
- "noreply@O-RAN-SC.org")) //
- .license("Apache 2.0 License").licenseUrl("http://www.apache.org/licenses/LICENSE-2.0") //
- .version(version == null ? "version not available" : version) //
- .build();
- }
+ private ApiInfo apiInfo() {
+ final String version = DashboardApplication.class.getPackage().getImplementationVersion();
+ return new ApiInfoBuilder() //
+ .title("RIC Dashboard backend") //
+ .description("Proxies access to RIC services.")//
+ .termsOfServiceUrl("Terms of service") //
+ .contact(new Contact("RIC Dashboard Dev Team", //
+ "http://no-docs-yet.org/", //
+ "noreply@O-RAN-SC.org")) //
+ .license("Apache 2.0 License").licenseUrl("http://www.apache.org/licenses/LICENSE-2.0") //
+ .version(version == null ? "version not available" : version) //
+ .build();
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/WebSecurityConfiguration.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/WebSecurityConfiguration.java
index 85a96d0a..b43f8a97 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/WebSecurityConfiguration.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/WebSecurityConfiguration.java
@@ -26,6 +26,7 @@ import java.lang.reflect.InvocationTargetException;
import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
import org.oransc.ric.portal.dashboard.DashboardUserManager;
+import org.oransc.ric.portal.dashboard.controller.PolicyController;
import org.oransc.ric.portal.dashboard.controller.SimpleErrorController;
import org.oransc.ric.portal.dashboard.portalapi.PortalAuthManager;
import org.oransc.ric.portal.dashboard.portalapi.PortalAuthenticationFilter;
@@ -43,7 +44,6 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
-import org.oransc.ric.portal.dashboard.controller.PolicyController;
@Configuration
@EnableWebSecurity
@@ -51,77 +51,77 @@ import org.oransc.ric.portal.dashboard.controller.PolicyController;
@Profile("!test")
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- // Although constructor arguments are recommended over field injection,
- // this results in fewer lines of code.
- @Value("${portalapi.security}")
- private Boolean portalapiSecurity;
- @Value("${portalapi.appname}")
- private String appName;
- @Value("${portalapi.username}")
- private String userName;
- @Value("${portalapi.password}")
- private String password;
- @Value("${portalapi.decryptor}")
- private String decryptor;
- @Value("${portalapi.usercookie}")
- private String userCookie;
+ // Although constructor arguments are recommended over field injection,
+ // this results in fewer lines of code.
+ @Value("${portalapi.security}")
+ private Boolean portalapiSecurity;
+ @Value("${portalapi.appname}")
+ private String appName;
+ @Value("${portalapi.username}")
+ private String userName;
+ @Value("${portalapi.password}")
+ private String password;
+ @Value("${portalapi.decryptor}")
+ private String decryptor;
+ @Value("${portalapi.usercookie}")
+ private String userCookie;
- @Autowired
- DashboardUserManager userManager;
+ @Autowired
+ DashboardUserManager userManager;
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- logger.debug("configure: portalapi.username {}", userName);
- // A chain of ".and()" always baffles me
- http.authorizeRequests().anyRequest().authenticated();
- http.headers().frameOptions().disable();
- http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
- http.addFilterBefore(portalAuthenticationFilterBean(), BasicAuthenticationFilter.class);
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ logger.debug("configure: portalapi.username {}", userName);
+ // A chain of ".and()" always baffles me
+ http.authorizeRequests().anyRequest().authenticated();
+ http.headers().frameOptions().disable();
+ http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
+ http.addFilterBefore(portalAuthenticationFilterBean(), BasicAuthenticationFilter.class);
+ }
- /**
- * Resource paths that do not require authentication, especially including
- * Swagger-generated documentation.
- */
- public static final String[] OPEN_PATHS = { //
- "/v2/api-docs", //
- "/swagger-resources/**", //
- "/swagger-ui.html", //
- "/webjars/**", //
- PortalApiConstants.API_PREFIX + "/**", //
- PolicyController.CONTROLLER_PATH + "/" + PolicyController.VERSION_METHOD, //
- SimpleErrorController.ERROR_PATH };
+ /**
+ * Resource paths that do not require authentication, especially including
+ * Swagger-generated documentation.
+ */
+ public static final String[] OPEN_PATHS = { //
+ "/v2/api-docs", //
+ "/swagger-resources/**", //
+ "/swagger-ui.html", //
+ "/webjars/**", //
+ PortalApiConstants.API_PREFIX + "/**", //
+ PolicyController.CONTROLLER_PATH + "/" + PolicyController.VERSION_METHOD, //
+ SimpleErrorController.ERROR_PATH};
- @Override
- public void configure(WebSecurity web) throws Exception {
- // This disables Spring security, but not the app's filter.
- web.ignoring().antMatchers(OPEN_PATHS);
- }
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ // This disables Spring security, but not the app's filter.
+ web.ignoring().antMatchers(OPEN_PATHS);
+ }
- @Bean
- public PortalAuthManager portalAuthManagerBean()
- throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException,
- IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
- return new PortalAuthManager(appName, userName, password, decryptor, userCookie);
- }
+ @Bean
+ public PortalAuthManager portalAuthManagerBean()
+ throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException,
+ IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
+ return new PortalAuthManager(appName, userName, password, decryptor, userCookie);
+ }
- /*
- * If this is annotated with @Bean, it is created automatically AND REGISTERED,
- * and Spring processes annotations in the source of the class. However, the
- * filter is added in the chain apparently in the wrong order. Alternately, with
- * no @Bean and added to the chain up in the configure() method in the desired
- * order, the ignoring() matcher pattern configured above causes Spring to
- * bypass this filter, which seems to me means the filter participates
- * correctly.
- */
- public PortalAuthenticationFilter portalAuthenticationFilterBean()
- throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException,
- IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
- PortalAuthenticationFilter portalAuthenticationFilter = new PortalAuthenticationFilter(portalapiSecurity,
- portalAuthManagerBean(), this.userManager);
- return portalAuthenticationFilter;
- }
+ /*
+ * If this is annotated with @Bean, it is created automatically AND REGISTERED,
+ * and Spring processes annotations in the source of the class. However, the
+ * filter is added in the chain apparently in the wrong order. Alternately, with
+ * no @Bean and added to the chain up in the configure() method in the desired
+ * order, the ignoring() matcher pattern configured above causes Spring to
+ * bypass this filter, which seems to me means the filter participates
+ * correctly.
+ */
+ public PortalAuthenticationFilter portalAuthenticationFilterBean()
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException,
+ IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
+ PortalAuthenticationFilter portalAuthenticationFilter =
+ new PortalAuthenticationFilter(portalapiSecurity, portalAuthManagerBean(), this.userManager);
+ return portalAuthenticationFilter;
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/CustomResponseEntityExceptionHandler.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/CustomResponseEntityExceptionHandler.java
index f5ecd104..52a51fb0 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/CustomResponseEntityExceptionHandler.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/CustomResponseEntityExceptionHandler.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -36,7 +36,7 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExcep
/**
* Catches certain exceptions. This controller advice factors out try-catch
* blocks in many controller methods.
- *
+ *
* Also see:
* https://www.baeldung.com/exception-handling-for-rest-with-spring
* https://www.springboottutorial.com/spring-boot-exception-handling-for-rest-services
@@ -44,39 +44,39 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExcep
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
- // Superclass has "logger" that is exposed here, so use a different name
- private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ // Superclass has "logger" that is exposed here, so use a different name
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- /**
- * Logs the error and generates a JSON response when a REST controller method
- * takes a RestClientResponseException. This is thrown by the Http client when a
- * remote method returns a non-2xx code. All the controller methods are proxies
- * in that they just forward the request along to a remote system, so if that
- * remote system fails, return 502 plus some details about the failure, rather
- * than the generic 500 that Spring-Boot will return on an uncaught exception.
- *
- * Why 502? I quote:
HTTP server received an invalid response from a
- * server it consulted when acting as a proxy or gateway.
- *
- * @param ex
- * The exception
- *
- * @param request
- * The original request
- *
- * @return A response entity with status code 502 plus some details in the body.
- */
- @ExceptionHandler({ RestClientResponseException.class })
- public final ResponseEntity handleProxyMethodException(Exception ex, WebRequest request) {
- // Capture the full stack trace in the log.
- log.error("handleProxyMethodException: request {}, exception {}", request.getDescription(false), ex);
- if (ex instanceof HttpStatusCodeException) {
- HttpStatusCodeException hsce = (HttpStatusCodeException) ex;
- return new ResponseEntity<>(new ErrorTransport(hsce.getRawStatusCode(), hsce.getResponseBodyAsString(),
- ex.toString(), request.getDescription(false)), HttpStatus.BAD_GATEWAY);
- } else {
- return new ResponseEntity<>(new ErrorTransport(500, ex), HttpStatus.BAD_GATEWAY);
- }
- }
+ /**
+ * Logs the error and generates a JSON response when a REST controller method
+ * takes a RestClientResponseException. This is thrown by the Http client when a
+ * remote method returns a non-2xx code. All the controller methods are proxies
+ * in that they just forward the request along to a remote system, so if that
+ * remote system fails, return 502 plus some details about the failure, rather
+ * than the generic 500 that Spring-Boot will return on an uncaught exception.
+ *
+ * Why 502? I quote:
HTTP server received an invalid response from a
+ * server it consulted when acting as a proxy or gateway.
+ *
+ * @param ex
+ * The exception
+ *
+ * @param request
+ * The original request
+ *
+ * @return A response entity with status code 502 plus some details in the body.
+ */
+ @ExceptionHandler({RestClientResponseException.class})
+ public final ResponseEntity handleProxyMethodException(Exception ex, WebRequest request) {
+ // Capture the full stack trace in the log.
+ log.error("handleProxyMethodException: request {}, exception {}", request.getDescription(false), ex);
+ if (ex instanceof HttpStatusCodeException) {
+ HttpStatusCodeException hsce = (HttpStatusCodeException) ex;
+ return new ResponseEntity<>(new ErrorTransport(hsce.getRawStatusCode(), hsce.getResponseBodyAsString(),
+ ex.toString(), request.getDescription(false)), HttpStatus.BAD_GATEWAY);
+ } else {
+ return new ResponseEntity<>(new ErrorTransport(500, ex), HttpStatus.BAD_GATEWAY);
+ }
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/Html5PathsController.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/Html5PathsController.java
index 7fb6e674..5d805381 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/Html5PathsController.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/Html5PathsController.java
@@ -8,9 +8,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -39,30 +39,31 @@ import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class Html5PathsController {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- /**
- * Forwards the browser to the index (main) page upon request of a known route.
- * This unfortunately requires duplication of the Angular route strings in the
- * path mappings on this method. Could switch to a regex pattern instead someday
- * if the routes change too often.
- *
- * https://stackoverflow.com/questions/44692781/configure-spring-boot-to-redirect-404-to-a-single-page-app
- *
- * @param request
- * HttpServletRequest
- * @param response
- * HttpServletResponse
- * @throws IOException
- * On error
- */
- @RequestMapping(method = { RequestMethod.OPTIONS, RequestMethod.GET }, //
- path = { "/policy", "/user" })
- public void forwardAngularRoutes(HttpServletRequest request, HttpServletResponse response) throws IOException {
- URL url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), "/index.html");
- if (logger.isDebugEnabled())
- logger.debug("forwardAngularRoutes: {} redirected to {}", request.getRequestURI(), url);
- response.sendRedirect(url.toString());
- }
+ /**
+ * Forwards the browser to the index (main) page upon request of a known route.
+ * This unfortunately requires duplication of the Angular route strings in the
+ * path mappings on this method. Could switch to a regex pattern instead someday
+ * if the routes change too often.
+ *
+ * https://stackoverflow.com/questions/44692781/configure-spring-boot-to-redirect-404-to-a-single-page-app
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @throws IOException
+ * On error
+ */
+ @RequestMapping(
+ method = {RequestMethod.OPTIONS, RequestMethod.GET}, //
+ path = {"/policy", "/user"})
+ public void forwardAngularRoutes(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ URL url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), "/index.html");
+ if (logger.isDebugEnabled())
+ logger.debug("forwardAngularRoutes: {} redirected to {}", request.getRequestURI(), url);
+ response.sendRedirect(url.toString());
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/PolicyController.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/PolicyController.java
index 529cd2af..5b909314 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/PolicyController.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/PolicyController.java
@@ -19,14 +19,16 @@
*/
package org.oransc.ric.portal.dashboard.controller;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import io.swagger.annotations.ApiOperation;
+
import java.lang.invoke.MethodHandles;
+import java.util.Collection;
import javax.servlet.http.HttpServletResponse;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-import org.oransc.ric.portal.dashboard.DashboardApplication;
import org.oransc.ric.portal.dashboard.DashboardConstants;
import org.oransc.ric.portal.dashboard.exceptions.HttpBadRequestException;
import org.oransc.ric.portal.dashboard.exceptions.HttpInternalServerErrorException;
@@ -34,7 +36,6 @@ import org.oransc.ric.portal.dashboard.exceptions.HttpNotFoundException;
import org.oransc.ric.portal.dashboard.exceptions.HttpNotImplementedException;
import org.oransc.ric.portal.dashboard.model.PolicyInstances;
import org.oransc.ric.portal.dashboard.model.PolicyTypes;
-import org.oransc.ric.portal.dashboard.model.SuccessTransport;
import org.oransc.ric.portal.dashboard.policyagentapi.PolicyAgentApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -52,8 +53,6 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
-import java.util.Collection;
-import io.swagger.annotations.ApiOperation;
/**
* Proxies calls from the front end to the Policy agent API.
@@ -67,117 +66,117 @@ import io.swagger.annotations.ApiOperation;
@RequestMapping(value = PolicyController.CONTROLLER_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
public class PolicyController {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- private static Gson gson = new GsonBuilder() //
- .serializeNulls() //
- .create(); //
-
- // Publish paths in constants so tests are easy to write
- public static final String CONTROLLER_PATH = DashboardConstants.ENDPOINT_PREFIX + "/policy";
- // Endpoints
- public static final String VERSION_METHOD = DashboardConstants.VERSION_METHOD;
- public static final String POLICY_TYPES_METHOD = "policytypes";
- public static final String POLICY_TYPE_ID_NAME = "policy_type_id";
- public static final String POLICIES_NAME = "policies";
- public static final String POLICY_INSTANCE_ID_NAME = "policy_instance_id";
-
- // Populated by the autowired constructor
- private final PolicyAgentApi policyAgentApi;
-
- @Autowired
- public PolicyController(final PolicyAgentApi policyAgentApi) {
- Assert.notNull(policyAgentApi, "API must not be null");
- this.policyAgentApi = policyAgentApi;
- logger.debug("ctor: configured with client type {}", policyAgentApi.getClass().getName());
- }
-
- /*
- * The fields are defined in the Policy Control Typescript interface.
- */
- @ApiOperation(value = "Gets the policy types from Near Realtime-RIC")
- @GetMapping(POLICY_TYPES_METHOD)
- @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
- public ResponseEntity getAllPolicyTypes(HttpServletResponse response) {
- logger.debug("getAllPolicyTypes");
- return this.policyAgentApi.getAllPolicyTypes();
- }
-
- @ApiOperation(value = "Returns the policy instances for the given policy type.")
- @GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME)
- @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
- public ResponseEntity getPolicyInstances(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString) {
- logger.debug("getPolicyInstances {}", policyTypeIdString);
-
- ResponseEntity response = this.policyAgentApi.getPolicyInstancesForType(policyTypeIdString);
- if (!response.getStatusCode().is2xxSuccessful()) {
- return new ResponseEntity<>(response.getStatusCode());
- }
- String json = gson.toJson(response.getBody());
- return new ResponseEntity<>(json, response.getStatusCode());
- }
-
- @ApiOperation(value = "Returns a policy instance of a type")
- @GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{" + POLICY_INSTANCE_ID_NAME
- + "}")
- @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
- public ResponseEntity getPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
- @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
- logger.debug("getPolicyInstance {}:{}", policyTypeIdString, policyInstanceId);
- return this.policyAgentApi.getPolicyInstance(policyInstanceId);
- }
-
- @ApiOperation(value = "Creates the policy instances for the given policy type.")
- @PutMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{" + POLICY_INSTANCE_ID_NAME
- + "}")
- @Secured({ DashboardConstants.ROLE_ADMIN })
- public ResponseEntity putPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
- @RequestParam(name = "ric", required = true) String ric,
- @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId, @RequestBody String instance) {
- logger.debug("putPolicyInstance typeId: {}, instanceId: {}, instance: {}", policyTypeIdString, policyInstanceId,
- instance);
- return this.policyAgentApi.putPolicy(policyTypeIdString, policyInstanceId, instance, ric);
- }
-
- @ApiOperation(value = "Deletes the policy instances for the given policy type.")
- @DeleteMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{"
- + POLICY_INSTANCE_ID_NAME + "}")
- @Secured({ DashboardConstants.ROLE_ADMIN })
- public void deletePolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
- @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
- logger.debug("deletePolicyInstance typeId: {}, instanceId: {}", policyTypeIdString, policyInstanceId);
- this.policyAgentApi.deletePolicy(policyInstanceId);
- }
-
- private void checkHttpError(String httpCode) {
- logger.debug("Http Response Code: {}", httpCode);
- if (httpCode.equals(String.valueOf(HttpStatus.NOT_FOUND.value()))) {
- logger.error("Caught HttpNotFoundException");
- throw new HttpNotFoundException("Not Found Exception");
- } else if (httpCode.equals(String.valueOf(HttpStatus.BAD_REQUEST.value()))) {
- logger.error("Caught HttpBadRequestException");
- throw new HttpBadRequestException("Bad Request Exception");
- } else if (httpCode.equals(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()))) {
- logger.error("Caught HttpInternalServerErrorException");
- throw new HttpInternalServerErrorException("Internal Server Error Exception");
- } else if (httpCode.equals(String.valueOf(HttpStatus.NOT_IMPLEMENTED.value()))) {
- logger.error("Caught HttpNotImplementedException");
- throw new HttpNotImplementedException("Not Implemented Exception");
- }
- }
-
- @ApiOperation(value = "Returns the rics supporting the given policy type.")
- @GetMapping("/rics")
- @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD })
- public ResponseEntity getRicsSupportingType(
- @RequestParam(name = "policyType", required = true) String supportingPolicyType) {
- logger.debug("getRicsSupportingType {}", supportingPolicyType);
-
- ResponseEntity> result = this.policyAgentApi.getRicsSupportingType(supportingPolicyType);
- if (!result.getStatusCode().is2xxSuccessful()) {
- return new ResponseEntity<>(result.getStatusCode());
- }
- String json = gson.toJson(result.getBody());
- return new ResponseEntity<>(json, result.getStatusCode());
- }
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static Gson gson = new GsonBuilder() //
+ .serializeNulls() //
+ .create(); //
+
+ // Publish paths in constants so tests are easy to write
+ public static final String CONTROLLER_PATH = DashboardConstants.ENDPOINT_PREFIX + "/policy";
+ // Endpoints
+ public static final String VERSION_METHOD = DashboardConstants.VERSION_METHOD;
+ public static final String POLICY_TYPES_METHOD = "policytypes";
+ public static final String POLICY_TYPE_ID_NAME = "policy_type_id";
+ public static final String POLICIES_NAME = "policies";
+ public static final String POLICY_INSTANCE_ID_NAME = "policy_instance_id";
+
+ // Populated by the autowired constructor
+ private final PolicyAgentApi policyAgentApi;
+
+ @Autowired
+ public PolicyController(final PolicyAgentApi policyAgentApi) {
+ Assert.notNull(policyAgentApi, "API must not be null");
+ this.policyAgentApi = policyAgentApi;
+ logger.debug("ctor: configured with client type {}", policyAgentApi.getClass().getName());
+ }
+
+ /*
+ * The fields are defined in the Policy Control Typescript interface.
+ */
+ @ApiOperation(value = "Gets the policy types from Near Realtime-RIC")
+ @GetMapping(POLICY_TYPES_METHOD)
+ @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD})
+ public ResponseEntity getAllPolicyTypes(HttpServletResponse response) {
+ logger.debug("getAllPolicyTypes");
+ return this.policyAgentApi.getAllPolicyTypes();
+ }
+
+ @ApiOperation(value = "Returns the policy instances for the given policy type.")
+ @GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME)
+ @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD})
+ public ResponseEntity getPolicyInstances(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString) {
+ logger.debug("getPolicyInstances {}", policyTypeIdString);
+
+ ResponseEntity response = this.policyAgentApi.getPolicyInstancesForType(policyTypeIdString);
+ if (!response.getStatusCode().is2xxSuccessful()) {
+ return new ResponseEntity<>(response.getStatusCode());
+ }
+ String json = gson.toJson(response.getBody());
+ return new ResponseEntity<>(json, response.getStatusCode());
+ }
+
+ @ApiOperation(value = "Returns a policy instance of a type")
+ @GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{" + POLICY_INSTANCE_ID_NAME
+ + "}")
+ @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD})
+ public ResponseEntity getPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
+ @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
+ logger.debug("getPolicyInstance {}:{}", policyTypeIdString, policyInstanceId);
+ return this.policyAgentApi.getPolicyInstance(policyInstanceId);
+ }
+
+ @ApiOperation(value = "Creates the policy instances for the given policy type.")
+ @PutMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{" + POLICY_INSTANCE_ID_NAME
+ + "}")
+ @Secured({DashboardConstants.ROLE_ADMIN})
+ public ResponseEntity putPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
+ @RequestParam(name = "ric", required = true) String ric,
+ @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId, @RequestBody String instance) {
+ logger.debug("putPolicyInstance typeId: {}, instanceId: {}, instance: {}", policyTypeIdString, policyInstanceId,
+ instance);
+ return this.policyAgentApi.putPolicy(policyTypeIdString, policyInstanceId, instance, ric);
+ }
+
+ @ApiOperation(value = "Deletes the policy instances for the given policy type.")
+ @DeleteMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{"
+ + POLICY_INSTANCE_ID_NAME + "}")
+ @Secured({DashboardConstants.ROLE_ADMIN})
+ public void deletePolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString,
+ @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) {
+ logger.debug("deletePolicyInstance typeId: {}, instanceId: {}", policyTypeIdString, policyInstanceId);
+ this.policyAgentApi.deletePolicy(policyInstanceId);
+ }
+
+ private void checkHttpError(String httpCode) {
+ logger.debug("Http Response Code: {}", httpCode);
+ if (httpCode.equals(String.valueOf(HttpStatus.NOT_FOUND.value()))) {
+ logger.error("Caught HttpNotFoundException");
+ throw new HttpNotFoundException("Not Found Exception");
+ } else if (httpCode.equals(String.valueOf(HttpStatus.BAD_REQUEST.value()))) {
+ logger.error("Caught HttpBadRequestException");
+ throw new HttpBadRequestException("Bad Request Exception");
+ } else if (httpCode.equals(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()))) {
+ logger.error("Caught HttpInternalServerErrorException");
+ throw new HttpInternalServerErrorException("Internal Server Error Exception");
+ } else if (httpCode.equals(String.valueOf(HttpStatus.NOT_IMPLEMENTED.value()))) {
+ logger.error("Caught HttpNotImplementedException");
+ throw new HttpNotImplementedException("Not Implemented Exception");
+ }
+ }
+
+ @ApiOperation(value = "Returns the rics supporting the given policy type.")
+ @GetMapping("/rics")
+ @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD})
+ public ResponseEntity getRicsSupportingType(
+ @RequestParam(name = "policyType", required = true) String supportingPolicyType) {
+ logger.debug("getRicsSupportingType {}", supportingPolicyType);
+
+ ResponseEntity> result = this.policyAgentApi.getRicsSupportingType(supportingPolicyType);
+ if (!result.getStatusCode().is2xxSuccessful()) {
+ return new ResponseEntity<>(result.getStatusCode());
+ }
+ String json = gson.toJson(result.getBody());
+ return new ResponseEntity<>(json, result.getStatusCode());
+ }
};
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/SimpleErrorController.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/SimpleErrorController.java
index e2248e64..63b78ec1 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/SimpleErrorController.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/SimpleErrorController.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -35,7 +35,6 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.ServletWebRequest;
-
import springfox.documentation.annotations.ApiIgnore;
/**
@@ -43,12 +42,12 @@ import springfox.documentation.annotations.ApiIgnore;
* context, including page not found, and redirects the caller to a custom error
* page. The caller is also redirected to this page if a REST controller takes
* an uncaught exception.
- *
+ *
* If trace is requested via request parameter ("?trace=true") and available,
* adds stack trace information to the standard JSON error response.
- *
+ *
* Excluded from Swagger API documentation.
- *
+ *
* https://stackoverflow.com/questions/25356781/spring-boot-remove-whitelabel-error-page
* https://www.baeldung.com/spring-boot-custom-error-page
*/
@@ -58,36 +57,36 @@ import springfox.documentation.annotations.ApiIgnore;
@RequestMapping(value = SimpleErrorController.ERROR_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
public class SimpleErrorController implements ErrorController {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- public static final String ERROR_PATH = "/error";
+ public static final String ERROR_PATH = "/error";
- private final ErrorAttributes errorAttributes;
+ private final ErrorAttributes errorAttributes;
- @Autowired
- public SimpleErrorController(ErrorAttributes errorAttributes) {
- this.errorAttributes = errorAttributes;
- }
+ @Autowired
+ public SimpleErrorController(ErrorAttributes errorAttributes) {
+ this.errorAttributes = errorAttributes;
+ }
- @Override
- public String getErrorPath() {
- logger.warn("getErrorPath");
- return ERROR_PATH;
- }
+ @Override
+ public String getErrorPath() {
+ logger.warn("getErrorPath");
+ return ERROR_PATH;
+ }
- @GetMapping
- public String handleError(HttpServletRequest request) {
- ServletWebRequest servletWebRequest = new ServletWebRequest(request);
- Throwable t = errorAttributes.getError(servletWebRequest);
- if (t != null)
- logger.warn("handleError", t);
- Map attributes = errorAttributes.getErrorAttributes(servletWebRequest, true);
- attributes.forEach((attribute, value) -> {
- logger.warn("handleError: {} -> {}", attribute, value);
- });
- // Return the name of the page INCLUDING suffix, which I guess is a "view" name.
- // Just "error" is not enough, but don't seem to need a ModelAndView object.
- return "error.html";
- }
+ @GetMapping
+ public String handleError(HttpServletRequest request) {
+ ServletWebRequest servletWebRequest = new ServletWebRequest(request);
+ Throwable t = errorAttributes.getError(servletWebRequest);
+ if (t != null)
+ logger.warn("handleError", t);
+ Map attributes = errorAttributes.getErrorAttributes(servletWebRequest, true);
+ attributes.forEach((attribute, value) -> {
+ logger.warn("handleError: {} -> {}", attribute, value);
+ });
+ // Return the name of the page INCLUDING suffix, which I guess is a "view" name.
+ // Just "error" is not enough, but don't seem to need a ModelAndView object.
+ return "error.html";
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/k8sapi/SimpleKubernetesClient.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/k8sapi/SimpleKubernetesClient.java
index bcfae626..d3add601 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/k8sapi/SimpleKubernetesClient.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/k8sapi/SimpleKubernetesClient.java
@@ -34,23 +34,22 @@ import org.springframework.web.util.DefaultUriBuilderFactory;
*/
public class SimpleKubernetesClient {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
-
- private final String k8sUrl;
-
- public SimpleKubernetesClient(String baseUrl) {
- logger.debug("ctor: baseUrl {}", baseUrl);
- k8sUrl = baseUrl;
- }
-
- public String listPods(String namespace) {
- logger.debug("listPods for namespace {}", namespace);
- String podsUrl = new DefaultUriBuilderFactory(k8sUrl.trim()).builder().pathSegment("v1")
- .pathSegment("namespaces").pathSegment(namespace.trim()).pathSegment("pods").build().normalize()
- .toString();
- RestTemplate rt = new RestTemplate();
- ResponseEntity podsResponse = rt.getForEntity(podsUrl, String.class);
- return podsResponse.getBody();
- }
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ private final String k8sUrl;
+
+ public SimpleKubernetesClient(String baseUrl) {
+ logger.debug("ctor: baseUrl {}", baseUrl);
+ k8sUrl = baseUrl;
+ }
+
+ public String listPods(String namespace) {
+ logger.debug("listPods for namespace {}", namespace);
+ String podsUrl = new DefaultUriBuilderFactory(k8sUrl.trim()).builder().pathSegment("v1")
+ .pathSegment("namespaces").pathSegment(namespace.trim()).pathSegment("pods").build().normalize().toString();
+ RestTemplate rt = new RestTemplate();
+ ResponseEntity podsResponse = rt.getForEntity(podsUrl, String.class);
+ return podsResponse.getBody();
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/EcompUserDetails.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/EcompUserDetails.java
index 7bc9f004..3a082062 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/EcompUserDetails.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/EcompUserDetails.java
@@ -32,54 +32,54 @@ import org.springframework.security.core.userdetails.UserDetails;
public class EcompUserDetails implements UserDetails {
- private static final long serialVersionUID = 1L;
- private final EcompUser ecompUser;
+ private static final long serialVersionUID = 1L;
+ private final EcompUser ecompUser;
- // This is the default Spring role-name prefix.
- private static final String ROLEP = "ROLE_";
+ // This is the default Spring role-name prefix.
+ private static final String ROLEP = "ROLE_";
- public EcompUserDetails(EcompUser ecompUser) {
- this.ecompUser = ecompUser;
- }
+ public EcompUserDetails(EcompUser ecompUser) {
+ this.ecompUser = ecompUser;
+ }
- /*
- * Gets a list of authorities (roles) for this user. To keep Spring happy, every
- * item has prefix ROLE_.
- */
- public Collection extends GrantedAuthority> getAuthorities() {
- List roleList = new ArrayList<>();
- Iterator roleIter = ecompUser.getRoles().iterator();
- while (roleIter.hasNext()) {
- EcompRole role = roleIter.next();
- // Add the prefix if the ONAP portal doesn't supply it.
- final String roleName = role.getName().startsWith(ROLEP) ? role.getName() : ROLEP + role.getName();
- roleList.add(new SimpleGrantedAuthority(roleName));
- }
- return roleList;
- }
+ /*
+ * Gets a list of authorities (roles) for this user. To keep Spring happy, every
+ * item has prefix ROLE_.
+ */
+ public Collection extends GrantedAuthority> getAuthorities() {
+ List roleList = new ArrayList<>();
+ Iterator roleIter = ecompUser.getRoles().iterator();
+ while (roleIter.hasNext()) {
+ EcompRole role = roleIter.next();
+ // Add the prefix if the ONAP portal doesn't supply it.
+ final String roleName = role.getName().startsWith(ROLEP) ? role.getName() : ROLEP + role.getName();
+ roleList.add(new SimpleGrantedAuthority(roleName));
+ }
+ return roleList;
+ }
- public String getPassword() {
- return null;
- }
+ public String getPassword() {
+ return null;
+ }
- public String getUsername() {
- return ecompUser.getLoginId();
- }
+ public String getUsername() {
+ return ecompUser.getLoginId();
+ }
- public boolean isAccountNonExpired() {
- return true;
- }
+ public boolean isAccountNonExpired() {
+ return true;
+ }
- public boolean isAccountNonLocked() {
- return true;
- }
+ public boolean isAccountNonLocked() {
+ return true;
+ }
- public boolean isCredentialsNonExpired() {
- return true;
- }
+ public boolean isCredentialsNonExpired() {
+ return true;
+ }
- public boolean isEnabled() {
- return ecompUser.isActive();
- }
+ public boolean isEnabled() {
+ return ecompUser.isActive();
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/ErrorTransport.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/ErrorTransport.java
index 516e3c8e..f1250c18 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/ErrorTransport.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/ErrorTransport.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -28,106 +28,106 @@ import java.time.Instant;
*/
public class ErrorTransport implements IDashboardResponse {
- private Instant timestamp;
- private Integer status;
- private String error;
- private String message;
- private String path;
-
- /**
- * Builds an empty object.
- */
- public ErrorTransport() {
- // no-arg constructor
- }
-
- /**
- * Convenience constructor for minimal value set.
- *
- * @param status
- * Integer value like 400
- * @param error
- * Error message
- */
- public ErrorTransport(int status, String error) {
- this(status, error, null, null);
- }
-
- /**
- * Convenience constructor for populating an error from an exception
- *
- * @param status
- * Integer value like 400
- * @param throwable
- * The caught exception/throwable to convert to String with
- * an upper bound on characters
- */
- public ErrorTransport(int status, Throwable throwable) {
- this.timestamp = Instant.now();
- this.status = status;
- final int enough = 256;
- String exString = throwable.toString();
- this.error = exString.length() > enough ? exString.substring(0, enough) : exString;
- }
-
- /**
- * Builds an object with all fields
- *
- * @param status
- * Integer value like 500
- * @param error
- * Explanation
- * @param message
- * Additional explanation
- * @param path
- * Requested path
- */
- public ErrorTransport(int status, String error, String message, String path) {
- this.timestamp = Instant.now();
- this.status = status;
- this.error = error;
- this.message = message;
- this.path = path;
- }
-
- public Integer getStatus() {
- return status;
- }
-
- public void setStatus(Integer status) {
- this.status = status;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String error) {
- this.message = error;
- }
-
- public Instant getTimestamp() {
- return timestamp;
- }
-
- public void setTimestamp(Instant timestamp) {
- this.timestamp = timestamp;
- }
-
- public String getError() {
- return error;
- }
-
- public void setError(String error) {
- this.error = error;
- }
-
- public String getPath() {
- return path;
- }
-
- public void setPath(String path) {
- this.path = path;
- }
+ private Instant timestamp;
+ private Integer status;
+ private String error;
+ private String message;
+ private String path;
+
+ /**
+ * Builds an empty object.
+ */
+ public ErrorTransport() {
+ // no-arg constructor
+ }
+
+ /**
+ * Convenience constructor for minimal value set.
+ *
+ * @param status
+ * Integer value like 400
+ * @param error
+ * Error message
+ */
+ public ErrorTransport(int status, String error) {
+ this(status, error, null, null);
+ }
+
+ /**
+ * Convenience constructor for populating an error from an exception
+ *
+ * @param status
+ * Integer value like 400
+ * @param throwable
+ * The caught exception/throwable to convert to String with
+ * an upper bound on characters
+ */
+ public ErrorTransport(int status, Throwable throwable) {
+ this.timestamp = Instant.now();
+ this.status = status;
+ final int enough = 256;
+ String exString = throwable.toString();
+ this.error = exString.length() > enough ? exString.substring(0, enough) : exString;
+ }
+
+ /**
+ * Builds an object with all fields
+ *
+ * @param status
+ * Integer value like 500
+ * @param error
+ * Explanation
+ * @param message
+ * Additional explanation
+ * @param path
+ * Requested path
+ */
+ public ErrorTransport(int status, String error, String message, String path) {
+ this.timestamp = Instant.now();
+ this.status = status;
+ this.error = error;
+ this.message = message;
+ this.path = path;
+ }
+
+ public Integer getStatus() {
+ return status;
+ }
+
+ public void setStatus(Integer status) {
+ this.status = status;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String error) {
+ this.message = error;
+ }
+
+ public Instant getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(Instant timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getError() {
+ return error;
+ }
+
+ public void setError(String error) {
+ this.error = error;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public void setPath(String path) {
+ this.path = path;
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInfo.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInfo.java
index ca1b79d4..30cfd2aa 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInfo.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInfo.java
@@ -26,16 +26,16 @@ import org.immutables.value.Value;
@Gson.TypeAdapters
public interface PolicyInfo {
- public String id();
+ public String id();
- public String type();
+ public String type();
- public String ric();
+ public String ric();
- public String json();
+ public String json();
- public String service();
+ public String service();
- public String lastModified();
+ public String lastModified();
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInstances.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInstances.java
index eb6b4555..c6faf9b1 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInstances.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInstances.java
@@ -23,6 +23,6 @@ import java.util.ArrayList;
public class PolicyInstances extends ArrayList {
- private static final long serialVersionUID = -928428052502491021L;
+ private static final long serialVersionUID = -928428052502491021L;
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyType.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyType.java
index ea51cc50..f0ca285b 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyType.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyType.java
@@ -23,35 +23,35 @@ import com.fasterxml.jackson.annotation.JsonProperty;
public class PolicyType {
- @JsonProperty("name")
- String name;
+ @JsonProperty("name")
+ String name;
- @JsonProperty("schema")
- String schema;
+ @JsonProperty("schema")
+ String schema;
- public PolicyType(String name, String schema) {
- this.name = name;
- this.schema = schema;
- }
+ public PolicyType(String name, String schema) {
+ this.name = name;
+ this.schema = schema;
+ }
- public String getName() {
- return name;
- }
+ public String getName() {
+ return name;
+ }
- public void setName(String name) {
- this.name = name;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public String getSchema() {
- return schema;
- }
+ public String getSchema() {
+ return schema;
+ }
- public void setSchema(String schema) {
- this.schema = schema;
- }
+ public void setSchema(String schema) {
+ this.schema = schema;
+ }
- @Override
- public String toString() {
- return "[name:" + name + ", schema:" + schema + "]";
- }
+ @Override
+ public String toString() {
+ return "[name:" + name + ", schema:" + schema + "]";
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyTypes.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyTypes.java
index 3165d1bc..43a6383e 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyTypes.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyTypes.java
@@ -23,6 +23,6 @@ import java.util.ArrayList;
public class PolicyTypes extends ArrayList {
- private static final long serialVersionUID = -928428052502491021L;
+ private static final long serialVersionUID = -928428052502491021L;
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/SuccessTransport.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/SuccessTransport.java
index 9e137890..65b39eb4 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/SuccessTransport.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/SuccessTransport.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -21,43 +21,43 @@ package org.oransc.ric.portal.dashboard.model;
public class SuccessTransport implements IDashboardResponse {
- private int status;
- private Object data;
-
- /**
- * Builds an empty object
- */
- public SuccessTransport() {
- // no-arg constructor
- }
-
- /**
- * Builds an object with the specified values.
- *
- * @param status
- * Status code
- * @param data
- * Data to transport
- */
- public SuccessTransport(int status, Object data) {
- this.status = status;
- this.data = data;
- }
-
- public int getStatus() {
- return status;
- }
-
- public void setStatus(int status) {
- this.status = status;
- }
-
- public Object getData() {
- return data;
- }
-
- public void setData(Object data) {
- this.data = data;
- }
+ private int status;
+ private Object data;
+
+ /**
+ * Builds an empty object
+ */
+ public SuccessTransport() {
+ // no-arg constructor
+ }
+
+ /**
+ * Builds an object with the specified values.
+ *
+ * @param status
+ * Status code
+ * @param data
+ * Data to transport
+ */
+ public SuccessTransport(int status, Object data) {
+ this.status = status;
+ this.data = data;
+ }
+
+ public int getStatus() {
+ return status;
+ }
+
+ public void setStatus(int status) {
+ this.status = status;
+ }
+
+ public Object getData() {
+ return data;
+ }
+
+ public void setData(Object data) {
+ this.data = data;
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApi.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApi.java
index 47add76a..4a26563a 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApi.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApi.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -35,7 +35,7 @@ public interface PolicyAgentApi {
public ResponseEntity getPolicyInstance(String id) throws RestClientException;
public ResponseEntity putPolicy(String policyTypeIdString, String policyInstanceId, String json, String ric)
- throws RestClientException;
+ throws RestClientException;
public void deletePolicy(String policyInstanceId) throws RestClientException;
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApiImpl.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApiImpl.java
index eb3f8368..af814b9d 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApiImpl.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApiImpl.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -19,12 +19,29 @@
*/
package org.oransc.ric.portal.dashboard.policyagentapi;
-import org.oransc.ric.portal.dashboard.DashboardConstants;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.google.gson.reflect.TypeToken;
+
+import java.lang.invoke.MethodHandles;
+import java.lang.reflect.Type;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import org.immutables.gson.Gson;
+import org.immutables.value.Value;
import org.oransc.ric.portal.dashboard.model.ImmutablePolicyInfo;
import org.oransc.ric.portal.dashboard.model.PolicyInfo;
import org.oransc.ric.portal.dashboard.model.PolicyInstances;
import org.oransc.ric.portal.dashboard.model.PolicyType;
import org.oransc.ric.portal.dashboard.model.PolicyTypes;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -32,26 +49,6 @@ import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-import java.lang.invoke.MethodHandles;
-import java.lang.reflect.Type;
-
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import com.google.gson.annotations.SerializedName;
-import com.google.gson.reflect.TypeToken;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.immutables.gson.Gson;
-import org.immutables.value.Value;
-
@Component("PolicyAgentApi")
public class PolicyAgentApiImpl implements PolicyAgentApi {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@@ -59,14 +56,14 @@ public class PolicyAgentApiImpl implements PolicyAgentApi {
RestTemplate restTemplate = new RestTemplate();
private static com.google.gson.Gson gson = new GsonBuilder() //
- .serializeNulls() //
- .create(); //
+ .serializeNulls() //
+ .create(); //
private final String urlPrefix;
@Autowired
public PolicyAgentApiImpl(
- @org.springframework.beans.factory.annotation.Value("${policycontroller.url.prefix}") final String urlPrefix) {
+ @org.springframework.beans.factory.annotation.Value("${policycontroller.url.prefix}") final String urlPrefix) {
logger.debug("ctor prefix '{}'", urlPrefix);
this.urlPrefix = urlPrefix;
}
@@ -114,8 +111,7 @@ public class PolicyAgentApiImpl implements PolicyAgentApi {
return new ResponseEntity<>(rsp.getStatusCode());
}
- Type listType = new TypeToken>() {
- }.getType();
+ Type listType = new TypeToken>() {}.getType();
List rspParsed = gson.fromJson(rsp.getBody(), listType);
PolicyInstances result = new PolicyInstances();
@@ -135,13 +131,13 @@ public class PolicyAgentApiImpl implements PolicyAgentApi {
@Override
public ResponseEntity putPolicy(String policyTypeIdString, String policyInstanceId, String json, String ric)
- throws RestClientException {
+ throws RestClientException {
String url = baseUrl() + "/policy?type={type}&instance={instance}&ric={ric}&service={service}";
Map uriVariables = Map.of( //
- "type", policyTypeIdString, //
- "instance", policyInstanceId, //
- "ric", ric, //
- "service", "dashboard");
+ "type", policyTypeIdString, //
+ "instance", policyInstanceId, //
+ "ric", ric, //
+ "service", "dashboard");
try {
this.restTemplate.put(url, json, uriVariables);
@@ -174,8 +170,7 @@ public class PolicyAgentApiImpl implements PolicyAgentApi {
Map uriVariables = Map.of("typeName", typeName);
String rsp = this.restTemplate.getForObject(url, String.class, uriVariables);
- Type listType = new TypeToken>() {
- }.getType();
+ Type listType = new TypeToken>() {}.getType();
List rspParsed = gson.fromJson(rsp, listType);
Collection result = new Vector<>(rspParsed.size());
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/IPortalSdkDecryptor.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/IPortalSdkDecryptor.java
index 34d80c94..552d7836 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/IPortalSdkDecryptor.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/IPortalSdkDecryptor.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -27,15 +27,15 @@ import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
*/
public interface IPortalSdkDecryptor {
- /**
- * Decrypts the specified value using a known key.
- *
- * @param cipherText
- * Encrypted value
- * @return Clear text on success, null otherwise.
- * @throws CipherUtilException
- * if any decryption step fails
- */
- String decrypt(String cipherText) throws CipherUtilException;
+ /**
+ * Decrypts the specified value using a known key.
+ *
+ * @param cipherText
+ * Encrypted value
+ * @return Clear text on success, null otherwise.
+ * @throws CipherUtilException
+ * if any decryption step fails
+ */
+ String decrypt(String cipherText) throws CipherUtilException;
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthManager.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthManager.java
index dc70f7e7..f4daa5c2 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthManager.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthManager.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -38,83 +38,83 @@ import org.slf4j.LoggerFactory;
*/
public class PortalAuthManager {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- final Map credentialsMap;
- private final IPortalSdkDecryptor portalSdkDecryptor;
- private final String userIdCookieName;
+ final Map credentialsMap;
+ private final IPortalSdkDecryptor portalSdkDecryptor;
+ private final String userIdCookieName;
- public PortalAuthManager(final String appName, final String username, final String password,
- final String decryptorClassName, final String userCookie)
- throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException,
- InvocationTargetException, NoSuchMethodException, SecurityException {
- credentialsMap = new HashMap<>();
- credentialsMap.put(IPortalRestCentralService.CREDENTIALS_APP, appName);
- credentialsMap.put(IPortalRestCentralService.CREDENTIALS_USER, username);
- credentialsMap.put(IPortalRestCentralService.CREDENTIALS_PASS, password);
- this.userIdCookieName = userCookie;
- // Instantiate here so configuration errors are detected at app-start time
- logger.debug("ctor: using decryptor class {}", decryptorClassName);
- Class> decryptorClass = Class.forName(decryptorClassName);
- portalSdkDecryptor = (IPortalSdkDecryptor) decryptorClass.getDeclaredConstructor().newInstance();
- }
+ public PortalAuthManager(final String appName, final String username, final String password,
+ final String decryptorClassName, final String userCookie)
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException,
+ InvocationTargetException, NoSuchMethodException, SecurityException {
+ credentialsMap = new HashMap<>();
+ credentialsMap.put(IPortalRestCentralService.CREDENTIALS_APP, appName);
+ credentialsMap.put(IPortalRestCentralService.CREDENTIALS_USER, username);
+ credentialsMap.put(IPortalRestCentralService.CREDENTIALS_PASS, password);
+ this.userIdCookieName = userCookie;
+ // Instantiate here so configuration errors are detected at app-start time
+ logger.debug("ctor: using decryptor class {}", decryptorClassName);
+ Class> decryptorClass = Class.forName(decryptorClassName);
+ portalSdkDecryptor = (IPortalSdkDecryptor) decryptorClass.getDeclaredConstructor().newInstance();
+ }
- /**
- * @return A map of key-value pairs with application name, user name and
- * password.
- */
- public Map getAppCredentials() {
- return credentialsMap;
- }
+ /**
+ * @return A map of key-value pairs with application name, user name and
+ * password.
+ */
+ public Map getAppCredentials() {
+ return credentialsMap;
+ }
- /**
- * Searches the request for a cookie with the specified name.
- *
- * @param request
- * HttpServletRequest
- * @param cookieName
- * Cookie name
- * @return Cookie, or null if not found.
- */
- private Cookie getCookie(HttpServletRequest request, String cookieName) {
- Cookie[] cookies = request.getCookies();
- if (cookies != null)
- for (Cookie cookie : cookies)
- if (cookie.getName().equals(cookieName))
- return cookie;
- return null;
- }
+ /**
+ * Searches the request for a cookie with the specified name.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param cookieName
+ * Cookie name
+ * @return Cookie, or null if not found.
+ */
+ private Cookie getCookie(HttpServletRequest request, String cookieName) {
+ Cookie[] cookies = request.getCookies();
+ if (cookies != null)
+ for (Cookie cookie : cookies)
+ if (cookie.getName().equals(cookieName))
+ return cookie;
+ return null;
+ }
- /**
- * Validates whether the ECOMP Portal sign-on process has completed. Checks for
- * the ECOMP cookie first, then the user cookie.
- *
- * @param request
- * HttpServletRequest
- * @return User ID if the ECOMP cookie is present and the sign-on process
- * established a user ID; else null.
- */
- public String validateEcompSso(HttpServletRequest request) {
- // Check ECOMP Portal cookie
- Cookie ep = getCookie(request, PortalApiConstants.EP_SERVICE);
- if (ep == null) {
- logger.debug("validateEcompSso: cookie not found: {}", PortalApiConstants.EP_SERVICE);
- return null;
- }
- logger.trace("validateEcompSso: found cookie {}", PortalApiConstants.EP_SERVICE);
- Cookie user = getCookie(request, userIdCookieName);
- if (user == null) {
- logger.debug("validateEcompSso: cookie not found: {}", userIdCookieName);
- return null;
- }
- logger.trace("validateEcompSso: user cookie {}", userIdCookieName);
- String userid = null;
- try {
- userid = portalSdkDecryptor.decrypt(user.getValue());
- } catch (CipherUtilException e) {
- throw new IllegalArgumentException("validateEcompSso failed", e);
- }
- return userid;
- }
+ /**
+ * Validates whether the ECOMP Portal sign-on process has completed. Checks for
+ * the ECOMP cookie first, then the user cookie.
+ *
+ * @param request
+ * HttpServletRequest
+ * @return User ID if the ECOMP cookie is present and the sign-on process
+ * established a user ID; else null.
+ */
+ public String validateEcompSso(HttpServletRequest request) {
+ // Check ECOMP Portal cookie
+ Cookie ep = getCookie(request, PortalApiConstants.EP_SERVICE);
+ if (ep == null) {
+ logger.debug("validateEcompSso: cookie not found: {}", PortalApiConstants.EP_SERVICE);
+ return null;
+ }
+ logger.trace("validateEcompSso: found cookie {}", PortalApiConstants.EP_SERVICE);
+ Cookie user = getCookie(request, userIdCookieName);
+ if (user == null) {
+ logger.debug("validateEcompSso: cookie not found: {}", userIdCookieName);
+ return null;
+ }
+ logger.trace("validateEcompSso: user cookie {}", userIdCookieName);
+ String userid = null;
+ try {
+ userid = portalSdkDecryptor.decrypt(user.getValue());
+ } catch (CipherUtilException e) {
+ throw new IllegalArgumentException("validateEcompSso failed", e);
+ }
+ return userid;
+ }
}
diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthenticationFilter.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthenticationFilter.java
index 4b6de914..711761a4 100644
--- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthenticationFilter.java
+++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthenticationFilter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file 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.
@@ -71,211 +71,211 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedA
* Portal knows where to forward the request to once the Portal Session is
* created and EPService cookie is set.
*
- *
+ *
* TODO: What about sessions? Will this be stateless?
- *
+ *
* This filter uses no annotations to avoid Spring's automatic registration,
* which add this filter in the chain in the wrong order.
*/
public class PortalAuthenticationFilter implements Filter {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- // Unfortunately not all file names are defined as constants
- private static final String[] securityPropertyFiles = { KeyProperties.PROPERTY_FILE_NAME,
- PortalApiProperties.PROPERTY_FILE_NAME, DefaultSecurityConfiguration.DEFAULT_RESOURCE_FILE,
- "validation.properties" };
+ // Unfortunately not all file names are defined as constants
+ private static final String[] securityPropertyFiles =
+ {KeyProperties.PROPERTY_FILE_NAME, PortalApiProperties.PROPERTY_FILE_NAME,
+ DefaultSecurityConfiguration.DEFAULT_RESOURCE_FILE, "validation.properties"};
- public static final String REDIRECT_URL_KEY = "redirectUrl";
+ public static final String REDIRECT_URL_KEY = "redirectUrl";
- private final boolean enforcePortalSecurity;
- private final PortalAuthManager authManager;
+ private final boolean enforcePortalSecurity;
+ private final PortalAuthManager authManager;
- private final DashboardUserManager userManager;
+ private final DashboardUserManager userManager;
- public PortalAuthenticationFilter(boolean portalSecurity, PortalAuthManager authManager,
- DashboardUserManager userManager) {
- this.enforcePortalSecurity = portalSecurity;
- this.authManager = authManager;
- this.userManager = userManager;
- if (portalSecurity) {
- // Throw if security is requested and prerequisites are not met
- for (String pf : securityPropertyFiles) {
- InputStream in = MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream(pf);
- if (in == null) {
- String msg = "Failed to find property file on classpath: " + pf;
- logger.error(msg);
- throw new RuntimeException(msg);
- } else {
- try {
- in.close();
- } catch (IOException ex) {
- logger.warn("Failed to close stream", ex);
- }
- }
- }
- }
- }
+ public PortalAuthenticationFilter(boolean portalSecurity, PortalAuthManager authManager,
+ DashboardUserManager userManager) {
+ this.enforcePortalSecurity = portalSecurity;
+ this.authManager = authManager;
+ this.userManager = userManager;
+ if (portalSecurity) {
+ // Throw if security is requested and prerequisites are not met
+ for (String pf : securityPropertyFiles) {
+ InputStream in = MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream(pf);
+ if (in == null) {
+ String msg = "Failed to find property file on classpath: " + pf;
+ logger.error(msg);
+ throw new RuntimeException(msg);
+ } else {
+ try {
+ in.close();
+ } catch (IOException ex) {
+ logger.warn("Failed to close stream", ex);
+ }
+ }
+ }
+ }
+ }
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- // complain loudly if this key property is missing
- String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
- logger.debug("init: Portal redirect URL {}", url);
- if (url == null)
- logger.error(
- "init: Failed to find property in portal.properties: " + PortalApiConstants.ECOMP_REDIRECT_URL);
- }
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ // complain loudly if this key property is missing
+ String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
+ logger.debug("init: Portal redirect URL {}", url);
+ if (url == null)
+ logger
+ .error("init: Failed to find property in portal.properties: " + PortalApiConstants.ECOMP_REDIRECT_URL);
+ }
- @Override
- public void destroy() {
- // No resources to release
- }
+ @Override
+ public void destroy() {
+ // No resources to release
+ }
- /**
- * Requests for pages ignored in the web security config do not hit this filter.
- */
- @Override
- public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
- throws IOException, ServletException {
- if (enforcePortalSecurity)
- doFilterEPSDKFW(req, res, chain);
- else
- doFilterMockUserAdminRole(req, res, chain);
- }
+ /**
+ * Requests for pages ignored in the web security config do not hit this filter.
+ */
+ @Override
+ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
+ throws IOException, ServletException {
+ if (enforcePortalSecurity)
+ doFilterEPSDKFW(req, res, chain);
+ else
+ doFilterMockUserAdminRole(req, res, chain);
+ }
- /*
- * Populates security context with a mock user in the admin role.
- *
- */
- private void doFilterMockUserAdminRole(ServletRequest req, ServletResponse res, FilterChain chain)
- throws IOException, ServletException {
- Authentication auth = SecurityContextHolder.getContext().getAuthentication();
- if (auth == null || auth.getAuthorities().isEmpty()) {
- if (logger.isDebugEnabled()) {
- logger.debug("doFilter adding auth to request URI {}",
- (req instanceof HttpServletRequest) ? ((HttpServletRequest) req).getRequestURL() : req);
- }
- EcompRole admin = new EcompRole();
- admin.setId(1L);
- admin.setName(DashboardConstants.ROLE_ADMIN);
- HashSet roles = new HashSet<>();
- roles.add(admin);
- EcompUser user = new EcompUser();
- user.setLoginId("fakeLoginId");
- user.setRoles(roles);
- user.setActive(true);
- EcompUserDetails userDetails = new EcompUserDetails(user);
- PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails,
- "fakeCredentials", userDetails.getAuthorities());
- SecurityContextHolder.getContext().setAuthentication(authToken);
- } else {
- logger.debug("doFilter: authorities {}", auth.getAuthorities());
- }
- chain.doFilter(req, res);
- }
+ /*
+ * Populates security context with a mock user in the admin role.
+ *
+ */
+ private void doFilterMockUserAdminRole(ServletRequest req, ServletResponse res, FilterChain chain)
+ throws IOException, ServletException {
+ Authentication auth = SecurityContextHolder.getContext().getAuthentication();
+ if (auth == null || auth.getAuthorities().isEmpty()) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("doFilter adding auth to request URI {}",
+ (req instanceof HttpServletRequest) ? ((HttpServletRequest) req).getRequestURL() : req);
+ }
+ EcompRole admin = new EcompRole();
+ admin.setId(1L);
+ admin.setName(DashboardConstants.ROLE_ADMIN);
+ HashSet roles = new HashSet<>();
+ roles.add(admin);
+ EcompUser user = new EcompUser();
+ user.setLoginId("fakeLoginId");
+ user.setRoles(roles);
+ user.setActive(true);
+ EcompUserDetails userDetails = new EcompUserDetails(user);
+ PreAuthenticatedAuthenticationToken authToken =
+ new PreAuthenticatedAuthenticationToken(userDetails, "fakeCredentials", userDetails.getAuthorities());
+ SecurityContextHolder.getContext().setAuthentication(authToken);
+ } else {
+ logger.debug("doFilter: authorities {}", auth.getAuthorities());
+ }
+ chain.doFilter(req, res);
+ }
- /*
- * Checks for valid cookies and allows request to be served if found; redirects
- * to Portal otherwise.
- */
- private void doFilterEPSDKFW(ServletRequest req, ServletResponse res, FilterChain chain)
- throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest) req;
- HttpServletResponse response = (HttpServletResponse) res;
- if (logger.isTraceEnabled())
- logger.trace("doFilter: req {}", request.getRequestURI());
- // Need to authenticate the request
- final String userId = authManager.validateEcompSso(request);
- final EcompUser ecompUser = (userId == null ? null : userManager.getUser(userId));
- if (userId == null || ecompUser == null) {
- logger.debug("doFilter: unauthorized user requests URI {}, serving login page", request.getRequestURI());
- StringBuffer sb = request.getRequestURL();
- sb.append(request.getQueryString() == null ? "" : "?" + request.getQueryString());
- String body = generateLoginRedirectPage(sb.toString());
- response.setContentType(MediaType.TEXT_HTML_VALUE);
- response.getWriter().print(body);
- response.getWriter().flush();
- } else {
- EcompUserDetails userDetails = new EcompUserDetails(ecompUser);
- // Using portal session as credentials is a hack
- PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails,
- getPortalSessionId(request), userDetails.getAuthorities());
- SecurityContextHolder.getContext().setAuthentication(authToken);
- // Pass request back down the filter chain
- chain.doFilter(request, response);
- }
- }
+ /*
+ * Checks for valid cookies and allows request to be served if found; redirects
+ * to Portal otherwise.
+ */
+ private void doFilterEPSDKFW(ServletRequest req, ServletResponse res, FilterChain chain)
+ throws IOException, ServletException {
+ HttpServletRequest request = (HttpServletRequest) req;
+ HttpServletResponse response = (HttpServletResponse) res;
+ if (logger.isTraceEnabled())
+ logger.trace("doFilter: req {}", request.getRequestURI());
+ // Need to authenticate the request
+ final String userId = authManager.validateEcompSso(request);
+ final EcompUser ecompUser = (userId == null ? null : userManager.getUser(userId));
+ if (userId == null || ecompUser == null) {
+ logger.debug("doFilter: unauthorized user requests URI {}, serving login page", request.getRequestURI());
+ StringBuffer sb = request.getRequestURL();
+ sb.append(request.getQueryString() == null ? "" : "?" + request.getQueryString());
+ String body = generateLoginRedirectPage(sb.toString());
+ response.setContentType(MediaType.TEXT_HTML_VALUE);
+ response.getWriter().print(body);
+ response.getWriter().flush();
+ } else {
+ EcompUserDetails userDetails = new EcompUserDetails(ecompUser);
+ // Using portal session as credentials is a hack
+ PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails,
+ getPortalSessionId(request), userDetails.getAuthorities());
+ SecurityContextHolder.getContext().setAuthentication(authToken);
+ // Pass request back down the filter chain
+ chain.doFilter(request, response);
+ }
+ }
- /**
- * Generates a page with text only, absolutely no references to any webapp
- * resources, so this can be served to an unauthenticated user without
- * triggering a new authentication attempt. The page has a link to the Portal
- * URL from configuration, with a return URL that is the original request.
- *
- * @param appUrl
- * Original requested URL
- * @return HTML
- * @throws UnsupportedEncodingException
- * On error
- */
- private static String generateLoginRedirectPage(String appUrl) throws UnsupportedEncodingException {
- String encodedAppUrl = URLEncoder.encode(appUrl, "UTF-8");
- String portalBaseUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
- String redirectUrl = portalBaseUrl + "?" + PortalAuthenticationFilter.REDIRECT_URL_KEY + "=" + encodedAppUrl;
- String aHref = "";
- // If only Java had "here" documents.
- String body = String.join(//
- System.getProperty("line.separator"), //
- "", //
- "", //
- "RIC Dashboard", //
- "", //
- "", //
- "", //
- "
", //
- "", //
- "");
- return body;
- }
+ /**
+ * Generates a page with text only, absolutely no references to any webapp
+ * resources, so this can be served to an unauthenticated user without
+ * triggering a new authentication attempt. The page has a link to the Portal
+ * URL from configuration, with a return URL that is the original request.
+ *
+ * @param appUrl
+ * Original requested URL
+ * @return HTML
+ * @throws UnsupportedEncodingException
+ * On error
+ */
+ private static String generateLoginRedirectPage(String appUrl) throws UnsupportedEncodingException {
+ String encodedAppUrl = URLEncoder.encode(appUrl, "UTF-8");
+ String portalBaseUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
+ String redirectUrl = portalBaseUrl + "?" + PortalAuthenticationFilter.REDIRECT_URL_KEY + "=" + encodedAppUrl;
+ String aHref = "";
+ // If only Java had "here" documents.
+ String body = String.join(//
+ System.getProperty("line.separator"), //
+ "", //
+ "", //
+ "RIC Dashboard", //
+ "", //
+ "", //
+ "", //
+ "