From 84b6500a6c3a95b927df2fa90cdf8453ed2a028b Mon Sep 17 00:00:00 2001 From: BT2983 Date: Mon, 23 Jul 2018 11:46:31 -0600 Subject: Adding naming micro-service code - API. API and configuration related classes. Change-Id: Ic62c502fc38b3f36dc12016e16f61adba789db9d Issue-ID: CCSDK-342 Signed-off-by: BT2983 --- .../apps/ms/neng/core/JerseyConfiguration.java | 62 ++++++ .../ccsdk/apps/ms/neng/core/WebConfiguration.java | 69 +++++++ .../neng/core/resource/model/GetConfigRequest.java | 77 +++++++ .../core/resource/model/GetConfigResponse.java | 39 ++++ .../ms/neng/core/resource/model/HelloWorld.java | 51 +++++ .../neng/core/resource/model/NameGenRequest.java | 60 ++++++ .../neng/core/resource/model/NameGenResponse.java | 41 ++++ .../PolicyManagerAuthorizationInterceptor.java | 52 +++++ .../apps/ms/neng/core/service/SpringService.java | 62 ++++++ .../ms/neng/core/service/SpringServiceImpl.java | 228 +++++++++++++++++++++ .../apps/ms/neng/core/service/rs/RestService.java | 102 +++++++++ .../ms/neng/core/service/rs/RestServiceImpl.java | 116 +++++++++++ .../neng/core/validator/ExternalKeyValidator.java | 44 ++++ .../extinf/impl/PolicyFinderServiceDbImpl.java | 59 ++++++ .../extinf/impl/PolicyFinderServiceImpl.java | 165 +++++++++++++++ 15 files changed, 1227 insertions(+) create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/JerseyConfiguration.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/WebConfiguration.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/GetConfigRequest.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/GetConfigResponse.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/HelloWorld.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/NameGenRequest.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/NameGenResponse.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/rs/interceptors/PolicyManagerAuthorizationInterceptor.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/SpringService.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/SpringServiceImpl.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/rs/RestService.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/rs/RestServiceImpl.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/validator/ExternalKeyValidator.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/PolicyFinderServiceDbImpl.java create mode 100644 ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/PolicyFinderServiceImpl.java (limited to 'ms/neng/src/main') diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/JerseyConfiguration.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/JerseyConfiguration.java new file mode 100644 index 00000000..4905e6eb --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/JerseyConfiguration.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core; + +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 javax.ws.rs.ApplicationPath; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.servlet.ServletProperties; +import org.onap.ccsdk.apps.ms.neng.core.service.rs.RestServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; + +/** + * Configuration of the REST framework. + */ +@Component +@ApplicationPath("/") +public class JerseyConfiguration extends ResourceConfig { + /** + * Builds the bean configuring Jackson for JSON serialization. + */ + @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; + } + + @Autowired + public JerseyConfiguration() { + register(RestServiceImpl.class); + property(ServletProperties.FILTER_FORWARD_ON_404, true); + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/WebConfiguration.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/WebConfiguration.java new file mode 100644 index 00000000..ca918eb9 --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/WebConfiguration.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core; + +import org.onap.ccsdk.apps.ms.neng.core.rs.interceptors.AaiAuthorizationInterceptor; +import org.onap.ccsdk.apps.ms.neng.core.rs.interceptors.PolicyManagerAuthorizationInterceptor; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +/** + * Configuration for the API part of the micro-service. + */ +@Configuration +public class WebConfiguration { + /** + * Creates the bean for configuring swagger. + */ + @Bean + public WebMvcConfigurerAdapter forwardToIndex() { + return new WebMvcConfigurerAdapter() { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/swagger").setViewName("redirect:/swagger/index.html"); + registry.addViewController("/swagger/").setViewName("redirect:/swagger/index.html"); + registry.addViewController("/docs").setViewName("redirect:/docs/html/index.html"); + registry.addViewController("/docs/").setViewName("redirect:/docs/html/index.html"); + } + }; + } + + /** + * Creates the bean for configuring policy manager interceptor. + */ + @Bean + public RestTemplateBuilder policyMgrRestTempBuilder(PolicyManagerAuthorizationInterceptor auth) { + RestTemplateBuilder restTemplateBuiler = new RestTemplateBuilder(); + return restTemplateBuiler.additionalInterceptors(auth); + } + + /** + * Creates the bean for configuring A&AI interceptor. + */ + @Bean + public RestTemplateBuilder aaiRestTempBuilder(AaiAuthorizationInterceptor auth) { + RestTemplateBuilder restTemplateBuiler = new RestTemplateBuilder(); + return restTemplateBuiler.additionalInterceptors(auth); + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/GetConfigRequest.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/GetConfigRequest.java new file mode 100644 index 00000000..e8bc555d --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/GetConfigRequest.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core.resource.model; + +import java.io.Serializable; +import java.util.Map; + +/** + * POJO representing policy manager get-config request. + */ +public class GetConfigRequest implements Serializable { + private static final long serialVersionUID = -8039686696076337053L; + + Map configAttributes; + String configName; + String ecompName; + String policyName; + boolean unique; + + public Map getConfigAttributes() { + return configAttributes; + } + + public void setConfigAttributes(Map configAttributes) { + this.configAttributes = configAttributes; + } + + public String getConfigName() { + return configName; + } + + public void setConfigName(String configName) { + this.configName = configName; + } + + public String getEcompName() { + return ecompName; + } + + public void setEcompName(String ecompName) { + this.ecompName = ecompName; + } + + public String getPolicyName() { + return policyName; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + public boolean isUnique() { + return unique; + } + + public void setUnique(boolean unique) { + this.unique = unique; + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/GetConfigResponse.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/GetConfigResponse.java new file mode 100644 index 00000000..9fe567f1 --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/GetConfigResponse.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core.resource.model; + +import java.io.Serializable; + +/** + * POJO representing policy manager get-config response. + */ +public class GetConfigResponse implements Serializable { + private static final long serialVersionUID = -8039686696076337053L; + Object response; + + public Object getResponse() { + return response; + } + + public void setResponse(Object response) { + this.response = response; + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/HelloWorld.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/HelloWorld.java new file mode 100644 index 00000000..19de4e33 --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/HelloWorld.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core.resource.model; + +/** + * POJO representing the hello/ping/heart-beat operation request. + */ +public class HelloWorld { + String message; + + public HelloWorld() { + } + + public HelloWorld(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + /** + * Gives a readable representation of this object. + */ + @Override + public String toString() { + return "message = " + getMessage(); + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/NameGenRequest.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/NameGenRequest.java new file mode 100644 index 00000000..9fa91410 --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/NameGenRequest.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core.resource.model; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +/** + * POJO representing the request from the client. + */ +public class NameGenRequest implements Serializable { + private static final long serialVersionUID = -8039686696076337053L; + + List> elements; + Boolean useDb; + + public List> getElements() { + return elements; + } + + public void setElements(List> elements) { + this.elements = elements; + } + + public Boolean getUseDb() { + return useDb; + } + + public void setUseDb(Boolean useDb) { + this.useDb = useDb; + } + + /** + * Gives a readable representation of this object. + */ + public String toString() { + StringBuffer buf = new StringBuffer(); + buf.append("elements: " + this.elements); + return buf.toString(); + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/NameGenResponse.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/NameGenResponse.java new file mode 100644 index 00000000..c4ac7fcb --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/resource/model/NameGenResponse.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core.resource.model; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +/** + * POJO representing the response back to the client. + */ +public class NameGenResponse implements Serializable { + private static final long serialVersionUID = -8039686696076337053L; + List> elements; + + public List> getElements() { + return elements; + } + + public void setElements(List> elements) { + this.elements = elements; + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/rs/interceptors/PolicyManagerAuthorizationInterceptor.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/rs/interceptors/PolicyManagerAuthorizationInterceptor.java new file mode 100644 index 00000000..c0a28f13 --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/rs/interceptors/PolicyManagerAuthorizationInterceptor.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core.rs.interceptors; + +import java.io.IOException; +import org.onap.ccsdk.apps.ms.neng.extinf.props.PolicyManagerProps; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; + +/** + * Interceptor for adding authorization headers in the request to policy manager. + */ +@Component +public class PolicyManagerAuthorizationInterceptor implements ClientHttpRequestInterceptor { + @Autowired + PolicyManagerProps props; + + /** + * Intercepts the given request and adds additional headers, mainly for authorization. + */ + @Override + public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body, + ClientHttpRequestExecution executionChain) throws IOException { + httpRequest.getHeaders().add("ClientAuth", props.getClientAuth()); + httpRequest.getHeaders().add("Environment", props.getEnvironment()); + httpRequest.getHeaders().add("X-ECOMP-RequestID", props.getEcompRequestId()); + httpRequest.getHeaders().add("Authorization", props.getBasicAuth()); + return executionChain.execute(httpRequest, body); + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/SpringService.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/SpringService.java new file mode 100644 index 00000000..1cdd61e1 --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/SpringService.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core.service; + +import org.onap.ccsdk.apps.ms.neng.core.resource.model.HelloWorld; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.NameGenRequest; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.NameGenResponse; +import org.onap.ccsdk.apps.ms.neng.persistence.entity.PolicyDetails; + +/** + * Specification for the implementation of the APIs exposed by this micro-service. + */ +public interface SpringService { + /** + * Name generation API. + */ + public NameGenResponse genNetworkElementName(NameGenRequest request) throws Exception; + + /** + * Name removal API. + */ + public NameGenResponse releaseNetworkElementName(NameGenRequest request) throws Exception; + + /** + * API to return naming policy cached in this micro-service. + * + *

This is not used by clients -- it is here to help with diagnostics. + */ + public PolicyDetails getPolicyDetails(String policyName); + + /** + * API to add a naming policy to the database cache in this micro-service. + * + *

This is not used by clients -- it is here to help with diagnostics. + */ + public void addPolicy(Object request) throws Exception; + + /** + * Heart-beat/ping API. + * + *

This is not used by clients -- it is here to help with diagnostics. + */ + public HelloWorld getQuickHello(String name); +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/SpringServiceImpl.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/SpringServiceImpl.java new file mode 100644 index 00000000..72aee461 --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/SpringServiceImpl.java @@ -0,0 +1,228 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; +import java.util.stream.Collectors; +import javax.transaction.Transactional; +import org.onap.ccsdk.apps.ms.neng.core.exceptions.NengException; +import org.onap.ccsdk.apps.ms.neng.core.gen.NameGenerator; +import org.onap.ccsdk.apps.ms.neng.core.persistence.NamePersister; +import org.onap.ccsdk.apps.ms.neng.core.policy.PolicyFinder; +import org.onap.ccsdk.apps.ms.neng.core.policy.PolicyParameters; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.HelloWorld; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.NameGenRequest; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.NameGenResponse; +import org.onap.ccsdk.apps.ms.neng.core.seq.SequenceGenerator; +import org.onap.ccsdk.apps.ms.neng.core.validator.AaiNameValidator; +import org.onap.ccsdk.apps.ms.neng.core.validator.DbNameValidator; +import org.onap.ccsdk.apps.ms.neng.core.validator.ExternalKeyValidator; +import org.onap.ccsdk.apps.ms.neng.persistence.entity.GeneratedName; +import org.onap.ccsdk.apps.ms.neng.persistence.entity.PolicyDetails; +import org.onap.ccsdk.apps.ms.neng.persistence.entity.ServiceParameter; +import org.onap.ccsdk.apps.ms.neng.persistence.repository.GeneratedNameRespository; +import org.onap.ccsdk.apps.ms.neng.persistence.repository.PolicyDetailsRepository; +import org.onap.ccsdk.apps.ms.neng.persistence.repository.ServiceParameterRepository; +import org.onap.ccsdk.apps.ms.neng.service.extinf.impl.AaiServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +/** + * Implementation of the APIs exposed by this micro-service. + */ +@Service +public class SpringServiceImpl implements SpringService { + private static Logger log = Logger.getLogger(SpringServiceImpl.class.getName()); + + @Autowired AaiServiceImpl aaiService; + @Autowired ExternalKeyValidator externalKeyValidator; + @Autowired @Qualifier("policyFinderServiceImpl") PolicyFinder policyFinder; + @Autowired @Qualifier("policyFinderServiceDBImpl") PolicyFinder policyFinderDbImpl; + @Autowired PolicyParameters policyParameters; + @Autowired SequenceGenerator sequenceGenerator; + @Autowired DbNameValidator dbNameValidator; + @Autowired PolicyDetailsRepository policyDetailsRepository; + @Autowired AaiNameValidator aaiNameValidator; + @Autowired NamePersister namePersister; + @Autowired ServiceParameterRepository serviceParamRepo; + @Autowired GeneratedNameRespository generatedNameRepository; + + /** + * Heart-beat/ping API. + */ + @Override + public HelloWorld getQuickHello(String name) { + if (name == null || name.isEmpty()) { + name = "world"; + } + String message = "Hello " + name + "!"; + log.info(message); + HelloWorld hello = new HelloWorld(message); + log.info(hello.toString()); + return hello; + } + + /** + * Name generation API. + */ + @Transactional(rollbackOn = Exception.class) + public NameGenResponse genNetworkElementName(NameGenRequest request) throws Exception { + try { + Map> earlierNames = new HashMap>(); + List> allElements = new ArrayList>(); + Map> policyCache = new HashMap>(); + List> generatedNames = new ArrayList>(); + validateRequest(request); + if (request.getElements() != null && request.getElements().size() > 0) { + allElements.addAll(request.getElements()); + } + PolicyFinder policyFinderImpl = findPolicyFinderImpl(request); + for (Map requestElement : allElements) { + log.info("Processing " + requestElement.toString()); + NameGenerator nameGen = new NameGenerator(policyFinderImpl, policyParameters, sequenceGenerator, + dbNameValidator, aaiNameValidator, namePersister, requestElement, allElements, + earlierNames, policyCache); + generatedNames.add(nameGen.generate()); + } + NameGenResponse resp = new NameGenResponse(); + resp.setElements(generatedNames); + return resp; + } catch (Exception e) { + if (e instanceof NengException) { + throw e; + } else { + e.printStackTrace(); + throw new Exception("Internal error occurred while processing the request"); + } + } + } + + /** + * Name removal API. + */ + @Transactional(rollbackOn = Exception.class) + public NameGenResponse releaseNetworkElementName(NameGenRequest request) throws Exception { + NameGenResponse response = new NameGenResponse(); + Timestamp curTime = new Timestamp(System.currentTimeMillis()); + try { + for (Map requestElement : request.getElements()) { + String key = requestElement.get("external-key"); + List generatedNames = generatedNameRepository.findByExternalId(key); + for (GeneratedName generatedName : generatedNames) { + generatedName.setIsReleased("Y"); + generatedName.setLastUpdatedTime(curTime); + } + buildUnAssignResponse(generatedNames, response); + } + return response; + } catch (Exception e) { + if (e instanceof NengException) { + throw e; + } else { + e.printStackTrace(); + throw new Exception("Internal error occurred while processing the request"); + } + } + } + + /** + * API to return naming policy cached in this micro-service. + */ + @Override + public PolicyDetails getPolicyDetails(String policyName) { + try { + return policyDetailsRepository.findPolicyResponseByName(policyName); + } catch (Exception e) { + return new PolicyDetails(); + } + } + + /** + * API to add a naming policy to the database cache in this micro-service. + */ + @Override + public void addPolicy(Object request) throws Exception { + try { + @SuppressWarnings("unchecked") + Map policyData = (Map)request; + PolicyDetails pd = new PolicyDetails(); + pd.setPolicyName((String) policyData.get("policyName")); + ObjectMapper objectmapper = new ObjectMapper(); + log.info(objectmapper.writeValueAsString(policyData.get("policyValue"))); + pd.setPolicyResponse(objectmapper.writeValueAsString(policyData.get("policyValue"))); + policyDetailsRepository.save(pd); + } catch (Exception e) { + log.warning(e.getMessage()); + } + } + + void buildUnAssignResponse(List generatedNames, NameGenResponse response) { + if (response.getElements() == null) { + response.setElements(new ArrayList>()); + } + for (GeneratedName generatedName : generatedNames) { + Map element = new HashMap<>(); + element.put("external-key", generatedName.getExternalId()); + element.put("resource-name", generatedName.getElementType()); + element.put("resource-value", generatedName.getName()); + response.getElements().add(element); + } + } + + void validateRequest(NameGenRequest request) throws Exception { + List> elems = request.getElements(); + if (elems != null && elems.size() > 0) { + boolean error = false; + Set externalKeySet = elems.stream().map(s -> s.get("external-key")).collect(Collectors.toSet()); + if (externalKeySet.size() != request.getElements().size()) { + error = true; + } + for (String externalKey : externalKeySet) { + if (externalKey == null || externalKeyValidator.isPresent(externalKey)) { + error = true; + } + } + if (error) { + throw new NengException("External Key is required and must be unique"); + } + } + } + + private PolicyFinder findPolicyFinderImpl(NameGenRequest request) { + if (request.getUseDb() != null && !request.getUseDb()) { + return this.policyFinder; + } + ServiceParameter param = serviceParamRepo.findByName("use_db_policy"); + if ((request.getUseDb() != null && request.getUseDb().booleanValue()) + || (param != null && "Y".equals(param.getValue()))) { + return policyFinderDbImpl; + } + return this.policyFinder; + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/rs/RestService.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/rs/RestService.java new file mode 100644 index 00000000..f8da1eee --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/rs/RestService.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core.service.rs; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import java.util.List; +import java.util.Map; +import javax.validation.Valid; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.NameGenRequest; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.NameGenResponse; +import org.springframework.web.bind.annotation.RequestBody; + + +/** + * Specifies the properties of the REST-style interface/API to this micro-service. + */ +@Api +@Path("/service") +@Produces({MediaType.APPLICATION_JSON}) +public interface RestService { + /** + * Name generation API. + */ + @POST + @Path("/v1/genNetworkElementName") + @Produces({MediaType.APPLICATION_JSON}) + @ApiOperation(value = "Generates network element names, based on naming policies", + response = NameGenResponse.class) + @ApiResponses(value = {@ApiResponse(code = 404, message = "Service not available"), + @ApiResponse(code = 500, message = "Unexpected Runtime error")}) + public Response generateNetworkElementName(@RequestBody @Valid NameGenRequest request); + + /** + * Name removal API. + */ + @DELETE + @Path("/v1/genNetworkElementName") + @Produces({MediaType.APPLICATION_JSON}) + @ApiOperation(value = "Releases network element names", response = NameGenResponse.class) + @ApiResponses(value = {@ApiResponse(code = 404, message = "Service not available"), + @ApiResponse(code = 500, message = "Unexpected Runtime error")}) + public Response releaseNetworkElementName(@RequestBody @Valid NameGenRequest request); + + /** + * API to return naming policy cached in this micro-service. + * + *

This is not used by clients -- it is here to help with diagnostics. + */ + @GET + @Path("/v1/getpolicyresponse/{policyName}") + @Produces({MediaType.APPLICATION_JSON}) + public List> getPolicyResponse(@QueryParam("policyName") String policyName) throws Exception; + + /** + * API to add a naming policy to the database cache in this micro-service. + * + *

This is not used by clients -- it is here to help with diagnostics. + */ + @POST + @Path("/v1/addPolicy") + @Produces({MediaType.APPLICATION_JSON}) + public Map addPolicyToDb(Object request) throws Exception; + + /** + * Heart-beat/ping API. + * + *

This is not used by clients -- it is here to help with diagnostics. + */ + @GET + @Path("/hello") + @Produces({MediaType.APPLICATION_JSON}) + public Response getQuickHello(@QueryParam("name") String name); +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/rs/RestServiceImpl.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/rs/RestServiceImpl.java new file mode 100644 index 00000000..ed5723b6 --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/service/rs/RestServiceImpl.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core.service.rs; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; +import javax.validation.Valid; +import javax.ws.rs.core.Response; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.HelloWorld; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.NameGenRequest; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.NameGenResponse; +import org.onap.ccsdk.apps.ms.neng.core.service.SpringService; +import org.onap.ccsdk.apps.ms.neng.persistence.entity.PolicyDetails; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.RequestBody; + +/** + * Implementation of the REST-style interface/API to this micro-service. + */ +@Component +public class RestServiceImpl implements RestService { + private static Logger log = Logger.getLogger(RestServiceImpl.class.getName()); + + @Autowired SpringService service; + + /** + * Heart-beat/ping API. + */ + @Override + public Response getQuickHello(String name) { + log.info(name); + HelloWorld hw = service.getQuickHello(name); + return Response.ok().entity(hw).build(); + } + + /** + * Name generation API. + */ + @Override + public Response generateNetworkElementName(@RequestBody @Valid NameGenRequest request) { + log.info("Received request: " + request.toString()); + try { + NameGenResponse resp = service.genNetworkElementName(request); + return Response.ok().entity(resp).build(); + } catch (Exception e) { + log.warning(e.getMessage()); + return Response.status(500).entity("{ \"error\": \"" + e.getMessage() + "\" }").build(); + } + } + + /** + * Name removal API. + */ + @Override + public Response releaseNetworkElementName(NameGenRequest request) { + NameGenResponse resp; + try { + resp = service.releaseNetworkElementName(request); + return Response.ok().entity(resp).build(); + } catch (Exception e) { + log.warning(e.getMessage()); + return Response.status(500).entity("{ \"error\": \"" + e.getMessage() + "\" }").build(); + } + } + + /** + * API to return naming policy cached in this micro-service. + */ + @Override + public List> getPolicyResponse(String policyName) throws Exception { + PolicyDetails policyDetails = service.getPolicyDetails(policyName); + List> policyResponse = null; + ObjectMapper mapper = new ObjectMapper(); + policyResponse = mapper.readValue(policyDetails.getPolicyResponse(), + new TypeReference>>() {}); + return policyResponse; + } + + /** + * API to add a naming policy to the database cache in this micro-service. + */ + @Override + public Map addPolicyToDb(Object request) throws Exception { + Map respMap = new HashMap<>(); + try { + service.addPolicy(request); + respMap.put("status", "Policy added successfully"); + } catch (Exception e) { + respMap.put("status", "Failed"); + } + return respMap; + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/validator/ExternalKeyValidator.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/validator/ExternalKeyValidator.java new file mode 100644 index 00000000..28dde566 --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/core/validator/ExternalKeyValidator.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.core.validator; + +import org.onap.ccsdk.apps.ms.neng.persistence.repository.GeneratedNameRespository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * Checks if the external key in the request is already there in the DB or not. + */ +@Component +public class ExternalKeyValidator { + @Autowired + GeneratedNameRespository genNameRepo; + + /** + * Tells if the given external ID is present in the DB. + */ + public boolean isPresent(String externalId) { + if (genNameRepo.findByExternalId(externalId).size() > 0) { + return true; + } + return false; + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/PolicyFinderServiceDbImpl.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/PolicyFinderServiceDbImpl.java new file mode 100644 index 00000000..d283b362 --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/PolicyFinderServiceDbImpl.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.service.extinf.impl; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.List; +import java.util.Map; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigResponse; +import org.onap.ccsdk.apps.ms.neng.persistence.entity.PolicyDetails; +import org.onap.ccsdk.apps.ms.neng.persistence.repository.PolicyDetailsRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +/** + * Finds policies from the database. + */ +@Component +@Qualifier("PolicyFinderDbImpl") +public class PolicyFinderServiceDbImpl extends PolicyFinderServiceImpl { + @Autowired + PolicyDetailsRepository policyDetailsRepo; + + /** + * Finds the policy with the given name from the DB. + */ + @Override + public GetConfigResponse getConfig(String policyName) throws Exception { + ObjectMapper objectmapper = new ObjectMapper(); + objectmapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); + PolicyDetails policyDetails = policyDetailsRepo.findPolicyResponseByName(policyName); + List> respObj = objectmapper.readValue(policyDetails.getPolicyResponse(), + new TypeReference>>() {}); + transformConfigObject(objectmapper, respObj); + GetConfigResponse configResp = new GetConfigResponse(); + configResp.setResponse(respObj); + return configResp; + } +} diff --git a/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/PolicyFinderServiceImpl.java b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/PolicyFinderServiceImpl.java new file mode 100644 index 00000000..a19c9153 --- /dev/null +++ b/ms/neng/src/main/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/PolicyFinderServiceImpl.java @@ -0,0 +1,165 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps + * ================================================================================ + * 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.ccsdk.apps.ms.neng.service.extinf.impl; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.URI; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; +import javax.net.ssl.SSLContext; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.onap.ccsdk.apps.ms.neng.core.exceptions.NengException; +import org.onap.ccsdk.apps.ms.neng.core.policy.PolicyFinder; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigRequest; +import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigResponse; +import org.onap.ccsdk.apps.ms.neng.core.rs.interceptors.PolicyManagerAuthorizationInterceptor; +import org.onap.ccsdk.apps.ms.neng.extinf.props.PolicyManagerProps; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestTemplate; + +/** + * Finds policies from policy manager. + */ +@Component +@Qualifier("PolicyFinderServiceImpl") +public class PolicyFinderServiceImpl implements PolicyFinder { + private static Logger log = Logger.getLogger(PolicyFinderServiceImpl.class.getName()); + + @Autowired PolicyManagerProps policManProps; + @Autowired + @Qualifier("policyMgrRestTempBuilder") + RestTemplateBuilder policyMgrRestTempBuilder; + @Autowired PolicyManagerAuthorizationInterceptor authInt; + RestTemplate restTemplate; + + /** + * Find policy with the given name from policy manager. + */ + @Override + public Map findPolicy(String policyName) throws Exception { + Object response = getConfig(policyName).getResponse(); + if (response instanceof List) { + @SuppressWarnings("unchecked") + List> policyList = (List>)response; + return ((policyList != null && policyList.size() > 0) ? policyList.get(0) : null); + } else { + return null; + } + } + + GetConfigResponse getConfig(String policyName) throws Exception { + GetConfigRequest getConfigRequest = new GetConfigRequest(); + getConfigRequest.setPolicyName(policyName); + GetConfigResponse getConfigResponse = makeOutboundCall(getConfigRequest, GetConfigResponse.class); + return getConfigResponse; + } + + GetConfigResponse makeOutboundCall(T request, Class response) throws Exception { + log.info("Policy Manager - " + policManProps.getUrl()); + RequestEntity re = RequestEntity.post(new URI(policManProps.getUrl())) + .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).body(request); + try { + ResponseEntity resp = getRestTemplate().exchange(re, Object.class); + if (HttpStatus.OK.equals(resp.getStatusCode())) { + ObjectMapper objectmapper = new ObjectMapper(); + System.out.println(objectmapper.writeValueAsString(resp.getBody())); + List> respObj = objectmapper.readValue( + objectmapper.writeValueAsString(resp.getBody()), + new TypeReference>>() {}); + transformConfigObject(objectmapper, respObj); + GetConfigResponse getConfigResp = new GetConfigResponse(); + getConfigResp.setResponse(respObj); + return getConfigResp; + } + } catch (HttpStatusCodeException e) { + handleError(e); + } + throw new NengException("Error while retrieving policy from policy manager."); + } + + void handleError(HttpStatusCodeException e) throws Exception { + String respString = e.getResponseBodyAsString(); + log.info(respString); + if (HttpStatus.NOT_FOUND.equals(e.getStatusCode()) && (respString != null && respString.contains(""))) { + throw new NengException("Policy not found in policy manager."); + } + throw new NengException("Error while retrieving policy from policy manager."); + } + + /** + * Transforms the 'config' element (which is received as a JSON string) to a map like a JSON object. + */ + void transformConfigObject(ObjectMapper objectmapper, List> respObj) throws Exception { + Object configElement = respObj.get(0).get("config"); + if (configElement instanceof String) { + Map obj = objectmapper.readValue(configElement.toString(), + new TypeReference>() {}); + respObj.get(0).put("config", obj); + } + } + + RestTemplate getRestTemplate() throws Exception { + if (restTemplate != null) { + return restTemplate; + } + TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; + SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() + .loadTrustMaterial(null, acceptingTrustStrategy).build(); + SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); + CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); + requestFactory.setHttpClient(httpClient); + restTemplate = new RestTemplate(requestFactory); + restTemplate.getInterceptors().add(getAuthInt()); + return restTemplate; + } + + RestTemplateBuilder getPolicyMgrRestTempBuilder() { + return policyMgrRestTempBuilder; + } + + void setPolicyMgrRestTempBuilder(RestTemplateBuilder policyMgrRestTempBuilder) { + this.policyMgrRestTempBuilder = policyMgrRestTempBuilder; + } + + PolicyManagerAuthorizationInterceptor getAuthInt() { + return authInt; + } + + void setAuthInt(PolicyManagerAuthorizationInterceptor authInt) { + this.authInt = authInt; + } +} -- cgit 1.2.3-korg