Fix formatting in the dashboard 15/2215/3
authorRehanRaza <muhammad.rehan.raza@est.tech>
Tue, 14 Jan 2020 09:42:52 +0000 (10:42 +0100)
committerRehanRaza <muhammad.rehan.raza@est.tech>
Wed, 15 Jan 2020 07:50:55 +0000 (08:50 +0100)
Change-Id: I3e7718fee18e38697aa1ac4ac1f08d6aee499d92
Signed-off-by: RehanRaza <muhammad.rehan.raza@est.tech>
38 files changed:
dashboard/webapp-backend/eclipse-formatter.xml [moved from policy-agent/java-formatter.xml with 100% similarity]
dashboard/webapp-backend/pom.xml
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardApplication.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardConstants.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/DashboardUserManager.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/AdminConfiguration.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/PortalApiConfiguration.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/SpringContextCache.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/SwaggerConfiguration.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/config/WebSecurityConfiguration.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/CustomResponseEntityExceptionHandler.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/Html5PathsController.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/PolicyController.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/SimpleErrorController.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/k8sapi/SimpleKubernetesClient.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/EcompUserDetails.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/ErrorTransport.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInfo.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInstances.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyType.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyTypes.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/SuccessTransport.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApi.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApiImpl.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/IPortalSdkDecryptor.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthManager.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthenticationFilter.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalRestCentralServiceImpl.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalSdkDecryptorAes.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalSdkDecryptorPkc.java
dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/util/HttpsURLConnectionUtils.java
dashboard/webapp-backend/src/test/java/org/oransc/ric/portal/dashboard/DashboardTestServer.java
dashboard/webapp-backend/src/test/java/org/oransc/ric/portal/dashboard/config/PolicyControllerMockConfiguration.java
dashboard/webapp-backend/src/test/java/org/oransc/ric/portal/dashboard/config/PortalApIMockConfiguration.java
dashboard/webapp-backend/src/test/java/org/oransc/ric/portal/dashboard/config/WebSecurityMockConfiguration.java
dashboard/webapp-backend/src/test/java/org/oransc/ric/portal/dashboard/controller/AbstractControllerTest.java
dashboard/webapp-backend/src/test/java/org/oransc/ric/portal/dashboard/controller/DefaultContextTest.java
dashboard/webapp-backend/src/test/java/org/oransc/ric/portal/dashboard/controller/PortalRestCentralServiceTest.java

index 80bb585..f089180 100644 (file)
@@ -36,6 +36,8 @@ limitations under the License.
     <properties>
         <springfox.version>2.9.2</springfox.version>
         <immutable.version>2.7.1</immutable.version>
+        <formatter-maven-plugin.version>2.8.1</formatter-maven-plugin.version>
+        <spotless-maven-plugin.version>1.18.0</spotless-maven-plugin.version>
         <!-- Set by Jenkins -->
         <build.number>0</build.number>
     </properties>
@@ -175,6 +177,32 @@ limitations under the License.
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-maven-plugin</artifactId>
             </plugin>
+            <plugin>
+                <groupId>net.revelc.code.formatter</groupId>
+                <artifactId>formatter-maven-plugin</artifactId>
+                <version>${formatter-maven-plugin.version}</version>
+                <configuration>
+                    <configFile>${project.basedir}/eclipse-formatter.xml</configFile>
+                </configuration>
+                <!-- https://code.revelc.net/formatter-maven-plugin/ use
+                    mvn formatter:format spotless:apply process-sources -->
+            </plugin>
+            <plugin>
+                <groupId>com.diffplug.spotless</groupId>
+                <artifactId>spotless-maven-plugin</artifactId>
+                <version>${spotless-maven-plugin.version}</version>
+                <configuration>
+                    <java>
+                        <removeUnusedImports />
+                        <importOrder>
+                            <order>com,java,javax,org</order>
+                        </importOrder>
+                    </java>
+                </configuration>
+                <!-- https://github.com/diffplug/spotless/tree/master/plugin-maven
+                    use mvn spotless:apply to rewrite source files use mvn spotless:check to
+                    validate source files -->
+            </plugin>
             <plugin>
                 <!-- Most configuration and all execution is inherited -->
                 <groupId>org.codehaus.mojo</groupId>
index 333c532..2550b8e 100644 (file)
@@ -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";
+    }
 
 }
index b82aa64..4b5d9a4 100644 (file)
@@ -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";
 
 }
index c5fd101..ffb7396 100644 (file)
@@ -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.
  */
 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<EcompUser> 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<List<EcompUser>>() {
-                       });
-               } else {
-                       users = new ArrayList<>();
-               }
-       }
-
-       /**
-        * Gets the current users.
-        * 
-        * @return List of EcompUser objects, possibly empty
-        */
-       public List<EcompUser> 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<EcompRole> 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<EcompUser> 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<List<EcompUser>>() {});
+        } else {
+            users = new ArrayList<>();
+        }
+    }
+
+    /**
+     * Gets the current users.
+     *
+     * @return List of EcompUser objects, possibly empty
+     */
+    public List<EcompUser> 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<EcompRole> roles = new HashSet<>();
+        roles.add(role);
+        user.setRoles(roles);
+        dum.createUser(user);
+        logger.debug("Created user {}", user);
+    }
 
 }
index 696d74f..8c646fe 100644 (file)
@@ -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);
+    }
 
 }
index f318cad..520f27f 100644 (file)
@@ -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<PortalRestAPIProxy> portalApiProxyServletBean() {
-               logger.debug("portalApiProxyServletBean");
-               PortalRestAPIProxy servlet = new PortalRestAPIProxy();
-               final ServletRegistrationBean<PortalRestAPIProxy> 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<PortalRestAPIProxy> portalApiProxyServletBean() {
+        logger.debug("portalApiProxyServletBean");
+        PortalRestAPIProxy servlet = new PortalRestAPIProxy();
+        final ServletRegistrationBean<PortalRestAPIProxy> servletBean =
+            new ServletRegistrationBean<>(servlet, PortalApiConstants.API_PREFIX + "/*");
+        servletBean.setName("PortalRestApiProxyServlet");
+        return servletBean;
+    }
 
 }
index 3a87782..a2f3d8f 100644 (file)
@@ -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;
+    }
 
 }
index b4bb0a3..435414a 100644 (file)
@@ -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();
+    }
 }
index 85a96d0..b43f8a9 100644 (file)
@@ -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;
+    }
 
 }
index f5ecd10..52a51fb 100644 (file)
@@ -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:<br>
  * 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: <blockquote>HTTP server received an invalid response from a
-        * server it consulted when acting as a proxy or gateway.</blockquote>
-        * 
-        * @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<ErrorTransport> 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: <blockquote>HTTP server received an invalid response from a
+     * server it consulted when acting as a proxy or gateway.</blockquote>
+     *
+     * @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<ErrorTransport> 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);
+        }
+    }
 
 }
index 7fb6e67..5d80538 100644 (file)
@@ -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());
+    }
 
 }
index 529cd2a..5b90931 100644 (file)
  */
 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<PolicyTypes> 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<String> getPolicyInstances(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString) {
-               logger.debug("getPolicyInstances {}", policyTypeIdString);
-
-               ResponseEntity<PolicyInstances> 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<String> 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<String> 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<String> getRicsSupportingType(
-                       @RequestParam(name = "policyType", required = true) String supportingPolicyType) {
-               logger.debug("getRicsSupportingType {}", supportingPolicyType);
-
-               ResponseEntity<Collection<String>> 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<PolicyTypes> 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<String> getPolicyInstances(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString) {
+        logger.debug("getPolicyInstances {}", policyTypeIdString);
+
+        ResponseEntity<PolicyInstances> 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<String> 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<String> 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<String> getRicsSupportingType(
+        @RequestParam(name = "policyType", required = true) String supportingPolicyType) {
+        logger.debug("getRicsSupportingType {}", supportingPolicyType);
+
+        ResponseEntity<Collection<String>> 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());
+    }
 
 };
index e2248e6..63b78ec 100644 (file)
@@ -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<String, Object> 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<String, Object> 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";
+    }
 
 }
index bcfae62..d3add60 100644 (file)
@@ -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<String> 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<String> podsResponse = rt.getForEntity(podsUrl, String.class);
+        return podsResponse.getBody();
+    }
 
 }
index 7bc9f00..3a08206 100644 (file)
@@ -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<GrantedAuthority> roleList = new ArrayList<>();
-               Iterator<EcompRole> 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<GrantedAuthority> roleList = new ArrayList<>();
+        Iterator<EcompRole> 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();
+    }
 
 }
index 516e3c8..f1250c1 100644 (file)
@@ -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;
+    }
 
 }
index ca1b79d..30cfd2a 100644 (file)
@@ -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();
 
 }
index eb6b455..c6faf9b 100644 (file)
@@ -23,6 +23,6 @@ import java.util.ArrayList;
 
 public class PolicyInstances extends ArrayList<PolicyInfo> {
 
-       private static final long serialVersionUID = -928428052502491021L;
+    private static final long serialVersionUID = -928428052502491021L;
 
 }
index ea51cc5..f0ca285 100644 (file)
@@ -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 + "]";
+    }
 }
index 3165d1b..43a6383 100644 (file)
@@ -23,6 +23,6 @@ import java.util.ArrayList;
 
 public class PolicyTypes extends ArrayList<PolicyType> {
 
-       private static final long serialVersionUID = -928428052502491021L;
+    private static final long serialVersionUID = -928428052502491021L;
 
 }
index 9e13789..65b39eb 100644 (file)
@@ -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;
+    }
 
 }
index 47add76..4a26563 100644 (file)
@@ -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<String> getPolicyInstance(String id) throws RestClientException;
 
     public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, String json, String ric)
-            throws RestClientException;
+        throws RestClientException;
 
     public void deletePolicy(String policyInstanceId) throws RestClientException;
 
index eb3f836..af814b9 100644 (file)
@@ -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.
  */
 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<List<ImmutablePolicyInfo>>() {
-        }.getType();
+        Type listType = new TypeToken<List<ImmutablePolicyInfo>>() {}.getType();
         List<PolicyInfo> rspParsed = gson.fromJson(rsp.getBody(), listType);
 
         PolicyInstances result = new PolicyInstances();
@@ -135,13 +131,13 @@ public class PolicyAgentApiImpl implements PolicyAgentApi {
 
     @Override
     public ResponseEntity<String> 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<String, ?> 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<String, ?> uriVariables = Map.of("typeName", typeName);
         String rsp = this.restTemplate.getForObject(url, String.class, uriVariables);
 
-        Type listType = new TypeToken<List<ImmutableRicInfo>>() {
-        }.getType();
+        Type listType = new TypeToken<List<ImmutableRicInfo>>() {}.getType();
         List<RicInfo> rspParsed = gson.fromJson(rsp, listType);
 
         Collection<String> result = new Vector<>(rspParsed.size());
index 34d80c9..552d783 100644 (file)
@@ -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;
 
 }
index dc70f7e..f4daa5c 100644 (file)
@@ -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<String, String> credentialsMap;
-       private final IPortalSdkDecryptor portalSdkDecryptor;
-       private final String userIdCookieName;
+    final Map<String, String> 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<String, String> getAppCredentials() {
-               return credentialsMap;
-       }
+    /**
+     * @return A map of key-value pairs with application name, user name and
+     *         password.
+     */
+    public Map<String, String> 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;
+    }
 
 }
index 4b6de91..711761a 100644 (file)
@@ -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.
  * </UL>
- * 
+ *
  * 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<EcompRole> 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<EcompRole> 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 = "<a href=\"" + redirectUrl + "\">";
-               // If only Java had "here" documents.
-               String body = String.join(//
-                               System.getProperty("line.separator"), //
-                               "<html>", //
-                               "<head>", //
-                               "<title>RIC Dashboard</title>", //
-                               "<style>", //
-                               "html, body { ", //
-                               "  font-family: Helvetica, Arial, sans-serif;", //
-                               "}", //
-                               "</style>", //
-                               "</head>", //
-                               "<body>", //
-                               "<h2>RIC Dashboard</h2>", //
-                               "<h4>Please log in.</h4>", //
-                               "<p>", //
-                               aHref, "Click here to authenticate at the ONAP Portal</a>", //
-                               "</p>", //
-                               "</body>", //
-                               "</html>");
-               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 = "<a href=\"" + redirectUrl + "\">";
+        // If only Java had "here" documents.
+        String body = String.join(//
+            System.getProperty("line.separator"), //
+            "<html>", //
+            "<head>", //
+            "<title>RIC Dashboard</title>", //
+            "<style>", //
+            "html, body { ", //
+            "  font-family: Helvetica, Arial, sans-serif;", //
+            "}", //
+            "</style>", //
+            "</head>", //
+            "<body>", //
+            "<h2>RIC Dashboard</h2>", //
+            "<h4>Please log in.</h4>", //
+            "<p>", //
+            aHref, "Click here to authenticate at the ONAP Portal</a>", //
+            "</p>", //
+            "</body>", //
+            "</html>");
+        return body;
+    }
 
-       /**
-        * 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;
+    }
 
-       /**
-        * Gets the ECOMP Portal service cookie value.
-        * 
-        * @param request
-        * @return Cookie value, or null if not found.
-        */
-       private String getPortalSessionId(HttpServletRequest request) {
-               Cookie ep = getCookie(request, PortalApiConstants.EP_SERVICE);
-               if (ep == null)
-                       return null;
-               return ep.getValue();
-       }
+    /**
+     * Gets the ECOMP Portal service cookie value.
+     *
+     * @param request
+     * @return Cookie value, or null if not found.
+     */
+    private String getPortalSessionId(HttpServletRequest request) {
+        Cookie ep = getCookie(request, PortalApiConstants.EP_SERVICE);
+        if (ep == null)
+            return null;
+        return ep.getValue();
+    }
 
 }
index 581ca25..a2fae9f 100644 (file)
@@ -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,52 +38,52 @@ import org.springframework.context.ApplicationContext;
  * Implements the contract used by the Portal to transmit user details to this
  * on-boarded application. The requests are intercepted first by a servlet in
  * the EPSDK-FW library, which proxies the calls to these methods.
- * 
+ *
  * An instance of this class is created upon first request to the API. But this
  * class is found and instantiated via Class.forName(), so cannot use Spring
  * annotations.
  */
 public class PortalRestCentralServiceImpl implements IPortalRestCentralService {
 
-       private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
-       private final PortalAuthManager authManager;
-       private final DashboardUserManager userManager;
+    private final PortalAuthManager authManager;
+    private final DashboardUserManager userManager;
 
-       public PortalRestCentralServiceImpl() throws IOException, PortalAPIException {
-               final ApplicationContext context = SpringContextCache.getApplicationContext();
-               authManager = (PortalAuthManager) context.getBean(PortalAuthManager.class);
-               userManager = (DashboardUserManager) context.getBean(DashboardUserManager.class);
-       }
+    public PortalRestCentralServiceImpl() throws IOException, PortalAPIException {
+        final ApplicationContext context = SpringContextCache.getApplicationContext();
+        authManager = context.getBean(PortalAuthManager.class);
+        userManager = context.getBean(DashboardUserManager.class);
+    }
 
-       /*
-        * Answers the Portal API credentials.
-        */
-       @Override
-       public Map<String, String> getAppCredentials() throws PortalAPIException {
-               logger.debug("getAppCredentials");
-               return authManager.getAppCredentials();
-       }
+    /*
+     * Answers the Portal API credentials.
+     */
+    @Override
+    public Map<String, String> getAppCredentials() throws PortalAPIException {
+        logger.debug("getAppCredentials");
+        return authManager.getAppCredentials();
+    }
 
-       /*
-        * Extracts the user ID from a cookie in the header
-        */
-       @Override
-       public String getUserId(HttpServletRequest request) throws PortalAPIException {
-               logger.debug("getuserId");
-               return authManager.validateEcompSso(request);
-       }
+    /*
+     * Extracts the user ID from a cookie in the header
+     */
+    @Override
+    public String getUserId(HttpServletRequest request) throws PortalAPIException {
+        logger.debug("getuserId");
+        return authManager.validateEcompSso(request);
+    }
 
-       @Override
-       public void pushUser(EcompUser user) throws PortalAPIException {
-               logger.debug("pushUser: {}", user);
-               userManager.createUser(user);
-       }
+    @Override
+    public void pushUser(EcompUser user) throws PortalAPIException {
+        logger.debug("pushUser: {}", user);
+        userManager.createUser(user);
+    }
 
-       @Override
-       public void editUser(String loginId, EcompUser user) throws PortalAPIException {
-               logger.debug("editUser: {}", user);
-               userManager.updateUser(loginId, user);
-       }
+    @Override
+    public void editUser(String loginId, EcompUser user) throws PortalAPIException {
+        logger.debug("editUser: {}", user);
+        userManager.updateUser(loginId, user);
+    }
 
 }
index 279f1dd..f62ea5f 100644 (file)
@@ -24,9 +24,9 @@ import org.onap.portalsdk.core.onboarding.util.CipherUtil;
 
 public class PortalSdkDecryptorAes implements IPortalSdkDecryptor {
 
-       @SuppressWarnings("deprecation")
-       public String decrypt(String cipherText) throws CipherUtilException {
-               return CipherUtil.decrypt(cipherText);
-       }
+    @SuppressWarnings("deprecation")
+    public String decrypt(String cipherText) throws CipherUtilException {
+        return CipherUtil.decrypt(cipherText);
+    }
 
 }
index 0127267..1020527 100644 (file)
@@ -24,8 +24,8 @@ import org.onap.portalsdk.core.onboarding.util.CipherUtil;
 
 public class PortalSdkDecryptorPkc implements IPortalSdkDecryptor {
 
-       public String decrypt(String cipherText) throws CipherUtilException {
-               return CipherUtil.decryptPKC(cipherText);
-       }
+    public String decrypt(String cipherText) throws CipherUtilException {
+        return CipherUtil.decryptPKC(cipherText);
+    }
 
 }
index a97ed7b..d5f2cbf 100644 (file)
@@ -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,48 +35,52 @@ import javax.net.ssl.X509TrustManager;
  * Disables and enables certificate and host-name checking in
  * HttpsURLConnection, the default JVM implementation of the HTTPS/TLS protocol.
  * Has no effect on implementations such as Apache Http Client, Ok Http.
- * 
+ *
  * https://stackoverflow.com/questions/23504819/how-to-disable-ssl-certificate-checking-with-spring-resttemplate/58291331#58291331
  */
 public final class HttpsURLConnectionUtils {
 
-       private static final HostnameVerifier jvmHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
+    private static final HostnameVerifier jvmHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
 
-       private static final HostnameVerifier trivialHostnameVerifier = new HostnameVerifier() {
-               public boolean verify(String hostname, SSLSession sslSession) {
-                       return true;
-               }
-       };
+    private static final HostnameVerifier trivialHostnameVerifier = new HostnameVerifier() {
+        @Override
+        public boolean verify(String hostname, SSLSession sslSession) {
+            return true;
+        }
+    };
 
-       private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[] { new X509TrustManager() {
-               public java.security.cert.X509Certificate[] getAcceptedIssuers() {
-                       return null;
-               }
+    private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[] {new X509TrustManager() {
+        @Override
+        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+            return null;
+        }
 
-               public void checkClientTrusted(X509Certificate[] certs, String authType) {
-               }
+        @Override
+        public void checkClientTrusted(X509Certificate[] certs, String authType) {
+        }
 
-               public void checkServerTrusted(X509Certificate[] certs, String authType) {
-               }
-       } };
+        @Override
+        public void checkServerTrusted(X509Certificate[] certs, String authType) {
+        }
+    }};
 
-       public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
-               HttpsURLConnection.setDefaultHostnameVerifier(trivialHostnameVerifier);
-               // Install the all-trusting trust manager
-               SSLContext sc = SSLContext.getInstance("SSL");
-               sc.init(null, UNQUESTIONING_TRUST_MANAGER, null);
-               HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
-       }
+    public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
+        HttpsURLConnection.setDefaultHostnameVerifier(trivialHostnameVerifier);
+        // Install the all-trusting trust manager
+        SSLContext sc = SSLContext.getInstance("SSL");
+        sc.init(null, UNQUESTIONING_TRUST_MANAGER, null);
+        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
+    }
 
-       public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
-               HttpsURLConnection.setDefaultHostnameVerifier(jvmHostnameVerifier);
-               // Return it to the initial state (discovered by reflection, now hardcoded)
-               SSLContext sc = SSLContext.getInstance("SSL");
-               sc.init(null, null, null);
-               HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
-       }
+    public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
+        HttpsURLConnection.setDefaultHostnameVerifier(jvmHostnameVerifier);
+        // Return it to the initial state (discovered by reflection, now hardcoded)
+        SSLContext sc = SSLContext.getInstance("SSL");
+        sc.init(null, null, null);
+        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
+    }
 
-       private HttpsURLConnectionUtils() {
-               throw new UnsupportedOperationException("Do not instantiate libraries.");
-       }
+    private HttpsURLConnectionUtils() {
+        throw new UnsupportedOperationException("Do not instantiate libraries.");
+    }
 }
index a6c0a1e..e19890b 100644 (file)
@@ -22,6 +22,7 @@ package org.oransc.ric.portal.dashboard;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 
 import java.lang.invoke.MethodHandles;
+
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
 import org.junit.jupiter.api.extension.ExtendWith;
@@ -29,7 +30,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
-import org.springframework.test.context.ActiveProfiles;
 import org.springframework.test.context.junit.jupiter.SpringExtension;
 
 /**
@@ -49,23 +49,23 @@ import org.springframework.test.context.junit.jupiter.SpringExtension;
 @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
 public class DashboardTestServer {
 
-       private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
-       /*
-        * Keeps the test server alive forever. Use a guard so this test is never run by
-        * Jenkins.
-        */
-       @EnabledIfSystemProperty(named = "org.oransc.ric.portal.dashboard", matches = "mock")
-       @Test
-       public void keepServerAlive() {
-               logger.warn("Keeping server alive!");
-               try {
-                       synchronized (this) {
-                               this.wait();
-                       }
-               } catch (Exception ex) {
-                       logger.warn(ex.toString());
-               }
-               assertEquals(1, 2);
-       }
+    /*
+     * Keeps the test server alive forever. Use a guard so this test is never run by
+     * Jenkins.
+     */
+    @EnabledIfSystemProperty(named = "org.oransc.ric.portal.dashboard", matches = "mock")
+    @Test
+    public void keepServerAlive() {
+        logger.warn("Keeping server alive!");
+        try {
+            synchronized (this) {
+                this.wait();
+            }
+        } catch (Exception ex) {
+            logger.warn(ex.toString());
+        }
+        assertEquals(1, 2);
+    }
 }
index e073ef6..41b9ee0 100644 (file)
@@ -52,143 +52,143 @@ import org.springframework.web.client.RestClientException;
 @TestConfiguration
 public class PolicyControllerMockConfiguration {
 
-       private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
-
-       @Bean
-       public PolicyAgentApi policyAgentApi() {
-               MockPolicyAgentApi apiClient = new MockPolicyAgentApi();
-               return apiClient;
-       }
-
-       class MockPolicyAgentApi implements PolicyAgentApi {
-               private final Database database = new Database();
-
-               @Override
-               public ResponseEntity<String> getPolicyInstance(String id) throws RestClientException {
-                       return new ResponseEntity<>(database.getInstance(id), HttpStatus.OK);
-               }
-
-               @Override
-               public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, String json,
-                               String ric) throws RestClientException {
-                       database.putInstance(policyTypeIdString, policyInstanceId, json, ric);
-                       return new ResponseEntity<>(HttpStatus.OK);
-               }
-
-               @Override
-               public void deletePolicy(String policyInstanceId) throws RestClientException {
-                       database.deleteInstance(policyInstanceId);
-               }
-
-               @Override
-               public ResponseEntity<PolicyTypes> getAllPolicyTypes() throws RestClientException {
-                       PolicyTypes result = new PolicyTypes();
-                       result.addAll(database.getTypes());
-                       return new ResponseEntity<>(result, HttpStatus.OK);
-               }
-
-               @Override
-               public ResponseEntity<PolicyInstances> getPolicyInstancesForType(String type) {
-                       PolicyInstances result = new PolicyInstances();
-                       List<PolicyInfo> inst = database.getInstances(Optional.of(type));
-                       result.addAll(inst);
-                       return new ResponseEntity<>(result, HttpStatus.OK);
-               }
-
-               @Override
-               public ResponseEntity<Collection<String>> getRicsSupportingType(String typeName) {
-                       Vector<String> res = new Vector<>();
-                       res.add("ric_1");
-                       res.add("ric_2");
-                       res.add("ric_3");
-                       return new ResponseEntity<>(res, HttpStatus.OK);
-               }
-       }
-
-       class Database {
-
-               Database() {
-                       String schema = getStringFromFile("anr-policy-schema.json");
-                       PolicyType policy = new PolicyType("ANR", schema);
-                       types.put("ANR", policy);
-
-                       schema = getStringFromFile("demo-policy-schema-1.json");
-                       policy = new PolicyType("type2", schema);
-                       types.put("type2", policy);
-
-                       schema = getStringFromFile("demo-policy-schema-2.json");
-                       policy = new PolicyType("type3", schema);
-                       types.put("type3", policy);
-
-                       schema = getStringFromFile("demo-policy-schema-3.json");
-                       policy = new PolicyType("type4", schema);
-                       types.put("type4", policy);
-                       try {
-                               putInstance("ANR", "ANR-1", getStringFromFile("anr-policy-instance.json"), "ric_1");
-                       } catch (Exception e) {
-                               // Nothing
-                       }
-               }
-
-               private String getStringFromFile(String path) {
-                       try {
-                               InputStream inputStream = MethodHandles.lookup().lookupClass().getClassLoader()
-                                               .getResourceAsStream(path);
-                               return new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));
-                       } catch (Exception e) {
-                               logger.error("Cannot read file :" + path, e);
-                               return "";
-                       }
-               }
-
-               String normalize(String str) {
-                       return str.replace('\n', ' ');
-               }
-
-               private String getTimeStampUTC() {
-                       return java.time.Instant.now().toString();
-               }
-
-               void putInstance(String typeId, String instanceId, String instanceData, String ric) {
-                       PolicyInfo i = ImmutablePolicyInfo.builder().json(instanceData).lastModified(getTimeStampUTC())
-                                       .id(instanceId).ric(ric).service("service").type(typeId).build();
-                       instances.put(instanceId, i);
-               }
-
-               public void deleteInstance(String instanceId) {
-                       instances.remove(instanceId);
-               }
-
-               String getInstance(String id) throws RestClientException {
-                       PolicyInfo i = instances.get(id);
-                       if (i == null) {
-                               throw new RestClientException("Type not found: " + id);
-                       }
-                       return i.json();
-               }
-
-               public Collection<PolicyType> getTypes() {
-                       return types.values();
-               }
-
-               public List<PolicyInfo> getInstances(Optional<String> typeId) {
-                       ArrayList<PolicyInfo> result = new ArrayList<>();
-                       for (PolicyInfo i : instances.values()) {
-                               if (typeId.isPresent()) {
-                                       if (i.type().equals(typeId.get())) {
-                                               result.add(i);
-                                       }
-
-                               } else {
-                                       result.add(i);
-                               }
-                       }
-                       return result;
-               }
-
-               private Map<String, PolicyType> types = new HashMap<>();
-               private Map<String, PolicyInfo> instances = new HashMap<>();
-
-       }
+    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+    @Bean
+    public PolicyAgentApi policyAgentApi() {
+        MockPolicyAgentApi apiClient = new MockPolicyAgentApi();
+        return apiClient;
+    }
+
+    class MockPolicyAgentApi implements PolicyAgentApi {
+        private final Database database = new Database();
+
+        @Override
+        public ResponseEntity<String> getPolicyInstance(String id) throws RestClientException {
+            return new ResponseEntity<>(database.getInstance(id), HttpStatus.OK);
+        }
+
+        @Override
+        public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, String json,
+            String ric) throws RestClientException {
+            database.putInstance(policyTypeIdString, policyInstanceId, json, ric);
+            return new ResponseEntity<>(HttpStatus.OK);
+        }
+
+        @Override
+        public void deletePolicy(String policyInstanceId) throws RestClientException {
+            database.deleteInstance(policyInstanceId);
+        }
+
+        @Override
+        public ResponseEntity<PolicyTypes> getAllPolicyTypes() throws RestClientException {
+            PolicyTypes result = new PolicyTypes();
+            result.addAll(database.getTypes());
+            return new ResponseEntity<>(result, HttpStatus.OK);
+        }
+
+        @Override
+        public ResponseEntity<PolicyInstances> getPolicyInstancesForType(String type) {
+            PolicyInstances result = new PolicyInstances();
+            List<PolicyInfo> inst = database.getInstances(Optional.of(type));
+            result.addAll(inst);
+            return new ResponseEntity<>(result, HttpStatus.OK);
+        }
+
+        @Override
+        public ResponseEntity<Collection<String>> getRicsSupportingType(String typeName) {
+            Vector<String> res = new Vector<>();
+            res.add("ric_1");
+            res.add("ric_2");
+            res.add("ric_3");
+            return new ResponseEntity<>(res, HttpStatus.OK);
+        }
+    }
+
+    class Database {
+
+        Database() {
+            String schema = getStringFromFile("anr-policy-schema.json");
+            PolicyType policy = new PolicyType("ANR", schema);
+            types.put("ANR", policy);
+
+            schema = getStringFromFile("demo-policy-schema-1.json");
+            policy = new PolicyType("type2", schema);
+            types.put("type2", policy);
+
+            schema = getStringFromFile("demo-policy-schema-2.json");
+            policy = new PolicyType("type3", schema);
+            types.put("type3", policy);
+
+            schema = getStringFromFile("demo-policy-schema-3.json");
+            policy = new PolicyType("type4", schema);
+            types.put("type4", policy);
+            try {
+                putInstance("ANR", "ANR-1", getStringFromFile("anr-policy-instance.json"), "ric_1");
+            } catch (Exception e) {
+                // Nothing
+            }
+        }
+
+        private String getStringFromFile(String path) {
+            try {
+                InputStream inputStream =
+                    MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream(path);
+                return new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));
+            } catch (Exception e) {
+                logger.error("Cannot read file :" + path, e);
+                return "";
+            }
+        }
+
+        String normalize(String str) {
+            return str.replace('\n', ' ');
+        }
+
+        private String getTimeStampUTC() {
+            return java.time.Instant.now().toString();
+        }
+
+        void putInstance(String typeId, String instanceId, String instanceData, String ric) {
+            PolicyInfo i = ImmutablePolicyInfo.builder().json(instanceData).lastModified(getTimeStampUTC())
+                .id(instanceId).ric(ric).service("service").type(typeId).build();
+            instances.put(instanceId, i);
+        }
+
+        public void deleteInstance(String instanceId) {
+            instances.remove(instanceId);
+        }
+
+        String getInstance(String id) throws RestClientException {
+            PolicyInfo i = instances.get(id);
+            if (i == null) {
+                throw new RestClientException("Type not found: " + id);
+            }
+            return i.json();
+        }
+
+        public Collection<PolicyType> getTypes() {
+            return types.values();
+        }
+
+        public List<PolicyInfo> getInstances(Optional<String> typeId) {
+            ArrayList<PolicyInfo> result = new ArrayList<>();
+            for (PolicyInfo i : instances.values()) {
+                if (typeId.isPresent()) {
+                    if (i.type().equals(typeId.get())) {
+                        result.add(i);
+                    }
+
+                } else {
+                    result.add(i);
+                }
+            }
+            return result;
+        }
+
+        private Map<String, PolicyType> types = new HashMap<>();
+        private Map<String, PolicyInfo> instances = new HashMap<>();
+
+    }
 
 }
index a3d05be..01265d9 100644 (file)
@@ -43,41 +43,41 @@ import org.springframework.context.annotation.Profile;
 @Profile("test")
 public class PortalApIMockConfiguration {
 
-       private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
-       // Unfortunately EPSDK-FW does not define these as constants
-       public static final String PORTAL_USERNAME_HEADER_KEY = "username";
-       public static final String PORTAL_PASSWORD_HEADER_KEY = "password";
+    // Unfortunately EPSDK-FW does not define these as constants
+    public static final String PORTAL_USERNAME_HEADER_KEY = "username";
+    public static final String PORTAL_PASSWORD_HEADER_KEY = "password";
 
-       @Bean
-       public ServletRegistrationBean<PortalRestAPIProxy> portalApiProxyServlet() {
-               PortalRestAPIProxy servlet = new PortalRestAPIProxy();
-               final ServletRegistrationBean<PortalRestAPIProxy> servletBean = new ServletRegistrationBean<>(servlet,
-                               PortalApiConstants.API_PREFIX + "/*");
-               servletBean.setName("PortalRestApiProxyServlet");
-               return servletBean;
-       }
+    @Bean
+    public ServletRegistrationBean<PortalRestAPIProxy> portalApiProxyServlet() {
+        PortalRestAPIProxy servlet = new PortalRestAPIProxy();
+        final ServletRegistrationBean<PortalRestAPIProxy> servletBean =
+            new ServletRegistrationBean<>(servlet, PortalApiConstants.API_PREFIX + "/*");
+        servletBean.setName("PortalRestApiProxyServlet");
+        return servletBean;
+    }
 
-       @Bean
-       public PortalAuthManager portalAuthManager() throws Exception {
-               PortalAuthManager mockManager = mock(PortalAuthManager.class);
-               final Map<String, String> credentialsMap = new HashMap<>();
-               credentialsMap.put("appName", "appName");
-               credentialsMap.put(PORTAL_USERNAME_HEADER_KEY, PORTAL_USERNAME_HEADER_KEY);
-               credentialsMap.put(PORTAL_PASSWORD_HEADER_KEY, PORTAL_PASSWORD_HEADER_KEY);
-               doAnswer(inv -> {
-                       logger.debug("getAppCredentials");
-                       return credentialsMap;
-               }).when(mockManager).getAppCredentials();
-               doAnswer(inv -> {
-                       logger.debug("getUserId");
-                       return "userId";
-               }).when(mockManager).validateEcompSso(any(HttpServletRequest.class));
-               doAnswer(inv -> {
-                       logger.debug("getAppCredentials");
-                       return credentialsMap;
-               }).when(mockManager).getAppCredentials();
-               return mockManager;
-       }
+    @Bean
+    public PortalAuthManager portalAuthManager() throws Exception {
+        PortalAuthManager mockManager = mock(PortalAuthManager.class);
+        final Map<String, String> credentialsMap = new HashMap<>();
+        credentialsMap.put("appName", "appName");
+        credentialsMap.put(PORTAL_USERNAME_HEADER_KEY, PORTAL_USERNAME_HEADER_KEY);
+        credentialsMap.put(PORTAL_PASSWORD_HEADER_KEY, PORTAL_PASSWORD_HEADER_KEY);
+        doAnswer(inv -> {
+            logger.debug("getAppCredentials");
+            return credentialsMap;
+        }).when(mockManager).getAppCredentials();
+        doAnswer(inv -> {
+            logger.debug("getUserId");
+            return "userId";
+        }).when(mockManager).validateEcompSso(any(HttpServletRequest.class));
+        doAnswer(inv -> {
+            logger.debug("getAppCredentials");
+            return credentialsMap;
+        }).when(mockManager).getAppCredentials();
+        return mockManager;
+    }
 
 }
index 80cde66..3e75606 100644 (file)
@@ -42,43 +42,43 @@ import org.springframework.security.crypto.password.PasswordEncoder;
 @Profile("test")
 public class WebSecurityMockConfiguration extends WebSecurityConfigurerAdapter {
 
-       public static final String TEST_CRED_ADMIN = "admin";
-       public static final String TEST_CRED_STANDARD = "standard";
+    public static final String TEST_CRED_ADMIN = "admin";
+    public static final String TEST_CRED_STANDARD = "standard";
 
-       private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
-       public WebSecurityMockConfiguration(@Value("${userfile}") final String userFilePath) {
-               logger.debug("ctor: user file path {}", userFilePath);
-       }
+    public WebSecurityMockConfiguration(@Value("${userfile}") final String userFilePath) {
+        logger.debug("ctor: user file path {}", userFilePath);
+    }
 
-       @Override
-       protected void configure(AuthenticationManagerBuilder auth) throws Exception {
-               PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
-               auth.inMemoryAuthentication() //
-                               .passwordEncoder(encoder) //
-                               // The admin user has the admin AND standard roles
-                               .withUser(TEST_CRED_ADMIN) //
-                               .password(encoder.encode(TEST_CRED_ADMIN))
-                               .roles(DashboardConstants.ROLE_NAME_ADMIN, DashboardConstants.ROLE_NAME_STANDARD)//
-                               .and()//
-                               // The standard user has only the standard role
-                               .withUser(TEST_CRED_STANDARD) //
-                               .password(encoder.encode(TEST_CRED_STANDARD)) //
-                               .roles(DashboardConstants.ROLE_NAME_STANDARD);
-       }
+    @Override
+    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
+        auth.inMemoryAuthentication() //
+            .passwordEncoder(encoder) //
+            // The admin user has the admin AND standard roles
+            .withUser(TEST_CRED_ADMIN) //
+            .password(encoder.encode(TEST_CRED_ADMIN))
+            .roles(DashboardConstants.ROLE_NAME_ADMIN, DashboardConstants.ROLE_NAME_STANDARD)//
+            .and()//
+            // The standard user has only the standard role
+            .withUser(TEST_CRED_STANDARD) //
+            .password(encoder.encode(TEST_CRED_STANDARD)) //
+            .roles(DashboardConstants.ROLE_NAME_STANDARD);
+    }
 
-       @Override
-       protected void configure(HttpSecurity http) throws Exception {
-               http.authorizeRequests().anyRequest().authenticated()//
-                               .and().httpBasic() //
-                               .and().csrf().disable();
-       }
+    @Override
+    protected void configure(HttpSecurity http) throws Exception {
+        http.authorizeRequests().anyRequest().authenticated()//
+            .and().httpBasic() //
+            .and().csrf().disable();
+    }
 
-       @Override
-       public void configure(WebSecurity web) throws Exception {
-               // This disables Spring security, but not the app's filter.
-               web.ignoring().antMatchers(WebSecurityConfiguration.OPEN_PATHS);
-               web.ignoring().antMatchers("/", "/csrf"); // allow swagger-ui to load
-       }
+    @Override
+    public void configure(WebSecurity web) throws Exception {
+        // This disables Spring security, but not the app's filter.
+        web.ignoring().antMatchers(WebSecurityConfiguration.OPEN_PATHS);
+        web.ignoring().antMatchers("/", "/csrf"); // allow swagger-ui to load
+    }
 
 }
index d4163f0..09d3a86 100644 (file)
@@ -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.
@@ -44,69 +44,69 @@ import org.springframework.web.util.UriComponentsBuilder;
 @ActiveProfiles("test")
 public class AbstractControllerTest {
 
-       private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
-       // Created by Spring black magic
-       // https://spring.io/guides/gs/testing-web/
-       @LocalServerPort
-       private int localServerPort;
+    // Created by Spring black magic
+    // https://spring.io/guides/gs/testing-web/
+    @LocalServerPort
+    private int localServerPort;
 
-       @Autowired
-       protected TestRestTemplate restTemplate;
+    @Autowired
+    protected TestRestTemplate restTemplate;
 
-       /**
-        * Flexible URI builder.
-        * 
-        * @param queryParams
-        *                        Map of string-string query parameters
-        * @param path
-        *                        Array of path components. If a component has an
-        *                        embedded slash, the string is split and each
-        *                        subcomponent is added individually.
-        * @return URI
-        */
-       protected URI buildUri(final Map<String, String> queryParams, final String... path) {
-               UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:" + localServerPort + "/");
-               for (int p = 0; p < path.length; ++p) {
-                       if (path[p] == null || path[p].isEmpty()) {
-                               throw new IllegalArgumentException("Unexpected null or empty at path index " + Integer.toString(p));
-                       } else if (path[p].contains("/")) {
-                               String[] subpaths = path[p].split("/");
-                               for (String s : subpaths)
-                                       if (!s.isEmpty())
-                                               builder.pathSegment(s);
-                       } else {
-                               builder.pathSegment(path[p]);
-                       }
-               }
-               if (queryParams != null && queryParams.size() > 0) {
-                       for (Map.Entry<String, String> entry : queryParams.entrySet()) {
-                               if (entry.getKey() == null || entry.getValue() == null)
-                                       throw new IllegalArgumentException("Unexpected null key or value");
-                               else
-                                       builder.queryParam(entry.getKey(), entry.getValue());
-                       }
-               }
-               return builder.build().encode().toUri();
-       }
+    /**
+     * Flexible URI builder.
+     *
+     * @param queryParams
+     *        Map of string-string query parameters
+     * @param path
+     *        Array of path components. If a component has an
+     *        embedded slash, the string is split and each
+     *        subcomponent is added individually.
+     * @return URI
+     */
+    protected URI buildUri(final Map<String, String> queryParams, final String... path) {
+        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:" + localServerPort + "/");
+        for (int p = 0; p < path.length; ++p) {
+            if (path[p] == null || path[p].isEmpty()) {
+                throw new IllegalArgumentException("Unexpected null or empty at path index " + Integer.toString(p));
+            } else if (path[p].contains("/")) {
+                String[] subpaths = path[p].split("/");
+                for (String s : subpaths)
+                    if (!s.isEmpty())
+                        builder.pathSegment(s);
+            } else {
+                builder.pathSegment(path[p]);
+            }
+        }
+        if (queryParams != null && queryParams.size() > 0) {
+            for (Map.Entry<String, String> entry : queryParams.entrySet()) {
+                if (entry.getKey() == null || entry.getValue() == null)
+                    throw new IllegalArgumentException("Unexpected null key or value");
+                else
+                    builder.queryParam(entry.getKey(), entry.getValue());
+            }
+        }
+        return builder.build().encode().toUri();
+    }
 
-       // Because I put the annotations on this parent class,
-       // must define at least one test here.
-       @Test
-       public void contextLoads() {
-               // Silence Sonar warning about missing assertion.
-               Assertions.assertTrue(logger.isWarnEnabled());
-               logger.info("Context loads on mock profile");
-       }
+    // Because I put the annotations on this parent class,
+    // must define at least one test here.
+    @Test
+    public void contextLoads() {
+        // Silence Sonar warning about missing assertion.
+        Assertions.assertTrue(logger.isWarnEnabled());
+        logger.info("Context loads on mock profile");
+    }
 
-       public TestRestTemplate testRestTemplateAdminRole() {
-               return restTemplate.withBasicAuth(WebSecurityMockConfiguration.TEST_CRED_ADMIN,
-                               WebSecurityMockConfiguration.TEST_CRED_ADMIN);
-       }
+    public TestRestTemplate testRestTemplateAdminRole() {
+        return restTemplate.withBasicAuth(WebSecurityMockConfiguration.TEST_CRED_ADMIN,
+            WebSecurityMockConfiguration.TEST_CRED_ADMIN);
+    }
 
-       public TestRestTemplate testRestTemplateStandardRole() {
-               return restTemplate.withBasicAuth(WebSecurityMockConfiguration.TEST_CRED_STANDARD,
-                               WebSecurityMockConfiguration.TEST_CRED_STANDARD);
-       }
+    public TestRestTemplate testRestTemplateStandardRole() {
+        return restTemplate.withBasicAuth(WebSecurityMockConfiguration.TEST_CRED_STANDARD,
+            WebSecurityMockConfiguration.TEST_CRED_STANDARD);
+    }
 
 }
index 48c5931..643f15e 100644 (file)
@@ -36,13 +36,13 @@ import org.springframework.test.context.junit.jupiter.SpringExtension;
 @SpringBootTest
 public class DefaultContextTest {
 
-       private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
-       @Test
-       public void contextLoads() {
-               // Silence Sonar warning about missing assertion.
-               Assertions.assertTrue(logger.isWarnEnabled());
-               logger.info("Context loads on default profile");
-       }
+    @Test
+    public void contextLoads() {
+        // Silence Sonar warning about missing assertion.
+        Assertions.assertTrue(logger.isWarnEnabled());
+        logger.info("Context loads on default profile");
+    }
 
 }
index dc80968..1e8d3a3 100644 (file)
@@ -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.
@@ -41,77 +41,78 @@ import org.springframework.http.ResponseEntity;
 
 public class PortalRestCentralServiceTest extends AbstractControllerTest {
 
-       private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
-       @Test
-       public void getAnalyticsTest() {
-               // paths are hardcoded here exactly like the EPSDK-FW library :(
-               URI uri = buildUri(null, PortalApiConstants.API_PREFIX, "/analytics");
-               logger.info("Invoking {}", uri);
-               ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, null, String.class);
-               // No Portal is available so this always fails
-               Assertions.assertTrue(response.getStatusCode().is4xxClientError());
-       }
+    @Test
+    public void getAnalyticsTest() {
+        // paths are hardcoded here exactly like the EPSDK-FW library :(
+        URI uri = buildUri(null, PortalApiConstants.API_PREFIX, "/analytics");
+        logger.info("Invoking {}", uri);
+        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, null, String.class);
+        // No Portal is available so this always fails
+        Assertions.assertTrue(response.getStatusCode().is4xxClientError());
+    }
 
-       @Test
-       public void getErrorPageTest() {
-               // Send unauthorized request
-               URI uri = buildUri(null, "/favicon.ico");
-               logger.info("Invoking {}", uri);
-               ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, null, String.class);
-               Assertions.assertTrue(response.getStatusCode().is4xxClientError());
-               Assertions.assertTrue(response.getBody().contains("Static error page"));
-       }
+    @Test
+    public void getErrorPageTest() {
+        // Send unauthorized request
+        URI uri = buildUri(null, "/favicon.ico");
+        logger.info("Invoking {}", uri);
+        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, null, String.class);
+        Assertions.assertTrue(response.getStatusCode().is4xxClientError());
+        Assertions.assertTrue(response.getBody().contains("Static error page"));
+    }
 
-       private HttpEntity<Object> getEntityWithHeaders(Object body) {
-               HttpHeaders headers = new HttpHeaders();
-               headers.set(PortalApIMockConfiguration.PORTAL_USERNAME_HEADER_KEY,
-                               PortalApIMockConfiguration.PORTAL_USERNAME_HEADER_KEY);
-               headers.set(PortalApIMockConfiguration.PORTAL_PASSWORD_HEADER_KEY,
-                               PortalApIMockConfiguration.PORTAL_PASSWORD_HEADER_KEY);
-               HttpEntity<Object> entity = new HttpEntity<>(body, headers);
-               return entity;
-       }
+    private HttpEntity<Object> getEntityWithHeaders(Object body) {
+        HttpHeaders headers = new HttpHeaders();
+        headers.set(PortalApIMockConfiguration.PORTAL_USERNAME_HEADER_KEY,
+            PortalApIMockConfiguration.PORTAL_USERNAME_HEADER_KEY);
+        headers.set(PortalApIMockConfiguration.PORTAL_PASSWORD_HEADER_KEY,
+            PortalApIMockConfiguration.PORTAL_PASSWORD_HEADER_KEY);
+        HttpEntity<Object> entity = new HttpEntity<>(body, headers);
+        return entity;
+    }
 
-       private EcompUser createEcompUser(String loginId) {
-               EcompUser user = new EcompUser();
-               user.setLoginId(loginId);
-               EcompRole role = new EcompRole();
-               role.setRoleFunctions(Collections.EMPTY_SET);
-               role.setId(1L);
-               role.setName(DashboardConstants.ROLE_NAME_ADMIN);
-               Set<EcompRole> roles = new HashSet<>();
-               roles.add(role);
-               user.setRoles(roles);
-               return user;
-       }
+    private EcompUser createEcompUser(String loginId) {
+        EcompUser user = new EcompUser();
+        user.setLoginId(loginId);
+        EcompRole role = new EcompRole();
+        role.setRoleFunctions(Collections.EMPTY_SET);
+        role.setId(1L);
+        role.setName(DashboardConstants.ROLE_NAME_ADMIN);
+        Set<EcompRole> roles = new HashSet<>();
+        roles.add(role);
+        user.setRoles(roles);
+        return user;
+    }
 
-/*     @Test
-       public void createUserTest() {
-               final String loginId = "login1";
-               URI create = buildUri(null, PortalApiConstants.API_PREFIX, "user");
-               logger.info("Invoking {}", create);
-               HttpEntity<Object> requestEntity = getEntityWithHeaders(createEcompUser(loginId));
-               ResponseEntity<String> response = restTemplate.exchange(create, HttpMethod.POST, requestEntity, String.class);
-               Assertions.assertTrue(response.getStatusCode().is2xxSuccessful());
-       }
-
-       @Test
-       public void updateUserTest() {
-               final String loginId = "login2";
-               URI create = buildUri(null, PortalApiConstants.API_PREFIX, "user");
-               EcompUser user = createEcompUser(loginId);
-               logger.info("Invoking {}", create);
-               HttpEntity<Object> requestEntity = getEntityWithHeaders(user);
-               // Create
-               ResponseEntity<String> response = restTemplate.exchange(create, HttpMethod.POST, requestEntity, String.class);
-               Assertions.assertTrue(response.getStatusCode().is2xxSuccessful());
-               URI update = buildUri(null, PortalApiConstants.API_PREFIX, "user", loginId);
-               user.setEmail("user@company.org");
-               requestEntity = getEntityWithHeaders(user);
-               response = restTemplate.exchange(update, HttpMethod.POST, requestEntity, String.class);
-               Assertions.assertTrue(response.getStatusCode().is2xxSuccessful());
-       }
-*/
+    /*
+     * @Test
+     * public void createUserTest() {
+     * final String loginId = "login1";
+     * URI create = buildUri(null, PortalApiConstants.API_PREFIX, "user");
+     * logger.info("Invoking {}", create);
+     * HttpEntity<Object> requestEntity = getEntityWithHeaders(createEcompUser(loginId));
+     * ResponseEntity<String> response = restTemplate.exchange(create, HttpMethod.POST, requestEntity, String.class);
+     * Assertions.assertTrue(response.getStatusCode().is2xxSuccessful());
+     * }
+     *
+     * @Test
+     * public void updateUserTest() {
+     * final String loginId = "login2";
+     * URI create = buildUri(null, PortalApiConstants.API_PREFIX, "user");
+     * EcompUser user = createEcompUser(loginId);
+     * logger.info("Invoking {}", create);
+     * HttpEntity<Object> requestEntity = getEntityWithHeaders(user);
+     * // Create
+     * ResponseEntity<String> response = restTemplate.exchange(create, HttpMethod.POST, requestEntity, String.class);
+     * Assertions.assertTrue(response.getStatusCode().is2xxSuccessful());
+     * URI update = buildUri(null, PortalApiConstants.API_PREFIX, "user", loginId);
+     * user.setEmail("user@company.org");
+     * requestEntity = getEntityWithHeaders(user);
+     * response = restTemplate.exchange(update, HttpMethod.POST, requestEntity, String.class);
+     * Assertions.assertTrue(response.getStatusCode().is2xxSuccessful());
+     * }
+     */
 
 }