diff options
32 files changed, 921 insertions, 1076 deletions
@@ -69,8 +69,8 @@ <swagger.jaxrs2.version>2.0.0-rc4</swagger.jaxrs2.version> <eelf.core.version>1.0.0</eelf.core.version> - <camel.version>2.20.1</camel.version> - <springboot.version>1.5.14.RELEASE</springboot.version> + <camel.version>2.22.0</camel.version> + <springboot.version>2.0.2.RELEASE</springboot.version> <sonar.language>java</sonar.language> <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin> @@ -87,7 +87,7 @@ <docker.skip.tag>true</docker.skip.tag> <skip.staging.artifacts>false</skip.staging.artifacts> <python.http.proxy.param></python.http.proxy.param> - <tomcat.version>8.5.28</tomcat.version> + <tomcat.version>8.5.32</tomcat.version> </properties> <profiles> @@ -267,10 +267,19 @@ <artifactId>camel-servlet-starter</artifactId> </dependency> <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-jackson</artifactId> + </dependency> + <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> + <dependency> + <groupId>org.glassfish.jersey.core</groupId> + <artifactId>jersey-common</artifactId> + <version>2.27</version> + </dependency> <!-- Spring famework --> <dependency> <groupId>org.springframework.boot</groupId> @@ -281,11 +290,6 @@ <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> - <groupId>com.paypal.springboot</groupId> - <artifactId>resteasy-spring-boot-starter</artifactId> - <version>2.3.4-RELEASE</version> - </dependency> - <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> @@ -299,6 +303,10 @@ </dependency> <dependency> <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-autoconfigure</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> @@ -550,25 +558,6 @@ <artifactId>sdc-tosca</artifactId> <version>1.3.0</version> </dependency> - <!-- To generate Swagger.json, swagger.html and swagger.pdf --> - <dependency> - <groupId>io.springfox</groupId> - <artifactId>springfox-swagger2</artifactId> - <version>2.4.0</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>io.github.robwin</groupId> - <artifactId>assertj-swagger</artifactId> - <version>0.2.0</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>io.github.swagger2markup</groupId> - <artifactId>swagger2markup-spring-restdocs-ext</artifactId> - <version>1.2.0</version> - <scope>test</scope> - </dependency> <!-- TESTING --> <dependency> <groupId>org.assertj</groupId> @@ -576,6 +565,12 @@ <version>3.10.0</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>1.10.19</version> + <scope>test</scope> + </dependency> </dependencies> <pluginRepositories> <pluginRepository> @@ -631,121 +626,6 @@ </resources> <plugins> - <!-- Scan Clamp code and generate the swagger.json file with all the - APIs --> - <plugin> - <groupId>com.sebastian-daschner</groupId> - <artifactId>jaxrs-analyzer-maven-plugin</artifactId> - <version>0.14</version> - <executions> - <execution> - <phase>test</phase> - <goals> - <goal>analyze-jaxrs</goal> - </goals> - <configuration> - <backend>swagger</backend> - <resourcesDir>../docs/swagger/</resourcesDir> - </configuration> - </execution> - </executions> - </plugin> - - <!-- Read the swagger.json file and the definition from SwaggerConfig.java; - generate a list of .adoc files containing the APIs info in more structured - way --> - <plugin> - <groupId>io.github.swagger2markup</groupId> - <artifactId>swagger2markup-maven-plugin</artifactId> - <version>1.3.1</version> - <dependencies> - <dependency> - <groupId>io.github.swagger2markup</groupId> - <artifactId>swagger2markup-import-files-ext</artifactId> - <version>1.3.1</version> - </dependency> - <dependency> - <groupId>io.github.swagger2markup</groupId> - <artifactId>swagger2markup-spring-restdocs-ext</artifactId> - <version>1.3.1</version> - </dependency> - </dependencies> - <configuration> - <swaggerInput>${project.basedir}/docs/swagger/swagger.json</swaggerInput> - <outputDir>${project.build.directory}/asciidoc/generated</outputDir> - <config> - <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage> - </config> - </configuration> - <executions> - <execution> - <phase>test</phase> - <goals> - <goal>convertSwagger2markup</goal> - </goals> - </execution> - </executions> - </plugin> - - <!-- Run the generated asciidoc through Asciidoctor to generate other - documentation types, such as PDFs or HTML5 --> - <plugin> - <groupId>org.asciidoctor</groupId> - <artifactId>asciidoctor-maven-plugin</artifactId> - <version>1.5.3</version> - <dependencies> - <dependency> - <groupId>org.asciidoctor</groupId> - <artifactId>asciidoctorj-pdf</artifactId> - <version>1.5.0-alpha.10.1</version> - </dependency> - <dependency> - <groupId>org.jruby</groupId> - <artifactId>jruby-complete</artifactId> - <version>1.7.21</version> - </dependency> - </dependencies> - <configuration> - <sourceDirectory>${project.basedir}/src/main/resources/asciidoc</sourceDirectory> - <sourceDocumentName>swagger.adoc</sourceDocumentName> - <attributes> - <doctype>book</doctype> - <toc>left</toc> - <toclevels>3</toclevels> - <numbered></numbered> - <hardbreaks></hardbreaks> - <sectlinks></sectlinks> - <sectanchors></sectanchors> - <generated>${project.build.directory}/asciidoc/generated</generated> - </attributes> - </configuration> - - <executions> - <execution> - <id>output-html</id> - <phase>test</phase> - <goals> - <goal>process-asciidoc</goal> - </goals> - <configuration> - <backend>html5</backend> - <outputDirectory>${project.basedir}/docs/swagger</outputDirectory> - <outputDirectory>${project.basedir}/src/main/resources/META-INF/resources/</outputDirectory> - </configuration> - </execution> - <execution> - <id>output-pdf</id> - <phase>test</phase> - <goals> - <goal>process-asciidoc</goal> - </goals> - <configuration> - <backend>pdf</backend> - <outputDirectory>${project.basedir}/docs/swagger</outputDirectory> - </configuration> - </execution> - </executions> - </plugin> <plugin> <groupId>org.codehaus.groovy.maven</groupId> <artifactId>gmaven-plugin</artifactId> diff --git a/src/main/java/org/onap/clamp/clds/Application.java b/src/main/java/org/onap/clamp/clds/Application.java index 5975b9d47..fd5deb911 100644 --- a/src/main/java/org/onap/clamp/clds/Application.java +++ b/src/main/java/org/onap/clamp/clds/Application.java @@ -5,20 +5,20 @@ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. + * 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. - * See the License for the specific language governing permissions and + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds; @@ -32,31 +32,32 @@ import org.onap.clamp.clds.model.properties.Holmes; import org.onap.clamp.clds.model.properties.ModelProperties; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; -import org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; -import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; -import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.server.ServletWebServerFactory; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; + @SpringBootApplication @ComponentScan(basePackages = { - "org.onap.clamp.clds" + "org.onap.clamp.clds" }) @EnableAutoConfiguration(exclude = { - DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, - SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class + DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, + SecurityAutoConfiguration.class,UserDetailsServiceAutoConfiguration .class }) @EnableConfigurationProperties @EnableAsync @@ -96,25 +97,25 @@ public class Application extends SpringBootServletInitializer { /** * This method is used to declare the camel servlet. - * + * * @return A servlet bean */ @Bean public ServletRegistrationBean camelServletRegistrationBean() { - ServletRegistrationBean registration = new ServletRegistrationBean(new CamelHttpTransportServlet(), - "/restservices/clds/v2"); + ServletRegistrationBean registration = new ServletRegistrationBean(new ClampServlet(), + "/restservices/clds/v1/*"); registration.setName("CamelServlet"); return registration; } /** * This method is used by Spring to create the servlet container factory. - * + * * @return The TomcatEmbeddedServletContainerFactory just created */ @Bean - public EmbeddedServletContainerFactory getEmbeddedServletContainerFactory() { - TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); + public ServletWebServerFactory getEmbeddedServletContainerFactory() { + TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); if (!"none".equals(httpRedirectedPort) && !"none".equals(sslKeystoreFile)) { // Automatically redirect to HTTPS tomcat = new TomcatEmbeddedServletContainerFactoryRedirection(); @@ -129,7 +130,7 @@ public class Application extends SpringBootServletInitializer { private Connector createRedirectConnector(int redirectSecuredPort) { if (redirectSecuredPort <= 0) { EELF_LOGGER.warn( - "HTTP port redirection to HTTPS is disabled because the HTTPS port is 0 (random port) or -1 (Connector disabled)"); + "HTTP port redirection to HTTPS is disabled because the HTTPS port is 0 (random port) or -1 (Connector disabled)"); return null; } Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); diff --git a/src/main/java/org/onap/clamp/clds/ClampServlet.java b/src/main/java/org/onap/clamp/clds/ClampServlet.java new file mode 100644 index 000000000..2ef57803e --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/ClampServlet.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.clamp.clds; + +import java.io.IOException; +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.ServletException; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.apache.camel.component.servlet.CamelHttpTransportServlet; + +import org.springframework.context.ApplicationContext; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.web.context.support.WebApplicationContextUtils; + +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.service.SecureServicePermission; +import org.onap.clamp.clds.util.ClampTimer; + + +public class ClampServlet extends CamelHttpTransportServlet { + + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ClampServlet.class); + public static final String PERM_INSTANCE = "clamp.config.security.permission.instance"; + public static final String PERM_CL= "clamp.config.security.permission.type.cl"; + public static final String PERM_TEMPLACE = "clamp.config.security.permission.type.template"; + + protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + List<SecureServicePermission> permissionList = new ArrayList<>(); + + // Get Principal info and translate it into Spring Authentication + // If authenticataion is null: a) the authentication info was set manually in the previous thread + // b) handled by Spring automatically + // for the 2 cases above, no need for the translation, just skip the following step + if (null == authentication) { + logger.debug ("Populate Spring Authenticataion info manually."); + ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); + // Start a timer to clear the authentication after 5 mins, so that the authentication will be reinitialized with AAF DB + new ClampTimer(300); + String cldsPersmissionTypeCl = applicationContext.getEnvironment().getProperty(PERM_INSTANCE); + String cldsPermissionTypeTemplate = applicationContext.getEnvironment().getProperty(PERM_CL); + String cldsPermissionInstance = applicationContext.getEnvironment().getProperty(PERM_TEMPLACE); + + // set the stragety to Mode_Global, so that all thread is able to see the authentication + SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL); + Principal p = request.getUserPrincipal(); + + permissionList.add(SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "read")); + permissionList.add(SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "update")); + permissionList.add(SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance, "read")); + permissionList.add(SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance, "update")); + + List<GrantedAuthority> grantedAuths = new ArrayList<>(); + for (SecureServicePermission perm:permissionList) { + String permString = perm.toString(); + if (request.isUserInRole(permString)) { + grantedAuths.add(new SimpleGrantedAuthority(permString)); + } + } + Authentication auth = new UsernamePasswordAuthenticationToken(new User(p.getName(), "", grantedAuths), "", grantedAuths); + SecurityContextHolder.getContext().setAuthentication(auth); + } + super.doService(request, response); + } +}
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/TomcatEmbeddedServletContainerFactoryRedirection.java b/src/main/java/org/onap/clamp/clds/TomcatEmbeddedServletContainerFactoryRedirection.java index 18a44af71..1d9150ee8 100644 --- a/src/main/java/org/onap/clamp/clds/TomcatEmbeddedServletContainerFactoryRedirection.java +++ b/src/main/java/org/onap/clamp/clds/TomcatEmbeddedServletContainerFactoryRedirection.java @@ -5,20 +5,20 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights * reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. + * 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. - * See the License for the specific language governing permissions and + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds; @@ -26,18 +26,18 @@ package org.onap.clamp.clds; import org.apache.catalina.Context; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; -import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; /** * This class is a factory that redirects by default all HTTP to HTTPS * connector. It is used by the Application.java class and defined in a Spring * Bean. - * + * * In order to do this, the method postProcessContext has been overridden to * provide another behavior. - * + * */ -public class TomcatEmbeddedServletContainerFactoryRedirection extends TomcatEmbeddedServletContainerFactory { +public class TomcatEmbeddedServletContainerFactoryRedirection extends TomcatServletWebServerFactory { /** * This method is there to force the automatic redirection of all calls done diff --git a/src/main/java/org/onap/clamp/clds/service/JaxrsApplication.java b/src/main/java/org/onap/clamp/clds/config/CamelConfiguration.java index 56fbca8da..16cbd840a 100644 --- a/src/main/java/org/onap/clamp/clds/service/JaxrsApplication.java +++ b/src/main/java/org/onap/clamp/clds/config/CamelConfiguration.java @@ -18,17 +18,23 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * */ - -package org.onap.clamp.clds.service; - -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; - +package org.onap.clamp.clds.config; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.model.rest.RestBindingMode; +import org.onap.clamp.clds.model.CldsInfo; import org.springframework.stereotype.Component; + @Component -@ApplicationPath("/restservices/clds/v1") -public class JaxrsApplication extends Application { +public class CamelConfiguration extends RouteBuilder { + + @Override + public void configure() { + restConfiguration().component("servlet") + .bindingMode(RestBindingMode.json); -}
\ No newline at end of file + rest("/clds") + .get("/test").description("Find user by id").outType(CldsInfo.class).produces("application/json") + .to("bean:org.onap.clamp.clds.service.CldsService?method=getCldsInfo()") ; + } +} diff --git a/src/main/java/org/onap/clamp/clds/config/ClampUserWrap.java b/src/main/java/org/onap/clamp/clds/config/ClampUserWrap.java deleted file mode 100644 index a2b6c07d0..000000000 --- a/src/main/java/org/onap/clamp/clds/config/ClampUserWrap.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ - -package org.onap.clamp.clds.config; - -import java.security.Principal; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; - -/** - * Overwrite the key method isUserInRole and getUserPrincipal, to adapt to the Clamp default user verification - */ -public class ClampUserWrap extends HttpServletRequestWrapper { - - private String user; - private List<String> roles = null; - private HttpServletRequest realRequest; - - /** - * Standard Wrapper constructor for Delegate pattern - * @param request - */ - public ClampUserWrap(HttpServletRequest request, String userName, List<String> roles){ - super(request); - - this.user = userName; - this.roles = roles; - this.realRequest = request; - } - - @Override - public boolean isUserInRole(String role) { - if (roles == null) { - return this.realRequest.isUserInRole(role); - } - return roles.contains(role); - } - - @Override - public Principal getUserPrincipal() { - if (this.user == null) { - return realRequest.getUserPrincipal(); - } - - // make an anonymous implementation to just return our user - return new Principal() { - @Override - public String getName() { - return user; - } - }; - } -} diff --git a/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java b/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java index e43aa114d..a99dde207 100644 --- a/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java @@ -18,45 +18,120 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * */ + package org.onap.clamp.clds.config; -import javax.servlet.Filter; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; -import org.onap.clamp.clds.filter.ClampDefaultUserFilter; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; +import java.io.IOException; + +import org.onap.clamp.clds.exception.CldsConfigException; +import org.onap.clamp.clds.exception.CldsUsersException; +import org.onap.clamp.clds.service.CldsUser; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +/** + * This class is used to enable the HTTP authentication to login. It requires a + * specific JSON file containing the user definition + * (classpath:clds/clds-users.json). + */ @Configuration +@EnableWebSecurity @Profile("clamp-default-user") -public class DefaultUserConfiguration { +public class DefaultUserConfiguration extends WebSecurityConfigurerAdapter { + + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DefaultUserConfiguration.class); + protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + @Autowired + private ClampProperties refProp; + @Value("${clamp.config.security.permission.type.cl:permission-type-cl}") + private String cldsPersmissionTypeCl; + @Value("${CLDS_PERMISSION_INSTANCE:dev}") + private String cldsPermissionInstance; + @Value("${clamp.config.security.encoder:bcrypt}") + private String cldsEncoderMethod; + @Value("${clamp.config.security.encoder.bcrypt.strength:10}") + private Integer cldsBcryptEncoderStrength; + + /** + * This method configures on which URL the authorization will be enabled. + */ + @Override + protected void configure(HttpSecurity http) { + try { + http.csrf().disable().httpBasic().and().authorizeRequests().antMatchers("/restservices/clds/v1/user/**") + .authenticated().anyRequest().permitAll().and().logout().and().sessionManagement().maximumSessions(1) + .and().invalidSessionUrl("/designer/timeout.html"); + + } catch (Exception e) { + logger.error("Exception occurred during the setup of the Web users in memory", e); + throw new CldsUsersException("Exception occurred during the setup of the Web users in memory", e); + } + } /** - * Method to return clamp default user filter. - * - * @return Filter + * This method is called by the framework and is used to load all the users + * defined in cldsUsersFile variable (this file path can be configured in the + * application.properties). + * + * @param auth */ - @Bean(name = "defaultUserFilter") - public Filter defaultUserFilter() { - return new ClampDefaultUserFilter(); + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) { + // configure algorithm used for password hashing + final PasswordEncoder passwordEncoder = getPasswordEncoder(); + + try { + CldsUser[] usersList = loadUsers(); + // no users defined + if (null == usersList) { + logger.warn("No users defined. Users should be defined under clds-users.json"); + return; + } + for (CldsUser user : usersList) { + auth.inMemoryAuthentication().withUser(user.getUser()).password(user.getPassword()) + .authorities(user.getPermissionsString()).and().passwordEncoder(passwordEncoder); + } + } catch (Exception e) { + logger.error("Exception occurred during the setup of the Web users in memory", e); + throw new CldsUsersException("Exception occurred during the setup of the Web users in memory", e); + } } /** - * Method to register defaultUserFilter. - * - * @return FilterRegistrationBean + * This method loads physically the JSON file and convert it to an Array of + * CldsUser. + * + * @return The array of CldsUser + * @throws IOException + * In case of the file is not found */ - @Bean - public FilterRegistrationBean defaultUserFilterRegistration() { - FilterRegistrationBean registration = new FilterRegistrationBean(); - registration.setFilter(defaultUserFilter()); - registration.addUrlPatterns("/restservices/*"); - registration.setName("defaultUserFilter"); - registration.setOrder(0); - return registration; + private CldsUser[] loadUsers() throws IOException { + logger.info("Load from clds-users.properties"); + return CldsUserJsonDecoder.decodeJson(refProp.getFileContent("files.cldsUsers")); } + /** + * This methods returns the chosen encoder for password hashing. + */ + private PasswordEncoder getPasswordEncoder() { + if ("bcrypt".equals(cldsEncoderMethod)) { + return new BCryptPasswordEncoder(cldsBcryptEncoderStrength); + } else { + throw new CldsConfigException( + "Invalid clamp.config.security.encoder value. 'bcrypt' is the only option at this time."); + } + } }
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/filter/ClampCadiFilter.java b/src/main/java/org/onap/clamp/clds/filter/ClampCadiFilter.java index 1c3ba1cf6..ed3dcb46a 100644 --- a/src/main/java/org/onap/clamp/clds/filter/ClampCadiFilter.java +++ b/src/main/java/org/onap/clamp/clds/filter/ClampCadiFilter.java @@ -22,26 +22,15 @@ */ package org.onap.clamp.clds.filter; -import javax.servlet.FilterConfig; - -import java.io.IOException; -import java.security.Principal; -import java.security.cert.X509Certificate; import java.util.Properties; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.context.SecurityContextImpl; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.beans.factory.annotation.Value; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; import org.onap.aaf.cadi.filter.CadiFilter; import org.onap.clamp.clds.config.AAFConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; public class ClampCadiFilter extends CadiFilter { private static final String CADI_TRUST_STORE = "cadi_truststore"; @@ -52,13 +41,13 @@ public class ClampCadiFilter extends CadiFilter { @Value("${server.ssl.key-store:none}") private String keyStore; - + @Value("${clamp.config.cadi.cadiKeystorePassword:none}") private String keyStorePass; @Value("${server.ssl.trust:none}") private String trustStore; - + @Value("${clamp.config.cadi.cadiTruststorePassword:none}") private String trustStorePass; @@ -67,7 +56,7 @@ public class ClampCadiFilter extends CadiFilter { @Autowired private AAFConfiguration aafConfiguration; - + @Override public void init(FilterConfig filterConfig) throws ServletException { Properties props = aafConfiguration.getProperties(); @@ -82,7 +71,7 @@ public class ClampCadiFilter extends CadiFilter { private String trimFileName (String fileName) { int index= fileName.indexOf("file:"); - if (index == -1) { + if (index == -1) { return fileName; } else { return fileName.substring(index+5); diff --git a/src/main/java/org/onap/clamp/clds/filter/ClampDefaultUserFilter.java b/src/main/java/org/onap/clamp/clds/filter/ClampDefaultUserFilter.java deleted file mode 100644 index 539e3c6a5..000000000 --- a/src/main/java/org/onap/clamp/clds/filter/ClampDefaultUserFilter.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.clamp.clds.filter; - -import java.io.IOException; -import java.util.Arrays; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; -import org.onap.clamp.clds.config.ClampProperties; -import org.onap.clamp.clds.config.ClampUserWrap; -import org.onap.clamp.clds.config.CldsUserJsonDecoder; -import org.onap.clamp.clds.exception.CldsUsersException; -import org.onap.clamp.clds.service.CldsUser; - - -public class ClampDefaultUserFilter implements Filter { - private CldsUser defaultUser; - @Autowired - private ClampProperties refProp; - - // Load the default user - public void init(FilterConfig cfg) throws ServletException { - try { - CldsUser[] users = CldsUserJsonDecoder.decodeJson(refProp.getFileContent("files.cldsUsers")); - defaultUser = users[0]; - } catch (IOException e) { - // not able to load default user - throw new CldsUsersException("Exception occurred during the decoding of the clds-users.json", e); - } - } - - // Call the ClampUserWrapper - @Override - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException { - HttpServletRequest hreq = (HttpServletRequest)req; - chain.doFilter(new ClampUserWrap(hreq, defaultUser.getUser(), Arrays.asList(defaultUser.getPermissionsString())), res); - } - - public void destroy() { - } -} diff --git a/src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java b/src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java index 18533ad5a..a017d54b0 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java @@ -5,61 +5,53 @@ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. + * 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. - * See the License for the specific language governing permissions and + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ * =================================================================== */ package org.onap.clamp.clds.service; -import java.util.Date; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import java.util.Date; import org.onap.clamp.clds.dao.CldsDao; import org.onap.clamp.clds.model.CldsHealthCheck; import org.onap.clamp.clds.util.LoggingUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - /** * Service to retrieve the Health Check of the clds application. - * + * */ @Component -@Path("/") public class CldsHealthcheckService { - - @Autowired - private CldsDao cldsDao; - - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsHealthcheckService.class); - - /** + + @Autowired + private CldsDao cldsDao; + + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsHealthcheckService.class); + + /** * REST service that retrieves clds healthcheck information. * * @return CldsHealthCheck class containing healthcheck info */ - @GET - @Path("/healthcheck") - @Produces(MediaType.APPLICATION_JSON) - public Response gethealthcheck() { + public ResponseEntity<CldsHealthCheck> gethealthcheck() { CldsHealthCheck cldsHealthCheck = new CldsHealthCheck(); Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: GET healthcheck", "Clamp-Health-Check"); @@ -72,7 +64,7 @@ public class CldsHealthcheckService { cldsHealthCheck.setDescription("OK"); LoggingUtils.setResponseContext("0", "Get healthcheck success", this.getClass().getName()); } catch (Exception e) { - healthcheckFailed = true; + healthcheckFailed = true; logger.error("CLAMP application Heath check failed", e); LoggingUtils.setResponseContext("999", "Get healthcheck failed", this.getClass().getName()); cldsHealthCheck.setHealthCheckComponent("CLDS-APP"); @@ -82,9 +74,9 @@ public class CldsHealthcheckService { // audit log LoggingUtils.setTimeContext(startTime, new Date()); if(healthcheckFailed) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(cldsHealthCheck).build(); + return new ResponseEntity<>(cldsHealthCheck, HttpStatus.INTERNAL_SERVER_ERROR); } else { - return Response.status(Response.Status.OK).entity(cldsHealthCheck).build(); + return new ResponseEntity<>(cldsHealthCheck, HttpStatus.OK); } } }
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/service/CldsService.java b/src/main/java/org/onap/clamp/clds/service/CldsService.java index a63d02185..d6fbde356 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -34,23 +34,12 @@ import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Date; import java.util.List; +import java.util.Optional; import java.util.UUID; - import javax.ws.rs.BadRequestException; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.NotAuthorizedException; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import javax.xml.transform.TransformerException; + import org.apache.camel.Produce; import org.apache.commons.codec.DecoderException; import org.apache.commons.lang3.StringUtils; @@ -61,12 +50,12 @@ import org.onap.clamp.clds.client.DcaeInventoryServices; import org.onap.clamp.clds.client.req.sdc.SdcCatalogServices; import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.dao.CldsDao; + import org.onap.clamp.clds.exception.CldsConfigException; import org.onap.clamp.clds.exception.policy.PolicyClientException; import org.onap.clamp.clds.exception.sdc.SdcCommunicationException; import org.onap.clamp.clds.model.CldsDbServiceCache; import org.onap.clamp.clds.model.CldsEvent; -import org.onap.clamp.clds.model.CldsHealthCheck; import org.onap.clamp.clds.model.CldsInfo; import org.onap.clamp.clds.model.CldsModel; import org.onap.clamp.clds.model.CldsModelProp; @@ -87,6 +76,7 @@ import org.onap.clamp.clds.util.LoggingUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpClientErrorException; @@ -94,7 +84,6 @@ import org.springframework.web.client.HttpClientErrorException; * Service to save and retrieve the CLDS model attributes. */ @Component -@Path("/clds") public class CldsService extends SecureServiceBase { @Produce(uri = "direct:processSubmit") @@ -160,9 +149,6 @@ public class CldsService extends SecureServiceBase { * used to generate the ClosedLoop model. ACTION_CD | Current state of the * ClosedLoop in CLDS application. */ - @GET - @Path("/cldsDetails") - @Produces(MediaType.APPLICATION_JSON) public List<CldsMonitoringDetails> getCLDSDetails() { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: GET model details", getPrincipalName()); @@ -178,9 +164,6 @@ public class CldsService extends SecureServiceBase { * CLDS IFO service will return 3 things 1. User Name 2. CLDS code version that * is currently installed from pom.xml file 3. User permissions */ - @GET - @Path("/cldsInfo") - @Produces(MediaType.APPLICATION_JSON) public CldsInfo getCldsInfo() { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: GET cldsInfo", getPrincipalName()); @@ -197,44 +180,6 @@ public class CldsService extends SecureServiceBase { } /** - * REST service that retrieves clds healthcheck information. - * - * @return CldsHealthCheck class containing healthcheck info - */ - @GET - @Path("/healthcheck") - @Produces(MediaType.APPLICATION_JSON) - public Response gethealthcheck() { - CldsHealthCheck cldsHealthCheck = new CldsHealthCheck(); - Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET healthcheck", "Clamp-Health-Check"); - LoggingUtils.setTimeContext(startTime, new Date()); - boolean healthcheckFailed = false; - try { - cldsDao.doHealthCheck(); - cldsHealthCheck.setHealthCheckComponent("CLDS-APP"); - cldsHealthCheck.setHealthCheckStatus("UP"); - cldsHealthCheck.setDescription("OK"); - LoggingUtils.setResponseContext("0", "Get healthcheck success", this.getClass().getName()); - } catch (Exception e) { - healthcheckFailed = true; - logger.error("CLAMP application DB Error", e); - LoggingUtils.setResponseContext("999", "Get healthcheck failed", this.getClass().getName()); - cldsHealthCheck.setHealthCheckComponent("CLDS-APP"); - cldsHealthCheck.setHealthCheckStatus("DOWN"); - cldsHealthCheck.setDescription("NOT-OK"); - } - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - logger.info("GET healthcheck completed"); - if (healthcheckFailed) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(cldsHealthCheck).build(); - } else { - return Response.status(Response.Status.OK).entity(cldsHealthCheck).build(); - } - } - - /** * REST service that retrieves BPMN for a CLDS model name from the database. * This is subset of the json getModel. This is only expected to be used for * testing purposes, not by the UI. @@ -242,10 +187,7 @@ public class CldsService extends SecureServiceBase { * @param modelName * @return bpmn xml text - content of bpmn given name */ - @GET - @Path("/model/bpmn/{modelName}") - @Produces(MediaType.TEXT_XML) - public String getBpmnXml(@PathParam("modelName") String modelName) { + public String getBpmnXml(String modelName) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: GET model bpmn", getPrincipalName()); isAuthorized(permissionReadCl); @@ -266,10 +208,7 @@ public class CldsService extends SecureServiceBase { * @param modelName * @return image xml text - content of image given name */ - @GET - @Path("/model/image/{modelName}") - @Produces(MediaType.TEXT_XML) - public String getImageXml(@PathParam("modelName") String modelName) { + public String getImageXml(String modelName) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: GET model image", getPrincipalName()); isAuthorized(permissionReadCl); @@ -288,10 +227,7 @@ public class CldsService extends SecureServiceBase { * @param modelName * @return clds model - clds model for the given model name */ - @GET - @Path("/model/{modelName}") - @Produces(MediaType.APPLICATION_JSON) - public CldsModel getModel(@PathParam("modelName") String modelName) { + public CldsModel getModel(String modelName) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: GET model", getPrincipalName()); isAuthorized(permissionReadCl); @@ -320,11 +256,7 @@ public class CldsService extends SecureServiceBase { * * @param modelName */ - @PUT - @Path("/model/{modelName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public CldsModel putModel(@PathParam("modelName") String modelName, CldsModel cldsModel) { + public CldsModel putModel(String modelName, CldsModel cldsModel) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: PUT model", getPrincipalName()); isAuthorized(permissionUpdateCl); @@ -350,9 +282,6 @@ public class CldsService extends SecureServiceBase { * * @return model names in JSON */ - @GET - @Path("/model-names") - @Produces(MediaType.APPLICATION_JSON) public List<ValueItem> getModelNames() { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: GET model names", getPrincipalName()); @@ -397,12 +326,8 @@ public class CldsService extends SecureServiceBase { * @throws DecoderException * In case of issues with the Hex String decoding */ - @PUT - @Path("/action/{action}/{modelName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response putModelAndProcessAction(@PathParam("action") String action, - @PathParam("modelName") String modelName, @QueryParam("test") String validateFlag, CldsModel model) + public ResponseEntity<?> putModelAndProcessAction(String action, + String modelName,String test, CldsModel model) throws TransformerException, ParseException { Date startTime = new Date(); CldsModel retrievedModel = null; @@ -417,7 +342,7 @@ public class CldsService extends SecureServiceBase { String userId = getUserId(); logger.info("PUT actionCd={}", actionCd); logger.info("PUT modelName={}", modelName); - logger.info("PUT test={}", validateFlag); + logger.info("PUT test={}", test); logger.info("PUT bpmnText={}", model.getBpmnText()); logger.info("PUT propText={}", model.getPropText()); logger.info("PUT userId={}", userId); @@ -438,7 +363,7 @@ public class CldsService extends SecureServiceBase { // Flag indicates whether it is triggered by Validation Test button // from // UI - boolean isTest = Boolean.valueOf(validateFlag); + boolean isTest = Boolean.valueOf(test); if (!isTest) { String actionTestOverride = refProp.getStringValue("action.test.override"); if (Boolean.valueOf(actionTestOverride)) { @@ -495,16 +420,16 @@ public class CldsService extends SecureServiceBase { auditLogger.info("Process model action completed"); } else { logger.error("CldsModel not found in database with modelName: " + modelName); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("CldsModel not found in database with modelName: \" + modelName").build(); + return new ResponseEntity<String>("CldsModel not found in database with modelName: \" + modelName", HttpStatus.INTERNAL_SERVER_ERROR); } } catch (Exception e) { errorCase = true; logger.error("Exception occured during putModelAndProcessAction", e); } if (errorCase) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(retrievedModel).build(); + return new ResponseEntity<>(retrievedModel, HttpStatus.INTERNAL_SERVER_ERROR); } - return Response.status(Response.Status.OK).entity(retrievedModel).build(); + return new ResponseEntity<>(retrievedModel, HttpStatus.OK); } /** @@ -513,11 +438,7 @@ public class CldsService extends SecureServiceBase { * @param test * @param dcaeEvent */ - @POST - @Path("/dcae/event") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public String postDcaeEvent(@QueryParam("test") String test, DcaeEvent dcaeEvent) { + public String postDcaeEvent(String test, DcaeEvent dcaeEvent) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: Post dcae event", getPrincipalName()); String userid = null; @@ -565,9 +486,6 @@ public class CldsService extends SecureServiceBase { * @throws DecoderException * In case of issues with the decoding of the Hex String */ - @GET - @Path("/sdc/services") - @Produces(MediaType.APPLICATION_JSON) public String getSdcServices() throws GeneralSecurityException, DecoderException { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: GET sdc services", getPrincipalName()); @@ -592,9 +510,6 @@ public class CldsService extends SecureServiceBase { * @throws IOException * In case of issues */ - @GET - @Path("/properties") - @Produces(MediaType.APPLICATION_JSON) public String getSdcProperties() throws IOException { return createPropertiesObjectByUUID("{}"); } @@ -610,18 +525,14 @@ public class CldsService extends SecureServiceBase { * @throws IOException * In case of issue to convert CldsServiceCache to InputStream */ - @GET - @Path("/properties/{serviceInvariantUUID}") - @Produces(MediaType.APPLICATION_JSON) public String getSdcPropertiesByServiceUUIDForRefresh( - @PathParam("serviceInvariantUUID") String serviceInvariantUUID, - @DefaultValue("false") @QueryParam("refresh") boolean refresh) + String serviceInvariantUUID, Boolean refresh) throws GeneralSecurityException, DecoderException, IOException { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: GET sdc properties by uuid", getPrincipalName()); CldsServiceData cldsServiceData = new CldsServiceData(); cldsServiceData.setServiceInvariantUUID(serviceInvariantUUID); - if (!refresh) { + if (!Optional.ofNullable(refresh).orElse(false)) { cldsServiceData = cldsDao.getCldsServiceCache(serviceInvariantUUID); } if (sdcCatalogServices.isCldsSdcCacheDataExpired(cldsServiceData)) { @@ -808,11 +719,7 @@ public class CldsService extends SecureServiceBase { return emptyvfcobjectNode; } - @PUT - @Path("/deploy/{modelName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response deployModel(@PathParam("modelName") String modelName, CldsModel model) { + public ResponseEntity<CldsModel> deployModel(String modelName, CldsModel model) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: Deploy model", getPrincipalName()); Boolean errorCase = false; @@ -865,16 +772,12 @@ public class CldsService extends SecureServiceBase { logger.error("Exception occured during deployModel", e); } if (errorCase) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(model).build(); + return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR); } - return Response.status(Response.Status.OK).entity(model).build(); + return new ResponseEntity<>(model, HttpStatus.OK); } - @PUT - @Path("/undeploy/{modelName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response unDeployModel(@PathParam("modelName") String modelName, CldsModel model) { + public ResponseEntity<CldsModel> unDeployModel(String modelName, CldsModel model) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: Undeploy model", getPrincipalName()); Boolean errorCase = false; @@ -914,9 +817,9 @@ public class CldsService extends SecureServiceBase { logger.error("Exception occured during unDeployModel", e); } if (errorCase) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(model).build(); + return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR); } - return Response.status(Response.Status.OK).entity(model).build(); + return new ResponseEntity<>(model, HttpStatus.OK); } private void checkForDuplicateServiceVf(String modelName, String modelPropText) throws IOException { diff --git a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java index 9e5068209..276670e2b 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java @@ -18,7 +18,7 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds.service; @@ -27,13 +27,6 @@ import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; import org.onap.clamp.clds.dao.CldsDao; import org.onap.clamp.clds.model.CldsTemplate; @@ -47,7 +40,6 @@ import org.springframework.stereotype.Component; * Service to save and retrieve the CLDS model attributes. */ @Component -@Path("/cldsTempate") public class CldsTemplateService extends SecureServiceBase { @Value("${clamp.config.security.permission.type.template:permission-type-template}") @@ -60,9 +52,9 @@ public class CldsTemplateService extends SecureServiceBase { @PostConstruct private final void afterConstruction() { permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance, - "read"); + "read"); permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance, - "update"); + "update"); } @Autowired @@ -76,10 +68,7 @@ public class CldsTemplateService extends SecureServiceBase { * @param templateName * @return bpmn xml text - content of bpmn given name */ - @GET - @Path("/template/bpmn/{templateName}") - @Produces(MediaType.TEXT_XML) - public String getBpmnTemplate(@PathParam("templateName") String templateName) { + public String getBpmnTemplate(String templateName) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsTemplateService: GET template bpmn", getPrincipalName()); isAuthorized(permissionReadTemplate); @@ -100,10 +89,7 @@ public class CldsTemplateService extends SecureServiceBase { * @param templateName * @return image xml text - content of image given name */ - @GET - @Path("/template/image/{templateName}") - @Produces(MediaType.TEXT_XML) - public String getImageXml(@PathParam("templateName") String templateName) { + public String getImageXml(String templateName) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsTemplateService: GET template image", getPrincipalName()); isAuthorized(permissionReadTemplate); @@ -122,10 +108,7 @@ public class CldsTemplateService extends SecureServiceBase { * @param templateName * @return clds template - clds template for the given template name */ - @GET - @Path("/template/{templateName}") - @Produces(MediaType.APPLICATION_JSON) - public CldsTemplate getTemplate(@PathParam("templateName") String templateName) { + public CldsTemplate getTemplate(String templateName) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsTemplateService: GET template", getPrincipalName()); isAuthorized(permissionReadTemplate); @@ -146,11 +129,7 @@ public class CldsTemplateService extends SecureServiceBase { * @param cldsTemplate * @return The CldsTemplate modified and saved in DB */ - @PUT - @Path("/template/{templateName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public CldsTemplate putTemplate(@PathParam("templateName") String templateName, CldsTemplate cldsTemplate) { + public CldsTemplate putTemplate(String templateName, CldsTemplate cldsTemplate) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsTemplateService: PUT template", getPrincipalName()); isAuthorized(permissionUpdateTemplate); @@ -172,9 +151,6 @@ public class CldsTemplateService extends SecureServiceBase { * * @return template names in JSON */ - @GET - @Path("/template-names") - @Produces(MediaType.APPLICATION_JSON) public List<ValueItem> getTemplateNames() { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsTemplateService: GET template names", getPrincipalName()); diff --git a/src/main/java/org/onap/clamp/clds/service/DefaultUserNameHandler.java b/src/main/java/org/onap/clamp/clds/service/DefaultUserNameHandler.java index 44372b62a..543dd4a92 100644 --- a/src/main/java/org/onap/clamp/clds/service/DefaultUserNameHandler.java +++ b/src/main/java/org/onap/clamp/clds/service/DefaultUserNameHandler.java @@ -5,40 +5,39 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
+ * 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.
- * See the License for the specific language governing permissions and
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END============================================
* ===================================================================
- *
+ *
*/
package org.onap.clamp.clds.service;
-import java.security.Principal;
+import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.core.userdetails.UserDetails;
+
-import javax.ws.rs.core.SecurityContext;
public class DefaultUserNameHandler implements UserNameHandler {
/*
* (non-Javadoc)
- *
+ *
* @see
- * org.onap.clamp.clds.service.PrincipalNameHandler#handleName(javax.ws.rs.
- * core.SecurityContext)
+ * org.onap.clamp.clds.service.PrincipalNameHandler#handleName(SecurityContext)
*/
@Override
public String retrieveUserName(SecurityContext securityContext) {
- Principal p = securityContext.getUserPrincipal();
- return (p == null ? "Not found" : p.getName());
+ return ((UserDetails)securityContext.getAuthentication().getPrincipal()).getUsername();
}
}
diff --git a/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java b/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java index 22fe4a8e0..522f682b7 100644 --- a/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java +++ b/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java @@ -18,7 +18,7 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds.service; @@ -26,14 +26,15 @@ package org.onap.clamp.clds.service; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import java.security.Principal; import java.util.Date; - import javax.ws.rs.NotAuthorizedException; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.SecurityContext; import org.onap.clamp.clds.util.LoggingUtils; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; /** * Base/abstract Service class. Implements shared security methods. @@ -46,8 +47,8 @@ public abstract class SecureServiceBase { // By default we'll set it to a default handler private static UserNameHandler userNameHandler = new DefaultUserNameHandler(); - @Context - private SecurityContext securityContext; + + private SecurityContext securityContext = SecurityContextHolder.getContext(); /** * Get the userId from AAF/CSP. @@ -78,10 +79,10 @@ public abstract class SecureServiceBase { * @return */ public String getPrincipalName() { - Principal principal = securityContext.getUserPrincipal(); + String principal = ((UserDetails)securityContext.getAuthentication().getPrincipal()).getUsername(); String name = "Not found"; if (principal != null) { - name = principal.getName(); + name = principal; } logger.debug("userPrincipal.getName()={}", name); return name; @@ -103,20 +104,20 @@ public abstract class SecureServiceBase { * In case of issues with the permission test, error is returned * in this exception */ - public boolean isAuthorized(SecureServicePermission inPermission) throws NotAuthorizedException { - Date startTime = new Date(); - LoggingUtils.setTargetContext("CLDS", "isAuthorized"); - LoggingUtils.setTimeContext(startTime, new Date()); - securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission); - try { - return isUserPermitted(inPermission); - } catch (NotAuthorizedException nae) { - String msg = getPrincipalName() + " does not have permission: " + inPermission; - LoggingUtils.setErrorContext("100", "Authorization Error"); - securityLogger.warn(msg); - throw new NotAuthorizedException(msg); - } - } + public boolean isAuthorized(SecureServicePermission inPermission) throws NotAuthorizedException { + Date startTime = new Date(); + LoggingUtils.setTargetContext("CLDS", "isAuthorized"); + LoggingUtils.setTimeContext(startTime, new Date()); + securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission); + try { + return isUserPermitted(inPermission); + } catch (NotAuthorizedException nae) { + String msg = getPrincipalName() + " does not have permission: " + inPermission; + LoggingUtils.setErrorContext("100", "Authorization Error"); + securityLogger.warn(msg); + throw new NotAuthorizedException(msg); + } + } /** * Check if user is authorized for the given aaf permission. Allow matches @@ -131,26 +132,26 @@ public abstract class SecureServiceBase { * @return A boolean to indicate if the user has the permission to do * execute the inPermission */ - public boolean isAuthorizedNoException(SecureServicePermission inPermission) { - securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission); - Date startTime = new Date(); - LoggingUtils.setTargetContext("CLDS", "isAuthorizedNoException"); - LoggingUtils.setTimeContext(startTime, new Date()); - try { - return isUserPermitted(inPermission); - } catch (NotAuthorizedException nae) { - String msg = getPrincipalName() + " does not have permission: " + inPermission; - LoggingUtils.setErrorContext("100", "Authorization Error"); - securityLogger.warn(msg); - } - return false; - } + public boolean isAuthorizedNoException(SecureServicePermission inPermission) { + securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission); + Date startTime = new Date(); + LoggingUtils.setTargetContext("CLDS", "isAuthorizedNoException"); + LoggingUtils.setTimeContext(startTime, new Date()); + try { + return isUserPermitted(inPermission); + } catch (NotAuthorizedException nae) { + String msg = getPrincipalName() + " does not have permission: " + inPermission; + LoggingUtils.setErrorContext("100", "Authorization Error"); + securityLogger.warn(msg); + } + return false; + } /** * This method can be used by the Application.class to set the * UserNameHandler that must be used in this class. The UserNameHandler * where to get the User name - * + * * @param handler * The Handler impl to use */ @@ -163,28 +164,42 @@ public abstract class SecureServiceBase { public void setSecurityContext(SecurityContext securityContext) { this.securityContext = securityContext; } - - private boolean isUserPermitted(SecureServicePermission inPermission) throws NotAuthorizedException { - boolean authorized = false; - // check if the user has the permission key or the permission key with a + + private boolean isUserPermitted(SecureServicePermission inPermission) { + boolean authorized = false; + // check if the user has the permission key or the permission key with a // combination of all instance and/or all action. - if (securityContext.isUserInRole(inPermission.getKey())) { - securityLogger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey()); + if (hasRole(inPermission.getKey())) { + securityLogger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey()); authorized = true; // the rest of these don't seem to be required - isUserInRole method // appears to take * as a wildcard - } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) { + } else if (hasRole(inPermission.getKeyAllInstance())) { securityLogger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(), inPermission.getKey()); authorized = true; - } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) { - securityLogger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey()); + } else if (hasRole(inPermission.getKeyAllInstanceAction())) { + securityLogger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey()); authorized = true; - } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) { - securityLogger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey()); + } else if (hasRole(inPermission.getKeyAllAction())) { + securityLogger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey()); authorized = true; } else { throw new NotAuthorizedException(""); } return authorized; } + + protected boolean hasRole(String role) { + Authentication authentication = securityContext.getAuthentication(); + if (authentication == null) { + return false; + } + + for (GrantedAuthority auth : authentication.getAuthorities()) { + if (role.equals(auth.getAuthority())) + return true; + } + + return false; + } }
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/service/SecureServicePermission.java b/src/main/java/org/onap/clamp/clds/service/SecureServicePermission.java index 2d4de6449..ae30d2aa3 100644 --- a/src/main/java/org/onap/clamp/clds/service/SecureServicePermission.java +++ b/src/main/java/org/onap/clamp/clds/service/SecureServicePermission.java @@ -5,20 +5,20 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights * reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. + * 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. - * See the License for the specific language governing permissions and + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds.service; @@ -28,7 +28,7 @@ package org.onap.clamp.clds.service; * methods. */ public class SecureServicePermission { - public final static String ALL = "*"; + public static final String ALL = "*"; private String type; private String instance; diff --git a/src/main/java/org/onap/clamp/clds/service/UserNameHandler.java b/src/main/java/org/onap/clamp/clds/service/UserNameHandler.java index bd3aa93a1..d48700f6a 100644 --- a/src/main/java/org/onap/clamp/clds/service/UserNameHandler.java +++ b/src/main/java/org/onap/clamp/clds/service/UserNameHandler.java @@ -5,25 +5,25 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
+ * 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.
- * See the License for the specific language governing permissions and
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END============================================
* ===================================================================
- *
+ *
*/
package org.onap.clamp.clds.service;
-import javax.ws.rs.core.SecurityContext;
+import org.springframework.security.core.context.SecurityContext;
public interface UserNameHandler {
diff --git a/src/main/java/org/onap/clamp/clds/service/UserService.java b/src/main/java/org/onap/clamp/clds/service/UserService.java index 996116090..cfe50c95f 100644 --- a/src/main/java/org/onap/clamp/clds/service/UserService.java +++ b/src/main/java/org/onap/clamp/clds/service/UserService.java @@ -5,16 +5,16 @@ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. + * 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. - * See the License for the specific language governing permissions and + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ * =================================================================== @@ -22,28 +22,20 @@ package org.onap.clamp.clds.service; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.SecurityContext; -import org.springframework.stereotype.Component; + +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; /** * User service used for authorization verification at the login page. Do not * remove this class. */ -@Component -@Path("/user") -@Produces({ - MediaType.TEXT_PLAIN -}) +@Controller public class UserService { - @Context - private SecurityContext securityContext; + + private SecurityContext securityContext= SecurityContextHolder.getContext(); /** * REST service that returns the username. @@ -51,12 +43,7 @@ public class UserService { * @param userName * @return the user name */ - @GET - @Path("/getUser") - @Produces(MediaType.TEXT_PLAIN) public String getUser() { - UserNameHandler userNameHandler = new DefaultUserNameHandler(); - String userName = userNameHandler.retrieveUserName(securityContext); - return userName; + return new DefaultUserNameHandler().retrieveUserName(securityContext); } }
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/util/ClampTimer.java b/src/main/java/org/onap/clamp/clds/util/ClampTimer.java new file mode 100644 index 000000000..794e2b486 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/util/ClampTimer.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ +package org.onap.clamp.clds.util; + +import java.util.Timer; +import java.util.TimerTask; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.springframework.security.core.context.SecurityContextHolder; + +/** + * Define the ClampTimer and CleanupTask, to clear up the Spring Authenticataion info when time is up. + */ + +public class ClampTimer { + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ClampTimer.class); + Timer timer; + + public ClampTimer(int seconds) { + timer = new Timer(); + timer.schedule(new CleanupTask(), seconds*1000); + } + + class CleanupTask extends TimerTask { + public void run() { + logger.debug("Time is up, clear the Spring authenticataion settings"); + //Clear up the spring authentication + SecurityContextHolder.getContext().setAuthentication(null); + //Terminate the timer thread + timer.cancel(); + } + } +}
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java index 7a6667c40..71835fa10 100644 --- a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java @@ -31,7 +31,7 @@ import java.util.Date; import java.util.TimeZone;
import java.util.UUID;
import javax.validation.constraints.NotNull;
-import org.apache.log4j.MDC;
+import org.slf4j.MDC;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
diff --git a/src/main/resources/META-INF/resources/designer/scripts/CldsModelService.js b/src/main/resources/META-INF/resources/designer/scripts/CldsModelService.js index 32c11221e..9cff04531 100644 --- a/src/main/resources/META-INF/resources/designer/scripts/CldsModelService.js +++ b/src/main/resources/META-INF/resources/designer/scripts/CldsModelService.js @@ -64,8 +64,12 @@ app.service('cldsModelService', ['alertService', '$http', '$q', function(alertSe $http.put(deployUrl, requestData) .success(function(data) { - deploymentId = data.deploymentId; - def.resolve(data); + var newData = data; + if (typeof data.body !== 'undefined') { + newData = data.body; + } + deploymentId = newData.deploymentId; + def.resolve(newData); alertService.alertMessage("Action Successful:" + uiAction, 1) }) .error(function(data) { @@ -281,11 +285,15 @@ app.service('cldsModelService', ['alertService', '$http', '$q', function(alertSe }; this.processRefresh = function(pars) { - typeID = pars.typeId; - deploymentId = pars.deploymentId; - setStatus(pars); - this.enableDisableMenuOptions(pars); - elementMap = JSON.parse(pars.propText); + var newPars = pars; + if (typeof pars.body !== 'undefined') { + newPars = pars.body; + } + typeID = newPars.typeId; + deploymentId = newPars.deploymentId; + setStatus(newPars); + this.enableDisableMenuOptions(newPars); + elementMap = JSON.parse(newPars.propText); } function setStatus(pars) { @@ -389,8 +397,8 @@ app.service('cldsModelService', ['alertService', '$http', '$q', function(alertSe this.getASDCServices().then(function(pars) { - - var services = pars.service; + var obj = JSON.parse(pars); + var services = obj.service; asdc_Services = services }); diff --git a/src/main/resources/META-INF/resources/designer/scripts/aOnBoot.js b/src/main/resources/META-INF/resources/designer/scripts/aOnBoot.js index ededa7c97..b69cfea08 100644 --- a/src/main/resources/META-INF/resources/designer/scripts/aOnBoot.js +++ b/src/main/resources/META-INF/resources/designer/scripts/aOnBoot.js @@ -158,7 +158,7 @@ function loadSharedPropertyByService(onChangeUUID, refresh, callBack) { dataType: "json", url: serviceUrl, success: function(data) { - vf_Services = data; + vf_Services = JSON.parse(data); setASDCFields() if (refresh) { $("#paramsWarnrefresh").hide(); @@ -200,7 +200,7 @@ function loadSharedPropertyByServiceProperties(callBack) { dataType: "json", url: '/restservices/clds/v1/clds/properties/', success: function(data) { - vf_Services = data; + vf_Services = JSON.parse(data); setASDCFields(); if (callBack && _.isFunction(callBack)) { callBack(true); @@ -316,8 +316,7 @@ $(window).on('load',function() { dataType: "json", url: '/restservices/clds/v1/clds/properties', success: function(data) { - - defaults_props = data; + defaults_props = JSON.parse(data); }, error: function(s, a, err) { console.log(err) diff --git a/src/main/resources/META-INF/resources/designer/scripts/authcontroller.js b/src/main/resources/META-INF/resources/designer/scripts/authcontroller.js index ae217a6bd..d6387c863 100644 --- a/src/main/resources/META-INF/resources/designer/scripts/authcontroller.js +++ b/src/main/resources/META-INF/resources/designer/scripts/authcontroller.js @@ -57,4 +57,4 @@ function($scope, $rootScope, $window, $resource, $http, $location, $cookies) { $window.localStorage.setItem("invalidUser", true); }); }; -} ]); +} ]);
\ No newline at end of file diff --git a/src/main/resources/application-noaaf.properties b/src/main/resources/application-noaaf.properties index 8d0395b47..1fd347a07 100644 --- a/src/main/resources/application-noaaf.properties +++ b/src/main/resources/application-noaaf.properties @@ -51,19 +51,9 @@ info.build.version=@project.version@ ### server.ssl.key-store=file:/tmp/mykey.jks ### server.ssl.key-store-password=mypass ### server.ssl.key-password=mypass -server.port=8443 -server.ssl.client-auth=want -server.ssl.key-store=file:/opt/clamp/config/org.onap.clamp.p12 -server.ssl.key-store-password=China in the Spring -server.ssl.key-password=China in the Spring -server.ssl.key-store-type=PKCS12 -server.ssl.trust=/opt/clamp/config/truststoreONAPall.jks -server.ssl.trust-pass=changeit -server.ssl.trust-type=JKS -server.ssl.key-alias=clamp@clamp.onap.org -server.http-to-https-redirection.port=8080 - -server.contextPath=/ +server.port=8080 + +server.servlet.context-path=/ #Modified engine-rest applicationpath spring.profiles.active=clamp-default,clamp-default-user,clamp-sdc-controller @@ -86,7 +76,8 @@ camel.defaultthreadpool.maxqueuesize=1000 camel.defaultthreadpool.keepaliveTime=60 camel.defaultthreadpool.rejectpolicy=CallerRuns #camel.springboot.xmlRoutes = false -camel.springboot.xmlRoutes=classpath:/clds/camel/*.xml +camel.springboot.xmlRoutes=classpath:/clds/camel/routes/*.xml +camel.springboot.xmlRests=classpath:/clds/camel/rest/*.xml #camel.springboot.typeConversion = false #clds datasource connection details diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 9a9bd2827..996129fda 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,237 +1,238 @@ -###
-# ============LICENSE_START=======================================================
-# ONAP CLAMP
-# ================================================================================
-# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
-# reserved.
-# ================================================================================
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ============LICENSE_END============================================
-# ===================================================================
-#
-###
-
-info.build.artifact=@project.artifactId@
-info.build.name=@project.name@
-info.build.description=@project.description@
-info.build.version=@project.version@
-
-### Set the port for HTTP or HTTPS protocol (Controlled by Spring framework, only one at a time).
-### (See below for the parameter 'server.http.port' if you want to have both enabled)
-### To have only HTTP, keep the lines server.ssl.* commented
-### To have only HTTPS enabled, uncomment the server.ssl.* lines and specify a right keystore location
-### server.port=8080
-### Settings for HTTPS (this automatically enables the HTTPS on the port 'server.port')
-#server.ssl.key-store=file:/tmp/mykey.jks
-#server.ssl.key-store-password=pass
-#server.ssl.key-password=pass
-
-### In order to be user friendly when HTTPS is enabled,
-### you can add another HTTP port that will be automatically redirected to HTTPS
-### by enabling this parameter (server.http.port) and set it to another port (80 or 8080, 8090, etc ...)
-#server.http-to-https-redirection.port=8090
-
-### HTTP Example:
-###--------------
-### server.port=8080
-
-### HTTPS Example:
-### --------------
-### server.port=8443
-### server.ssl.key-store=file:/tmp/mykey.jks
-### server.ssl.key-store-password=mypass
-### server.ssl.key-password=mypass
-
-### HTTP (Redirected to HTTPS) and HTTPS Example:
-### --------------------------------------------
-server.port=8443
-server.ssl.client-auth=want
-server.ssl.key-store=file:/opt/clamp/config/org.onap.clamp.p12
-server.ssl.key-store-password=China in the Spring
-server.ssl.key-password=China in the Spring
-server.ssl.key-store-type=PKCS12
-server.ssl.trust=/opt/clamp/config/truststoreONAPall.jks
-server.ssl.trust-pass=changeit
-server.ssl.trust-type=JKS
-server.ssl.key-alias=clamp@clamp.onap.org
-server.http-to-https-redirection.port=8080
-
-server.contextPath=/
-#Modified engine-rest applicationpath
-spring.profiles.active=clamp-default,clamp-aaf-authentication,clamp-sdc-controller
-
-#The max number of active threads in this pool
-server.tomcat.max-threads=200
-#The minimum number of threads always kept alive
-server.tomcat.min-Spare-Threads=25
-#The number of milliseconds before an idle thread shutsdown, unless the number of active threads are less or equal to minSpareThreads
-server.tomcat.max-idle-time=60000
-
-#Servlet context parameters
-server.context_parameters.p-name=value #context parameter with p-name as key and value as value.
-
-camel.springboot.consumer-template-cache-size=1000
-camel.springboot.producer-template-cache-size=1000
-camel.springboot.jmx-enabled=false
-camel.defaultthreadpool.poolsize=10
-camel.defaultthreadpool.maxpoolsize=20
-camel.defaultthreadpool.maxqueuesize=1000
-camel.defaultthreadpool.keepaliveTime=60
-camel.defaultthreadpool.rejectpolicy=CallerRuns
-#camel.springboot.xmlRoutes = false
-camel.springboot.xmlRoutes=classpath:/clds/camel/*.xml
-#camel.springboot.typeConversion = false
-
-#clds datasource connection details
-spring.datasource.cldsdb.driverClassName=org.mariadb.jdbc.Driver
-spring.datasource.cldsdb.url=jdbc:mariadb:sequential://localhost:${docker.mariadb.port.host}/cldsdb4?autoReconnect=true&connectTimeout=10000&socketTimeout=10000&retriesAllDown=3
-spring.datasource.cldsdb.username=clds
-spring.datasource.cldsdb.password=4c90a0b48204383f4283448d23e0b885a47237b2a23588e7c4651604f51c1067
-spring.datasource.cldsdb.validationQuery=SELECT 1
-spring.datasource.cldsdb.validationQueryTimeout=20000
-spring.datasource.cldsdb.validationInterval=30000
-spring.datasource.cldsdb.testWhileIdle = true
-spring.datasource.cldsdb.minIdle = 0
-spring.datasource.cldsdb.initialSize=0
-# Automatically test whether a connection provided is good or not
-spring.datasource.cldsdb.testOnBorrow=true
-spring.datasource.cldsdb.ignoreExceptionOnPreLoad=true
-
-#Async Executor default Parameters
-async.core.pool.size=10
-async.max.pool.size=20
-async.queue.capacity=500
-
-clamp.config.log.path=/var/log/onap
-clamp.config.files.systemProperties=classpath:/system.properties
-clamp.config.files.cldsUsers=classpath:/clds/clds-users.json
-clamp.config.files.globalProperties=classpath:/clds/templates/globalProperties.json
-clamp.config.files.sdcController=classpath:/clds/sdc-controllers-config.json
-
-# Properties for Clamp
-# DCAE request build properties
-#
-clamp.config.dcae.template=classpath:/clds/templates/dcae-template.json
-clamp.config.dcae.decode.service_ids=classpath:/clds/templates/dcae-decode-service_ids.json
-clamp.config.dcae.deployment.template=classpath:/clds/templates/dcae-deployment-template.json
-#
-# SDC request blueprint properties
-#
-clamp.config.sdc.template=classpath:/clds/templates/sdc-template.json
-clamp.config.sdc.decode.service_ids=classpath:/clds/templates/sdc-decode-service_ids.json
-#
-#
-# Configuration Settings for Policy Engine Components
-clamp.config.policy.pdpUrl1=http://policy.api.simpledemo.onap.org:8081/pdp/ , testpdp, alpha123
-clamp.config.policy.pdpUrl2=http://policy.api.simpledemo.onap.org:8081/pdp/ , testpdp, alpha123
-clamp.config.policy.papUrl=http://policy.api.simpledemo.onap.org:8081/pap/ , testpap, alpha123
-clamp.config.policy.notificationType=websocket
-clamp.config.policy.notificationUebServers=localhost
-clamp.config.policy.notificationTopic=PDPD-CONFIGURATION
-clamp.config.policy.clientId=python
-# base64 encoding
-
-clamp.config.policy.clientKey=dGVzdA==
-#DEVL for development
-#TEST for Test environments
-#PROD for prod environments
-clamp.config.policy.policyEnvironment=TEST
-# General Policy request properties
-#
-clamp.config.policy.onap.name=DCAE
-clamp.config.policy.pdp.group=default
-clamp.config.policy.ms.type=MicroService
-clamp.config.policy.ms.policyNamePrefix=Config_MS_
-clamp.config.policy.op.policyNamePrefix=Config_BRMS_Param_
-clamp.config.policy.base.policyNamePrefix=Config_
-clamp.config.policy.op.type=BRMS_Param
-
-
-# TCA MicroService Policy request build properties
-#
-clamp.config.tca.policyid.prefix=DCAE.Config_
-clamp.config.tca.policy.template=classpath:/clds/templates/tca-policy-template.json
-clamp.config.tca.template=classpath:/clds/templates/tca-template.json
-clamp.config.tca.thresholds.template=classpath:/clds/templates/tca-thresholds-template.json
-
-#
-#
-# Operational Policy request build properties
-#
-clamp.config.op.policyDescription=from clds
-# default
-clamp.config.op.templateName=ClosedLoopControlName
-clamp.config.op.operationTopic=APPC-CL
-clamp.config.op.notificationTopic=POLICY-CL-MGT
-clamp.config.op.controller=amsterdam
-clamp.config.op.policy.appc=APPC
-#
-# Sdc service properties
-clamp.config.sdc.catalog.url=http://sdc.api.simpledemo.onap.org:8080/sdc/v1/catalog/
-clamp.config.sdc.hostUrl=http://sdc.api.simpledemo.onap.org:8080
-clamp.config.sdc.serviceUrl=http://sdc.api.simpledemo.onap.org:8080/sdc/v1/catalog/services
-clamp.config.sdc.serviceUsername=clamp
-clamp.config.sdc.servicePassword=b7acccda32b98c5bb7acccda32b98c5b05D511BD6D93626E90D18E9D24D9B78CD34C7EE8012F0A189A28763E82271E50A5D4EC10C7D93E06E0A2D27CAE66B981
-clamp.config.sdc.artifactLabel=blueprintclampcockpit
-clamp.config.sdc.sdcX-InstanceID=CLAMP
-clamp.config.sdc.artifactType=DCAE_INVENTORY_BLUEPRINT
-clamp.config.sdc.locationArtifactLabel=locationclampcockpit
-clamp.config.sdc.locationArtifactType=DCAE_INVENTORY_JSON
-clamp.config.sdc.InstanceID=X-ECOMP-InstanceID
-clamp.config.sdc.header.requestId = X-ECOMP-RequestID
-#
-clamp.config.sdc.csarFolder = /tmp/sdc-controllers
-clamp.config.sdc.blueprint.parser.mapping = classpath:/clds/blueprint-parser-mapping.json
-#
-clamp.config.ui.location.default=classpath:/clds/templates/ui-location-default.json
-clamp.config.ui.alarm.default=classpath:/clds/templates/ui-alarm-default.json
-#
-# if action.test.override is true, then any action will be marked as test=true (even if incoming action request had test=false); otherwise, test flag will be unchanged on the action request
-clamp.config.action.test.override=false
-# if action.insert.test.event is true, then insert event even if the action is set to test
-clamp.config.action.insert.test.event=false
-clamp.config.clds.service.cache.invalidate.after.seconds=120
-
-#DCAE Inventory Url Properties
-clamp.config.dcae.inventory.url=http://dcae.api.simpledemo.onap.org:8080
-clamp.config.dcae.intentory.retry.interval=10000
-clamp.config.dcae.intentory.retry.limit=3
-
-#DCAE Dispatcher Url Properties
-clamp.config.dcae.dispatcher.url=http://dcae.api.simpledemo.onap.org:8188
-clamp.config.dcae.dispatcher.retry.interval=10000
-clamp.config.dcae.dispatcher.retry.limit=10
-clamp.config.dcae.header.requestId = X-ECOMP-RequestID
-
-#Define user permission related parameters, the permission type can be changed but MUST be redefined in clds-users.properties in that case !
-clamp.config.security.permission.type.cl=org.onap.clamp.clds.cl
-clamp.config.security.permission.type.cl.manage=org.onap.clamp.clds.cl.manage
-clamp.config.security.permission.type.cl.event=org.onap.clds.cl.event
-clamp.config.security.permission.type.filter.vf=org.onap.clamp.clds.filter.vf
-clamp.config.security.permission.type.template=org.onap.clamp.clds.template
-#This one indicates the type of instances (dev|prod|perf...), this must be set accordingly in clds-users.properties
-clamp.config.security.permission.instance=dev
-
-#AAF related parameters
-clamp.config.cadi.keyFile=/opt/clamp/config/org.onap.clamp.keyfile
-clamp.config.cadi.cadiLoglevel=INFO
-clamp.config.cadi.cadiLatitude=37.78187
-clamp.config.cadi.cadiLongitude=-122.26147
-clamp.config.cadi.aafLocateUrl=https://aaf-onap-beijing-test.osaaf.org
-clamp.config.cadi.cadiKeystorePassword=enc:V_kq_EwDNb4itWp_lYfDGXIWJzemHGkhkZOxAQI9IHs
-clamp.config.cadi.cadiTruststorePassword=enc:Mj0YQqNCUKbKq2lPp1kTFQWeqLxaBXKNwd5F1yB1ukf
-#clamp.config.cadi.oauthTokenUrl=https://AAF_LOCATE_URL/AAF_NS.token:2.0/token
-#clamp.config.cadi.oauthIntrospectUrll=https://AAF_LOCATE_URL/AAF_NS.introspect:2.0/introspect
-clamp.config.cadi.aafEnv=DEV
-clamp.config.cadi.aafUrl=https://AAF_LOCATE_URL/AAF_NS.service:2.0
-clamp.config.cadi.cadiX509Issuers=CN=intermediateCA_1, OU=OSAAF, O=ONAP, C=US
+### +# ============LICENSE_START======================================================= +# ONAP CLAMP +# ================================================================================ +# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights +# reserved. +# ================================================================================ +# 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. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END============================================ +# =================================================================== +# +### + +info.build.artifact=@project.artifactId@ +info.build.name=@project.name@ +info.build.description=@project.description@ +info.build.version=@project.version@ + +### Set the port for HTTP or HTTPS protocol (Controlled by Spring framework, only one at a time). +### (See below for the parameter 'server.http.port' if you want to have both enabled) +### To have only HTTP, keep the lines server.ssl.* commented +### To have only HTTPS enabled, uncomment the server.ssl.* lines and specify a right keystore location +### server.port=8080 +### Settings for HTTPS (this automatically enables the HTTPS on the port 'server.port') +#server.ssl.key-store=file:/tmp/mykey.jks +#server.ssl.key-store-password=pass +#server.ssl.key-password=pass + +### In order to be user friendly when HTTPS is enabled, +### you can add another HTTP port that will be automatically redirected to HTTPS +### by enabling this parameter (server.http.port) and set it to another port (80 or 8080, 8090, etc ...) +#server.http-to-https-redirection.port=8090 + +### HTTP Example: +###-------------- +### server.port=8080 + +### HTTPS Example: +### -------------- +### server.port=8443 +### server.ssl.key-store=file:/tmp/mykey.jks +### server.ssl.key-store-password=mypass +### server.ssl.key-password=mypass + +### HTTP (Redirected to HTTPS) and HTTPS Example: +### -------------------------------------------- +server.port=8443 +server.ssl.client-auth=want +server.ssl.key-store=file:/opt/clamp/config/org.onap.clamp.p12 +server.ssl.key-store-password=China in the Spring +server.ssl.key-password=China in the Spring +server.ssl.key-store-type=PKCS12 +server.ssl.trust=/opt/clamp/config/truststoreONAPall.jks +server.ssl.trust-pass=changeit +server.ssl.trust-type=JKS +server.ssl.key-alias=clamp@clamp.onap.org +server.http-to-https-redirection.port=8080 + +server.servlet.context-path=/ +#Modified engine-rest applicationpath +spring.profiles.active=clamp-default,clamp-aaf-authentication,clamp-sdc-controller + +#The max number of active threads in this pool +server.tomcat.max-threads=200 +#The minimum number of threads always kept alive +server.tomcat.min-Spare-Threads=25 +#The number of milliseconds before an idle thread shutsdown, unless the number of active threads are less or equal to minSpareThreads +server.tomcat.max-idle-time=60000 + +#Servlet context parameters +server.context_parameters.p-name=value #context parameter with p-name as key and value as value. + +camel.springboot.consumer-template-cache-size=1000 +camel.springboot.producer-template-cache-size=1000 +camel.springboot.jmx-enabled=false +camel.defaultthreadpool.poolsize=10 +camel.defaultthreadpool.maxpoolsize=20 +camel.defaultthreadpool.maxqueuesize=1000 +camel.defaultthreadpool.keepaliveTime=60 +camel.defaultthreadpool.rejectpolicy=CallerRuns +#camel.springboot.xmlRoutes = false +camel.springboot.xmlRoutes=classpath:/clds/camel/routes/*.xml +camel.springboot.xmlRests=classpath:/clds/camel/rest/*.xml +#camel.springboot.typeConversion = false + +#clds datasource connection details +spring.datasource.cldsdb.driverClassName=org.mariadb.jdbc.Driver +spring.datasource.cldsdb.url=jdbc:mariadb:sequential://localhost:${docker.mariadb.port.host}/cldsdb4?autoReconnect=true&connectTimeout=10000&socketTimeout=10000&retriesAllDown=3 +spring.datasource.cldsdb.username=clds +spring.datasource.cldsdb.password=4c90a0b48204383f4283448d23e0b885a47237b2a23588e7c4651604f51c1067 +spring.datasource.cldsdb.validationQuery=SELECT 1 +spring.datasource.cldsdb.validationQueryTimeout=20000 +spring.datasource.cldsdb.validationInterval=30000 +spring.datasource.cldsdb.testWhileIdle = true +spring.datasource.cldsdb.minIdle = 0 +spring.datasource.cldsdb.initialSize=0 +# Automatically test whether a connection provided is good or not +spring.datasource.cldsdb.testOnBorrow=true +spring.datasource.cldsdb.ignoreExceptionOnPreLoad=true + +#Async Executor default Parameters +async.core.pool.size=10 +async.max.pool.size=20 +async.queue.capacity=500 + +clamp.config.log.path=/var/log/onap +clamp.config.files.systemProperties=classpath:/system.properties +clamp.config.files.cldsUsers=classpath:/clds/clds-users.json +clamp.config.files.globalProperties=classpath:/clds/templates/globalProperties.json +clamp.config.files.sdcController=classpath:/clds/sdc-controllers-config.json + +# Properties for Clamp +# DCAE request build properties +# +clamp.config.dcae.template=classpath:/clds/templates/dcae-template.json +clamp.config.dcae.decode.service_ids=classpath:/clds/templates/dcae-decode-service_ids.json +clamp.config.dcae.deployment.template=classpath:/clds/templates/dcae-deployment-template.json +# +# SDC request blueprint properties +# +clamp.config.sdc.template=classpath:/clds/templates/sdc-template.json +clamp.config.sdc.decode.service_ids=classpath:/clds/templates/sdc-decode-service_ids.json +# +# +# Configuration Settings for Policy Engine Components +clamp.config.policy.pdpUrl1=http://policy.api.simpledemo.onap.org:8081/pdp/ , testpdp, alpha123 +clamp.config.policy.pdpUrl2=http://policy.api.simpledemo.onap.org:8081/pdp/ , testpdp, alpha123 +clamp.config.policy.papUrl=http://policy.api.simpledemo.onap.org:8081/pap/ , testpap, alpha123 +clamp.config.policy.notificationType=websocket +clamp.config.policy.notificationUebServers=localhost +clamp.config.policy.notificationTopic=PDPD-CONFIGURATION +clamp.config.policy.clientId=python +# base64 encoding + +clamp.config.policy.clientKey=dGVzdA== +#DEVL for development +#TEST for Test environments +#PROD for prod environments +clamp.config.policy.policyEnvironment=TEST +# General Policy request properties +# +clamp.config.policy.onap.name=DCAE +clamp.config.policy.pdp.group=default +clamp.config.policy.ms.type=MicroService +clamp.config.policy.ms.policyNamePrefix=Config_MS_ +clamp.config.policy.op.policyNamePrefix=Config_BRMS_Param_ +clamp.config.policy.base.policyNamePrefix=Config_ +clamp.config.policy.op.type=BRMS_Param + + +# TCA MicroService Policy request build properties +# +clamp.config.tca.policyid.prefix=DCAE.Config_ +clamp.config.tca.policy.template=classpath:/clds/templates/tca-policy-template.json +clamp.config.tca.template=classpath:/clds/templates/tca-template.json +clamp.config.tca.thresholds.template=classpath:/clds/templates/tca-thresholds-template.json + +# +# +# Operational Policy request build properties +# +clamp.config.op.policyDescription=from clds +# default +clamp.config.op.templateName=ClosedLoopControlName +clamp.config.op.operationTopic=APPC-CL +clamp.config.op.notificationTopic=POLICY-CL-MGT +clamp.config.op.controller=amsterdam +clamp.config.op.policy.appc=APPC +# +# Sdc service properties +clamp.config.sdc.catalog.url=http://sdc.api.simpledemo.onap.org:8080/sdc/v1/catalog/ +clamp.config.sdc.hostUrl=http://sdc.api.simpledemo.onap.org:8080 +clamp.config.sdc.serviceUrl=http://sdc.api.simpledemo.onap.org:8080/sdc/v1/catalog/services +clamp.config.sdc.serviceUsername=clamp +clamp.config.sdc.servicePassword=b7acccda32b98c5bb7acccda32b98c5b05D511BD6D93626E90D18E9D24D9B78CD34C7EE8012F0A189A28763E82271E50A5D4EC10C7D93E06E0A2D27CAE66B981 +clamp.config.sdc.artifactLabel=blueprintclampcockpit +clamp.config.sdc.sdcX-InstanceID=CLAMP +clamp.config.sdc.artifactType=DCAE_INVENTORY_BLUEPRINT +clamp.config.sdc.locationArtifactLabel=locationclampcockpit +clamp.config.sdc.locationArtifactType=DCAE_INVENTORY_JSON +clamp.config.sdc.InstanceID=X-ECOMP-InstanceID +clamp.config.sdc.header.requestId = X-ECOMP-RequestID +# +clamp.config.sdc.csarFolder = /tmp/sdc-controllers +clamp.config.sdc.blueprint.parser.mapping = classpath:/clds/blueprint-parser-mapping.json +# +clamp.config.ui.location.default=classpath:/clds/templates/ui-location-default.json +clamp.config.ui.alarm.default=classpath:/clds/templates/ui-alarm-default.json +# +# if action.test.override is true, then any action will be marked as test=true (even if incoming action request had test=false); otherwise, test flag will be unchanged on the action request +clamp.config.action.test.override=false +# if action.insert.test.event is true, then insert event even if the action is set to test +clamp.config.action.insert.test.event=false +clamp.config.clds.service.cache.invalidate.after.seconds=120 + +#DCAE Inventory Url Properties +clamp.config.dcae.inventory.url=http://dcae.api.simpledemo.onap.org:8080 +clamp.config.dcae.intentory.retry.interval=10000 +clamp.config.dcae.intentory.retry.limit=3 + +#DCAE Dispatcher Url Properties +clamp.config.dcae.dispatcher.url=http://dcae.api.simpledemo.onap.org:8188 +clamp.config.dcae.dispatcher.retry.interval=10000 +clamp.config.dcae.dispatcher.retry.limit=10 +clamp.config.dcae.header.requestId = X-ECOMP-RequestID + +#Define user permission related parameters, the permission type can be changed but MUST be redefined in clds-users.properties in that case ! +clamp.config.security.permission.type.cl=org.onap.clamp.clds.cl +clamp.config.security.permission.type.cl.manage=org.onap.clamp.clds.cl.manage +clamp.config.security.permission.type.cl.event=org.onap.clds.cl.event +clamp.config.security.permission.type.filter.vf=org.onap.clamp.clds.filter.vf +clamp.config.security.permission.type.template=org.onap.clamp.clds.template +#This one indicates the type of instances (dev|prod|perf...), this must be set accordingly in clds-users.properties +clamp.config.security.permission.instance=dev + +#AAF related parameters +clamp.config.cadi.keyFile=/opt/clamp/config/org.onap.clamp.keyfile +clamp.config.cadi.cadiLoglevel=DEBUG +clamp.config.cadi.cadiLatitude=37.78187 +clamp.config.cadi.cadiLongitude=-122.26147 +clamp.config.cadi.aafLocateUrl=https://aaf-onap-beijing-test.osaaf.org +clamp.config.cadi.cadiKeystorePassword=enc:V_kq_EwDNb4itWp_lYfDGXIWJzemHGkhkZOxAQI9IHs +clamp.config.cadi.cadiTruststorePassword=enc:Mj0YQqNCUKbKq2lPp1kTFQWeqLxaBXKNwd5F1yB1ukf +#clamp.config.cadi.oauthTokenUrl=https://AAF_LOCATE_URL/AAF_NS.token:2.0/token +#clamp.config.cadi.oauthIntrospectUrll=https://AAF_LOCATE_URL/AAF_NS.introspect:2.0/introspect +clamp.config.cadi.aafEnv=DEV +clamp.config.cadi.aafUrl=https://AAF_LOCATE_URL/AAF_NS.service:2.0 +clamp.config.cadi.cadiX509Issuers=CN=intermediateCA_1, OU=OSAAF, O=ONAP, C=US diff --git a/src/main/resources/clds/camel/rest/clds-services.xml b/src/main/resources/clds/camel/rest/clds-services.xml new file mode 100644 index 000000000..1ea8213f5 --- /dev/null +++ b/src/main/resources/clds/camel/rest/clds-services.xml @@ -0,0 +1,95 @@ +<rests xmlns="http://camel.apache.org/schema/spring"> + <rest> + <get uri="/clds/cldsDetails" outType="org.onap.clamp.clds.model.CldsMonitoringDetails" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=getCLDSDetails()" /> + </get> + <get uri="/clds/cldsInfo" outType="org.onap.clamp.clds.model.CldsInfo" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=getCldsInfo()" /> + </get> + <get uri="/healthcheck" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsHealthcheckService?method=gethealthcheck()" /> + </get> + <get uri="/clds/model/bpmn/{modelName}" produces="text/xml"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=getBpmnXml(${header.modelName})" /> + </get> + <get uri="/clds/model/image/{modelName}" produces="text/xml"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=getImageXml(${header.modelName})" /> + </get> + <get uri="/clds/model/{modelName}" outType="org.onap.clamp.clds.model.CldsModel" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=getModel(${header.modelName})" /> + </get> + <put uri="/clds/model/{modelName}" type="org.onap.clamp.clds.model.CldsModel" consumes="application/json" outType="org.onap.clamp.clds.model.CldsModel" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=putModel(${header.modelName},${body})" /> + </put> + <get uri="/clds/model-names" outType="org.onap.clamp.clds.model.ValueItem" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=getModelNames()" /> + </get> + <put uri="/clds/action/{action}/{modelName}?test={test}" type="org.onap.clamp.clds.model.CldsModel" consumes="application/json" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=putModelAndProcessAction(${header.action},${header.modelName},${header.test},${body})" /> + </put> + <post uri="/clds/dcae/event?test={test}" type="org.onap.clamp.clds.model.DcaeEvent" consumes="application/json" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=postDcaeEvent(${header.test},${body})" /> + </post> + <get uri="/clds/sdc/services" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=getSdcServices()" /> + </get> + <get uri="/clds/properties" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=getSdcProperties()" /> + </get> + <get uri="/clds/properties/{serviceInvariantUUID}?refresh={refresh}" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=getSdcPropertiesByServiceUUIDForRefresh(${header.serviceInvariantUUID},${header.refresh})" /> + </get> + <put uri="/clds/deploy/{modelName}" type="org.onap.clamp.clds.model.CldsModel" consumes="application/json" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=deployModel(${header.modelName},${body})" /> + </put> + <put uri="/clds/undeploy/{modelName}" type="org.onap.clamp.clds.model.CldsModel" consumes="application/json" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsService?method=unDeployModel(${header.modelName},${body})" /> + </put> + + + + + <get uri="/cldsTempate/template/bpmn/{templateName}" produces="text/xml"> + <to + uri="bean:org.onap.clamp.clds.service.CldsTemplateService?method=getBpmnTemplate(${header.templateName})" /> + </get> + <get uri="/cldsTempate/template/image/{templateName}" produces="text/xml"> + <to + uri="bean:org.onap.clamp.clds.service.CldsTemplateService?method=getImageXml(${header.templateName})" /> + </get> + <get uri="/cldsTempate/template/{templateName}" outType="org.onap.clamp.clds.model.CldsTemplate" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsTemplateService?method=getTemplate(${header.templateName})" /> + </get> + <put uri="/cldsTempate/template/{templateName}" type="org.onap.clamp.clds.model.CldsTemplate" consumes="application/json" outType="org.onap.clamp.clds.model.CldsTemplate" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsTemplateService?method=putTemplate(${header.templateName},${body})" /> + </put> + <get uri="/cldsTempate/template-names" outType="org.onap.clamp.clds.model.ValueItem" produces="application/json"> + <to + uri="bean:org.onap.clamp.clds.service.CldsTemplateService?method=getTemplateNames()" /> + </get> + + + + <get uri="/user/getUser" produces="text/plain"> + <to + uri="bean:org.onap.clamp.clds.service.UserService?method=getUser()" /> + </get> + </rest> +</rests> diff --git a/src/main/resources/clds/camel/flexible-flow.xml b/src/main/resources/clds/camel/routes/flexible-flow.xml index 8305c2e49..8305c2e49 100644 --- a/src/main/resources/clds/camel/flexible-flow.xml +++ b/src/main/resources/clds/camel/routes/flexible-flow.xml diff --git a/src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java index 40e876880..5d8910352 100644 --- a/src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java @@ -34,6 +34,7 @@ import org.onap.clamp.clds.service.CldsHealthcheckService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** @@ -48,8 +49,8 @@ public class CldsHealthcheckServiceItCase { @Test public void testGetHealthCheck() { - Response response = cldsHealthcheckService.gethealthcheck(); - CldsHealthCheck cldsHealthCheck = (CldsHealthCheck) response.getEntity(); + ResponseEntity response = cldsHealthcheckService.gethealthcheck(); + CldsHealthCheck cldsHealthCheck = (CldsHealthCheck) response.getBody(); assertNotNull(cldsHealthCheck); assertEquals("UP", cldsHealthCheck.getHealthCheckStatus()); assertEquals("CLDS-APP", cldsHealthCheck.getHealthCheckComponent()); diff --git a/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java index 1450af902..f61a33e3e 100644 --- a/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java @@ -35,11 +35,10 @@ import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.Principal; +import java.util.LinkedList; +import java.util.List; import java.util.Properties; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - import org.apache.commons.codec.DecoderException; import org.json.JSONException; import org.junit.Before; @@ -58,6 +57,14 @@ import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** @@ -74,6 +81,8 @@ public class CldsServiceItCase { private String bpmnPropText; @Autowired private CldsDao cldsDao; + private Authentication authentication; + private List<GrantedAuthority> authList = new LinkedList<GrantedAuthority>(); /** * Setup the variable before the tests execution. @@ -86,14 +95,24 @@ public class CldsServiceItCase { bpmnText = ResourceFileUtil.getResourceAsString("example/dao/bpmn-template.xml"); imageText = ResourceFileUtil.getResourceAsString("example/dao/image-template.xml"); bpmnPropText = ResourceFileUtil.getResourceAsString("example/dao/bpmn-prop.json"); + + authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|read")); + authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|update")); + authList.add(new SimpleGrantedAuthority("permission-type-template|dev|read")); + authList.add(new SimpleGrantedAuthority("permission-type-template|dev|update")); + authList.add(new SimpleGrantedAuthority("permission-type-filter-vf|dev|*")); + authentication = new UsernamePasswordAuthenticationToken(new User("admin", "", authList), "", authList); } @Test public void testCldsInfoNotAuthorized() { SecurityContext securityContext = Mockito.mock(SecurityContext.class); - Principal principal = Mockito.mock(Principal.class); - Mockito.when(principal.getName()).thenReturn("admin"); - Mockito.when(securityContext.getUserPrincipal()).thenReturn(principal); + Authentication localAuth = Mockito.mock(Authentication.class); + UserDetails userDetails = Mockito.mock(UserDetails.class); + Mockito.when(userDetails.getUsername()).thenReturn("admin"); + Mockito.when(securityContext.getAuthentication()).thenReturn(localAuth); + Mockito.when(localAuth.getPrincipal()).thenReturn(userDetails); + cldsService.setSecurityContext(securityContext); CldsInfo cldsInfo = cldsService.getCldsInfo(); assertFalse(cldsInfo.isPermissionReadCl()); @@ -105,13 +124,8 @@ public class CldsServiceItCase { @Test public void testCldsInfoAuthorized() throws Exception { SecurityContext securityContext = Mockito.mock(SecurityContext.class); - Principal principal = Mockito.mock(Principal.class); - Mockito.when(principal.getName()).thenReturn("admin"); - Mockito.when(securityContext.getUserPrincipal()).thenReturn(principal); - Mockito.when(securityContext.isUserInRole("permission-type-cl|dev|read")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-cl|dev|update")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-template|dev|read")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-template|dev|update")).thenReturn(true); + Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); + cldsService.setSecurityContext(securityContext); CldsInfo cldsInfo = cldsService.getCldsInfo(); assertTrue(cldsInfo.isPermissionReadCl()); @@ -127,25 +141,9 @@ public class CldsServiceItCase { } @Test - public void testGetHealthCheck() { - Response response = cldsService.gethealthcheck(); - CldsHealthCheck cldsHealthCheck = (CldsHealthCheck) response.getEntity(); - assertNotNull(cldsHealthCheck); - assertEquals("UP", cldsHealthCheck.getHealthCheckStatus()); - assertEquals("CLDS-APP", cldsHealthCheck.getHealthCheckComponent()); - assertEquals("OK", cldsHealthCheck.getDescription()); - } - - @Test public void testPutModel() { SecurityContext securityContext = Mockito.mock(SecurityContext.class); - Principal principal = Mockito.mock(Principal.class); - Mockito.when(principal.getName()).thenReturn("admin"); - Mockito.when(securityContext.getUserPrincipal()).thenReturn(principal); - Mockito.when(securityContext.isUserInRole("permission-type-cl|dev|read")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-cl|dev|update")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-template|dev|read")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-template|dev|update")).thenReturn(true); + Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); cldsService.setSecurityContext(securityContext); // Add the template first CldsTemplate newTemplate = new CldsTemplate(); @@ -188,14 +186,8 @@ public class CldsServiceItCase { public void testGetSdcPropertiesByServiceUuidForRefresh() throws GeneralSecurityException, DecoderException, JSONException, IOException { SecurityContext securityContext = Mockito.mock(SecurityContext.class); - Principal principal = Mockito.mock(Principal.class); - Mockito.when(principal.getName()).thenReturn("admin"); - Mockito.when(securityContext.getUserPrincipal()).thenReturn(principal); - Mockito.when(securityContext.isUserInRole("permission-type-cl|dev|read")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-cl|dev|update")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-template|dev|read")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-template|dev|update")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-filter-vf|dev|*")).thenReturn(true); + Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); + cldsService.setSecurityContext(securityContext); // Test basic functionalities String result = cldsService.getSdcPropertiesByServiceUUIDForRefresh("4cc5b45a-1f63-4194-8100-cd8e14248c92", diff --git a/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java index 040c999fa..913e49a45 100644 --- a/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java @@ -32,10 +32,9 @@ import com.att.eelf.configuration.EELFManager; import java.io.IOException; import java.security.Principal; +import java.util.LinkedList; import java.util.List; -import javax.ws.rs.core.SecurityContext; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -48,6 +47,13 @@ import org.onap.clamp.clds.util.ResourceFileUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.User; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** @@ -66,6 +72,8 @@ public class CldsTemplateServiceItCase { private String imageText; private String bpmnPropText; private CldsTemplate cldsTemplate; + private Authentication authentication; + private List<GrantedAuthority> authList = new LinkedList<GrantedAuthority>(); /** * Setup the variable before the tests execution. @@ -75,14 +83,17 @@ public class CldsTemplateServiceItCase { */ @Before public void setupBefore() throws IOException { + authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|read")); + authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|update")); + authList.add(new SimpleGrantedAuthority("permission-type-template|dev|read")); + authList.add(new SimpleGrantedAuthority("permission-type-template|dev|update")); + authList.add(new SimpleGrantedAuthority("permission-type-filter-vf|dev|*")); + authentication = new UsernamePasswordAuthenticationToken(new User("admin", "", authList), "", authList); + SecurityContext securityContext = Mockito.mock(SecurityContext.class); - Principal principal = Mockito.mock(Principal.class); - Mockito.when(principal.getName()).thenReturn("admin"); - Mockito.when(securityContext.getUserPrincipal()).thenReturn(principal); - Mockito.when(securityContext.isUserInRole("permission-type-cl|dev|read")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-cl|dev|update")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-template|dev|read")).thenReturn(true); - Mockito.when(securityContext.isUserInRole("permission-type-template|dev|update")).thenReturn(true); + Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); + + cldsTemplateService.setSecurityContext(securityContext); bpmnText = ResourceFileUtil.getResourceAsString("example/dao/bpmn-template.xml"); imageText = ResourceFileUtil.getResourceAsString("example/dao/image-template.xml"); diff --git a/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java b/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java index b6f3ef423..69dad53ec 100644 --- a/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java @@ -82,6 +82,7 @@ public class OperationPolicyReqItCase { } private String replaceGeneratedValues(String yaml) { + yaml = yaml.replaceAll("Policy - created" + System.lineSeparator() + " by CLDS", "Policy - created by CLDS"); yaml = yaml.replaceAll("trigger_policy: (.*)", "trigger_policy: <generatedId>"); yaml = yaml.replaceAll("id: (.*)", "id: <generatedId>"); yaml = yaml.replaceAll("success: (.*)", "success: <generatedId>"); diff --git a/src/test/java/org/onap/clamp/clds/swagger/SwaggerConfig.java b/src/test/java/org/onap/clamp/clds/swagger/SwaggerConfig.java deleted file mode 100644 index 96784dd64..000000000 --- a/src/test/java/org/onap/clamp/clds/swagger/SwaggerConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - */ - -package org.onap.clamp.clds.swagger; - -import org.springframework.context.annotation.Configuration; - -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@EnableSwagger2 -@Configuration -public class SwaggerConfig { - - private ApiInfo apiInfo() { - return new ApiInfoBuilder().title("Clamp").description("Clamp API Description").license("Apache 2.0") - .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0").build(); - } -} diff --git a/src/test/java/org/onap/clamp/clds/swagger/SwaggerGenerationTest.java b/src/test/java/org/onap/clamp/clds/swagger/SwaggerGenerationTest.java deleted file mode 100644 index 363d12d40..000000000 --- a/src/test/java/org/onap/clamp/clds/swagger/SwaggerGenerationTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - */ - -package org.onap.clamp.clds.swagger; - -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.clamp.clds.Application; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import io.github.swagger2markup.Swagger2MarkupConverter; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = { - Application.class, SwaggerConfig.class -}) -public class SwaggerGenerationTest { - - @Test - public void convertRemoteSwaggerToAsciiDoc() { - Path localSwaggerFile = Paths.get("docs/swagger/swagger.json"); - Swagger2MarkupConverter.from(localSwaggerFile).build(); - } -} |