diff options
author | Shankaranarayanan Puzhavakath Narayanan <snarayanan@research.att.com> | 2019-03-28 19:01:20 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2019-03-28 19:01:20 +0000 |
commit | d4d9d4e0b94dbee932fcc52b15832adee98bfea3 (patch) | |
tree | 12656410b5dbb754f6e21b5e36226920cad5b02d /cmso-optimizer/src/main/java | |
parent | e536a251cf98e6c0f1fb32e240be437c7818856e (diff) | |
parent | f39eb6d1bdc582623b0944a610725b8e7082e972 (diff) |
Merge "Commit 4 for Define OPtimizer API mS"
Diffstat (limited to 'cmso-optimizer/src/main/java')
11 files changed, 964 insertions, 0 deletions
diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/common/PropertiesManagement.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/common/PropertiesManagement.java new file mode 100644 index 0000000..79a0a79 --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/common/PropertiesManagement.java @@ -0,0 +1,135 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. Modifications Copyright © 2018 IBM. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed under the Creative + * Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except + * in compliance with the License. You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.optf.cmso.common; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import org.apache.commons.codec.binary.Base64; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +/** + * The Class PropertiesManagement. + */ +@Component +public class PropertiesManagement { + + private static EELFLogger debug = EELFManager.getInstance().getDebugLogger(); + private static EELFLogger errors = EELFManager.getInstance().getErrorLogger(); + + private static final String algorithm = "AES"; + + private static final String cipherMode = "CBC"; + + private static final String paddingScheme = "PKCS5Padding"; + + private static final String transformation = algorithm + "/" + cipherMode + "/" + paddingScheme; + + private static final String initVector = "ONAPCMSOVECTORIV"; // 16 bytes IV + + @Autowired + Environment env; + + /** + * Gets the property. + * + * @param key the key + * @param defaultValue the default value + * @return the property + */ + public String getProperty(String key, String defaultValue) { + String value = env.getProperty(key, defaultValue); + value = getDecryptedValue(value); + return value; + } + + /** + * Gets the decrypted value. + * + * @param value the value + * @return the decrypted value + */ + public static String getDecryptedValue(String value) { + if (value.startsWith("enc:")) { + String secret = getSecret(); + value = decrypt(secret, initVector, value.substring(4)); + } + return value; + } + + /** + * Gets the encrypted value. + * + * @param value the value + * @return the encrypted value + */ + public static String getEncryptedValue(String value) { + String secret = getSecret(); + value = encrypt(secret, initVector, value); + return value; + } + + private static final String encrypt(String key, String initVector, String value) { + try { + IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); + SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); + Cipher cipher = Cipher.getInstance(transformation); + cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); + byte[] encrypted = cipher.doFinal(value.getBytes()); + return Base64.encodeBase64String(encrypted); + } catch (Exception ex) { + errors.error("Unexpected exception {0}", ex.getMessage()); + debug.debug("Unexpected exception", ex); + } + + return null; + } + + private static final String decrypt(String key, String initVector, String encrypted) { + try { + IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); + SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); + Cipher cipher = Cipher.getInstance(transformation); + cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); + byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted)); + return new String(original); + } catch (Exception ex) { + errors.error("Unexpected exception {0}", ex.getMessage()); + debug.debug("Unexpected exception", ex); + } + return null; + } + + private static String getSecret() { + return "ONAPCMSOSECRETIV"; + } + +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/common/exceptions/CmsoException.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/common/exceptions/CmsoException.java new file mode 100644 index 0000000..a83437f --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/common/exceptions/CmsoException.java @@ -0,0 +1,99 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. Modifications Copyright © 2018 IBM. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed under the Creative + * Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except + * in compliance with the License. You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.optf.cmso.common.exceptions; + +import com.att.eelf.i18n.EELFResourceManager; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.Response.Status; +import org.onap.observations.ObservationInterface; +import org.onap.optf.cmso.common.CmsoRequestError; + +/** + * The Class CMSException. + */ +public class CmsoException extends Exception { + private static final long serialVersionUID = 1L; + + protected CmsoRequestError requestError = null; + private List<String> variables = new ArrayList<String>(); + protected ObservationInterface messageCode; + protected Status status; + + /** + * Instantiates a new CMS exception. + * + * @param status the status + * @param messageCode the message code + * @param args the args + */ + public CmsoException(Status status, ObservationInterface messageCode, String... args) { + super(EELFResourceManager.format(messageCode, args)); + this.status = status; + this.messageCode = messageCode; + for (String arg : args) { + variables.add(arg); + } + requestError = new CmsoRequestError(messageCode.name(), getMessage(), variables); + } + + /** + * Gets the status. + * + * @return the status + */ + public Status getStatus() { + return status; + } + + /** + * Gets the message code. + * + * @return the message code + */ + public ObservationInterface getMessageCode() { + return messageCode; + } + + /** + * Gets the variables. + * + * @return the variables + */ + public String[] getVariables() { + return variables.toArray(new String[variables.size()]); + } + + /** + * Gets the request error. + * + * @return the request error + */ + public CmsoRequestError getRequestError() { + return requestError; + } +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/Application.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/Application.java new file mode 100644 index 0000000..e4bcc1d --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/Application.java @@ -0,0 +1,94 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. Modifications Copyright © 2018 IBM. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed under the Creative + * Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except + * in compliance with the License. You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.optf.cmso.optimizer; + +import com.att.eelf.configuration.Configuration; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import java.net.InetAddress; +import java.util.TimeZone; +import javax.annotation.PostConstruct; +import org.onap.optf.cmso.optimizer.common.LogMessages; +import org.slf4j.MDC; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; +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; + +@SpringBootApplication +@ComponentScan(basePackages = {"org.onap.optf.cmso"}) +@EnableAsync + +@EnableAutoConfiguration(exclude = {/* DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class */} ) +public class Application extends SpringBootServletInitializer { + + private static EELFLogger log = EELFManager.getInstance().getLogger(Application.class); + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + @PostConstruct + void started() { + // Make sure all datetimes are stored in UTC format. + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + } + + public static void main(String[] args) { + initMdcData(); + SpringApplication.run(Application.class, args); + } + + protected static void initMdcData() { + MDC.clear(); + try { + MDC.put(Configuration.MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); + MDC.put("hostname", InetAddress.getLocalHost().getCanonicalHostName()); + MDC.put("serviceName", System.getProperty("info.build.artifact")); + MDC.put("version", System.getProperty("info.build.version")); + MDC.put(Configuration.MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + } catch (Exception e) { + log.error(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + } + } + + @Bean + public ServletWebServerFactory servletContainer() { + TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); + return tomcat; + } + + + +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/ApplicationPropertiesFiles.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/ApplicationPropertiesFiles.java new file mode 100644 index 0000000..283c19e --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/ApplicationPropertiesFiles.java @@ -0,0 +1,37 @@ +/* + * Copyright © 2018 AT&T Intellectual Property. Modifications Copyright © 2018 IBM. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed under the Creative + * Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except + * in compliance with the License. You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.optf.cmso.optimizer; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.PropertySources; + + +@Configuration +@PropertySources({@PropertySource("file:etc/config/optimizer.properties"),}) +public class ApplicationPropertiesFiles { +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/AuthProvider.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/AuthProvider.java new file mode 100644 index 0000000..ba763fa --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/AuthProvider.java @@ -0,0 +1,58 @@ +/* + * Copyright © 2018 AT&T Intellectual Property. Modifications Copyright © 2019 IBM. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed under the Creative + * Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except + * in compliance with the License. You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.optf.cmso.optimizer; + +import java.util.ArrayList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; + +@Component +@Profile(SpringProfiles.PROPRIETARY__AUTHENTICATION) + +public class AuthProvider implements AuthenticationProvider { + + @Autowired + Environment env; + + @Override + public Authentication authenticate(Authentication authentication) { + String name = authentication.getName(); + String password = authentication.getCredentials().toString(); + // TODO check credentials until we enable AAF + return new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>()); + } + + @Override + public boolean supports(Class<?> authentication) { + return authentication.equals(UsernamePasswordAuthenticationToken.class); + } +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/CmsoEnvironmentPostProcessor.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/CmsoEnvironmentPostProcessor.java new file mode 100644 index 0000000..5e425d0 --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/CmsoEnvironmentPostProcessor.java @@ -0,0 +1,56 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. Modifications Copyright © 2018 IBM. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed under the Creative + * Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except + * in compliance with the License. You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.optf.cmso.optimizer; + +import java.util.HashMap; +import java.util.Map; +import org.onap.optf.cmso.common.PropertiesManagement; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.MutablePropertySources; + +public class CmsoEnvironmentPostProcessor implements EnvironmentPostProcessor { + // TODO tested in ONAP springboot and this is called before all of the properties files have been + // loaded... + // perhaps there is a post post processor? Until this works. DB password will be in the clear in the + // proeprties files. + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + String pwd = environment.getProperty("cmso.database.password"); + if (pwd != null) { + pwd = PropertiesManagement.getDecryptedValue(pwd); + Map<String, Object> map = new HashMap<String, Object>(); + map.put("spring.datasource.password", pwd); + MapPropertySource propertySource = new MapPropertySource("abc", map); + MutablePropertySources proeprtySources = environment.getPropertySources(); + proeprtySources.addLast(propertySource); + } + } + +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/JerseyConfiguration.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/JerseyConfiguration.java new file mode 100644 index 0000000..fb8191b --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/JerseyConfiguration.java @@ -0,0 +1,106 @@ +/* + * Copyright © 2017-2019 AT&T Intellectual Property. Modifications Copyright © 2018 IBM. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed under the Creative + * Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except + * in compliance with the License. You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.optf.cmso.optimizer; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import java.util.logging.Logger; +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.logging.LoggingFeature; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.servlet.ServletProperties; +import org.onap.optf.cmso.optimizer.filters.CmsoContainerFilters; +import org.onap.optf.cmso.optimizer.service.rs.AdminToolImpl; +import org.onap.optf.cmso.optimizer.service.rs.HealthCheckImpl; +import org.onap.optf.cmso.optimizer.service.rs.OptimizerInterfaceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; + +@Component +@ApplicationPath("/") +public class JerseyConfiguration extends ResourceConfig { + private static final Logger log = Logger.getLogger(JerseyConfiguration.class.getName()); + + /** + * Object mapper. + * + * @return the object mapper + */ + @Bean + @Primary + public ObjectMapper objectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); + objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + return objectMapper; + } + + /** + * Instantiates a new jersey configuration. + */ + @Autowired + public JerseyConfiguration( /* LogRequestFilter lrf */ ) { + register(HealthCheckImpl.class); + register(AdminToolImpl.class); + register(OptimizerInterfaceImpl.class); + property(ServletProperties.FILTER_FORWARD_ON_404, true); + // TODO: ONAP Conversion identify appropriate ONAP logging filters if any + // register(lrf, 6001); + // register(LogResponseFilter.class, 6004); + + // TODO: Examine which logging features to enable + register(new LoggingFeature(log)); + register(CmsoContainerFilters.class); + } + + /** + * Jersey client. + * + * @return the client + */ + @Bean + public Client jerseyClient() { + ClientConfig client = new ClientConfig(); + + // TODO: ONAP Conversion identify appropriate ONAP logging filters if any + // client.register(TransactionIdRequestFilter.class); + // client.register(TransactionIdResponseFilter.class); + // client.register(DateTimeParamConverterProvider.class); + + return ClientBuilder.newClient(client); + } +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/SecurityConfig.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/SecurityConfig.java new file mode 100644 index 0000000..ff3f1b4 --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/SecurityConfig.java @@ -0,0 +1,59 @@ +/* + * Copyright © 2018 AT&T Intellectual Property. Modifications Copyright © 2018 IBM. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed under the Creative + * Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except + * in compliance with the License. You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.optf.cmso.optimizer; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +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; + +@Configuration +@EnableWebSecurity +@ComponentScan("org.onap.optf") +@Profile(SpringProfiles.PROPRIETARY__AUTHENTICATION) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private AuthProvider authProvider; + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + + auth.authenticationProvider(authProvider); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + + http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic(); + + } +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/SpringProfiles.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/SpringProfiles.java new file mode 100644 index 0000000..54d4b46 --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/SpringProfiles.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * + * Copyright © 2019 AT&T Intellectual Property. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed under the Creative + * Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except + * in compliance with the License. You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * + * * Unless required by applicable law or agreed to in writing, documentation distributed under the + * * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * * express or implied. See the License for the specific language governing permissions and + * * limitations under the License. + ******************************************************************************/ + +package org.onap.optf.cmso.optimizer; + +public class SpringProfiles { + + public static final String AAF_AUTHENTICATION = "aaf-auth"; + public static final String PROPRIETARY__AUTHENTICATION = "proprietary-auth"; + + private SpringProfiles() {} +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyClient.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyClient.java new file mode 100644 index 0000000..7674f43 --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyClient.java @@ -0,0 +1,183 @@ +/* + * ============LICENSE_START============================================== + * Copyright (c) 2019 AT&T Intellectual Property. + * ======================================================================= + * 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.optf.cmso.optimizer.clients.topology; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import org.onap.observations.Observation; +import org.onap.optf.cmso.common.BasicAuthenticatorFilter; +import org.onap.optf.cmso.common.PropertiesManagement; +import org.onap.optf.cmso.common.exceptions.CmsoException; +import org.onap.optf.cmso.optimizer.clients.topology.models.ElementCriteria; +import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyPolicyInfo; +import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyRequest; +import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyResponse; +import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyResponse.TopologyRequestStatus; +import org.onap.optf.cmso.optimizer.common.LogMessages; +import org.onap.optf.cmso.optimizer.filters.CmsoClientFilters; +import org.onap.optf.cmso.optimizer.model.Request; +import org.onap.optf.cmso.optimizer.model.Topology; +import org.onap.optf.cmso.optimizer.model.dao.RequestDao; +import org.onap.optf.cmso.optimizer.model.dao.TopologyDao; +import org.onap.optf.cmso.optimizer.service.rs.models.ElementInfo; +import org.onap.optf.cmso.optimizer.service.rs.models.OptimizerRequest; +import org.onap.optf.cmso.optimizer.service.rs.models.OptimizerResponse.OptimizeScheduleStatus; +import org.onap.optf.cmso.optimizer.service.rs.models.PolicyInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class TopologyClient { + private static EELFLogger debug = EELFManager.getInstance().getDebugLogger(); + + @Autowired + Environment env; + + @Autowired + PropertiesManagement pm; + + @Autowired + RequestDao requestDao; + + @Autowired + TopologyDao topologyDao; + + public TopologyResponse makeRequest(Request request, Topology topology) { + Integer maxAttempts = env.getProperty("cmso.optimizer.maxAttempts", Integer.class, 20); + if (topology.getTopologyRetries() >= maxAttempts) { + request.setStatus(OptimizeScheduleStatus.FAILED.toString()); + request.setRequestEnd(System.currentTimeMillis()); + requestDao.save(request); + return null; + } + TopologyRequest topologyRequest = new TopologyRequest(); + ObjectMapper om = new ObjectMapper(); + String originalRequest = request.getRequest(); + TopologyResponse topologyResponse = new TopologyResponse(); + OptimizerRequest optimizerRequest = null;; + try { + optimizerRequest = om.readValue(originalRequest, OptimizerRequest.class); + } catch (Exception e) { + topologyResponse.setStatus(TopologyRequestStatus.FAILED); + Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + } + topologyRequest = new TopologyRequest(); + topologyRequest.setRequestId(optimizerRequest.getRequestId()); + topologyRequest.setCommonData(optimizerRequest.getCommonData()); + topologyRequest.setElements(getElementCriteria(optimizerRequest)); + topologyRequest.setPolicies(getPolicies(optimizerRequest)); + try { + topologyResponse = initiateTopology(topologyRequest, topology, request); + } catch (Exception e) { + topologyResponse.setStatus(TopologyRequestStatus.FAILED); + Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + } + return topologyResponse; + } + + private List<TopologyPolicyInfo> getPolicies(OptimizerRequest optimizerRequest) { + List<TopologyPolicyInfo> list = new ArrayList<>(); + for (PolicyInfo optInfo : optimizerRequest.getPolicies()) { + TopologyPolicyInfo topInfo = new TopologyPolicyInfo(); + topInfo.setPolicyDescription(optInfo.getPolicyDescription()); + topInfo.setPolicyName(optInfo.getPolicyName()); + topInfo.setPolicyModifiers(optInfo.getPolicyModifiers()); + list.add(topInfo); + } + return list; + } + + private List<ElementCriteria> getElementCriteria(OptimizerRequest optimizerRequest) { + List<ElementCriteria> list = new ArrayList<>(); + for (ElementInfo info : optimizerRequest.getElements()) { + ElementCriteria criteria = new ElementCriteria(); + criteria.setElementId(info.getElementId()); + criteria.setElementData(info.getElementData()); + list.add(criteria); + } + return list; + } + + private TopologyResponse initiateTopology(TopologyRequest request, Topology topology, Request requestRow) throws CmsoException, JsonProcessingException { + String url = env.getProperty("cmso.topology.create.request.url"); + String username = env.getProperty("mechid.user"); + String password = pm.getProperty("mechid.pass", ""); + Client client = ClientBuilder.newClient(); + client.register(new BasicAuthenticatorFilter(username, password)); + client.register(new CmsoClientFilters()); + WebTarget webTarget = client.target(url); + Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); + debug.debug("topology url / user: " + url + " / " + username); + debug.debug("topology Request: " + new ObjectMapper().writeValueAsString(request)); + Observation.report(LogMessages.TOPOLOGY_REQUEST, "Begin", request.getRequestId(), url); + topology.setTopologyStart(System.currentTimeMillis()); + Response response = invocationBuilder.post(Entity.json(request)); + Observation.report(LogMessages.TOPOLOGY_REQUEST, "End", request.getRequestId(), url); + TopologyResponse topologyResponse = null; + switch (response.getStatus()) { + case 202: + debug.debug("Successfully scheduled asynchronous topology: " + request.getRequestId()); + break; + case 200: + debug.debug("Successfully retrieved topology: " + request.getRequestId()); + topologyResponse = processTopologyResponse(request, response, topology, requestRow); + break; + default: + throw new CmsoException(Status.INTERNAL_SERVER_ERROR, LogMessages.UNEXPECTED_RESPONSE, + url, response.getStatusInfo().toString()); + } + return topologyResponse; + } + + private TopologyResponse processTopologyResponse(TopologyRequest request, Response response, Topology topology, + Request requestRow) { + String responseString = response.readEntity(String.class); + TopologyResponse topologyResponse = null; + try { + topologyResponse = new ObjectMapper().readValue(responseString, TopologyResponse.class); + } + catch (Exception e) + { + Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + topologyResponse = new TopologyResponse(); + topologyResponse.setRequestId(request.getRequestId()); + topologyResponse.setStatus(TopologyRequestStatus.FAILED); + topologyResponse.setErrorMessage(e.getMessage()); + } + return topologyResponse; + } + +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyRequestManager.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyRequestManager.java new file mode 100644 index 0000000..3120e0d --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyRequestManager.java @@ -0,0 +1,100 @@ +/* + * ============LICENSE_START============================================== + * Copyright (c) 2019 AT&T Intellectual Property. + * ======================================================================= + * 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.optf.cmso.optimizer.clients.topology; + +import java.util.Optional; +import java.util.UUID; +import javax.ws.rs.core.Response.Status; +import org.onap.observations.Observation; +import org.onap.optf.cmso.common.exceptions.CmsoException; +import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyResponse; +import org.onap.optf.cmso.optimizer.common.LogMessages; +import org.onap.optf.cmso.optimizer.model.Request; +import org.onap.optf.cmso.optimizer.model.Topology; +import org.onap.optf.cmso.optimizer.model.dao.RequestDao; +import org.onap.optf.cmso.optimizer.model.dao.TopologyDao; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class TopologyRequestManager { + + @Autowired + Environment env; + + @Autowired + RequestDao requestDao; + + @Autowired + TopologyDao topologyDao; + + @Autowired + TopologyClient topologyClient; + + public TopologyResponse createTopologyRequest(UUID uuid) + { + try + { + Request request = null; + Optional<Request> requestOptional = requestDao.findById(uuid); + if (requestOptional.isPresent()) + { + request = requestOptional.get(); + } + if (request == null) + { + throw new CmsoException(Status.INTERNAL_SERVER_ERROR, LogMessages.EXPECTED_DATA_NOT_FOUND, + uuid.toString(), "Request table"); + } + Topology topology = null; + Optional<Topology> topologyOpt = topologyDao.findById(uuid); + if (topologyOpt.isPresent()) + { + topology = topologyOpt.get(); + + } + if (topology == null) + { + topology = new Topology(); + topology.setUuid(uuid); + topology.setTopologyRetries(0); + } + TopologyResponse topologyResponse = topologyClient.makeRequest(request, topology); + switch(topologyResponse.getStatus()) + { + case COMPLETED: + break; + case FAILED: + break; + case IN_PROGRESS: + break; + } + return topologyResponse; + } + catch (Exception e) + { + Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + } + return null; + + } + +} |