2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 Nordix Foundation.
4 * Modifications Copyright (C) 2020 AT&T Inc.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.distribution.forwarding.lifecycle.api;
24 import com.google.common.collect.ImmutableMap;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.List;
30 import javax.ws.rs.client.Entity;
31 import javax.ws.rs.core.HttpHeaders;
32 import javax.ws.rs.core.MediaType;
33 import javax.ws.rs.core.Response;
34 import javax.ws.rs.core.Response.Status;
35 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
36 import org.onap.policy.common.endpoints.http.client.HttpClient;
37 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
38 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
39 import org.onap.policy.common.parameters.ParameterService;
40 import org.onap.policy.distribution.forwarding.PolicyForwarder;
41 import org.onap.policy.distribution.forwarding.PolicyForwardingException;
42 import org.onap.policy.models.pap.concepts.PdpDeployPolicies;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
51 * This class provides an implementation of {@link PolicyForwarder} interface for forwarding the given policies & policy
52 * types to the life cycle api's of policy framework.
54 * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
56 public class LifecycleApiPolicyForwarder implements PolicyForwarder {
58 private static final String DEPLOY_POLICY_URI = "/policy/pap/v1/pdps/policies";
59 private static final String CREATE_POLICY_TYPE_URI = "/policy/api/v1/policytypes/";
60 private static final Logger LOGGER = LoggerFactory.getLogger(LifecycleApiPolicyForwarder.class);
61 private LifecycleApiForwarderParameters forwarderParameters;
67 public void configure(final String parameterGroupName) {
68 forwarderParameters = ParameterService.get(parameterGroupName);
75 public void forward(final Collection<ToscaEntity> entities) throws PolicyForwardingException {
76 final List<ToscaEntity> failedEntities = new ArrayList<>();
77 for (final ToscaEntity entity : entities) {
78 forwardSingleEntity(failedEntities, entity);
80 if (!failedEntities.isEmpty()) {
81 throw new PolicyForwardingException(
82 "Failed forwarding the following entities: " + Arrays.toString(failedEntities.toArray()));
86 private void forwardSingleEntity(final List<ToscaEntity> failedEntities, final ToscaEntity entity) {
87 Response policyCreated = null;
89 if (entity instanceof ToscaServiceTemplate) {
90 final ToscaServiceTemplate toscaServiceTemplate = (ToscaServiceTemplate) entity;
91 if (null != toscaServiceTemplate.getPolicyTypes() && !toscaServiceTemplate.getPolicyTypes().isEmpty()) {
92 createPolicyType(toscaServiceTemplate);
94 if (null != toscaServiceTemplate.getToscaTopologyTemplate()
95 && null != toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()
96 && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().isEmpty()
97 && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet().isEmpty()) {
98 policyCreated = createPolicy(toscaServiceTemplate);
100 if (forwarderParameters.isDeployPolicies() && policyCreated != null) {
101 deployPolicy(policyCreated.readEntity(ToscaServiceTemplate.class));
104 throw new PolicyForwardingException("The entity is not of type ToscaServiceTemplate - " + entity);
106 } catch (final Exception exp) {
107 LOGGER.error(exp.getMessage(), exp);
108 failedEntities.add(entity);
112 private Response createPolicyType(final ToscaServiceTemplate toscaServiceTemplate)
113 throws PolicyForwardingException {
114 return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON), CREATE_POLICY_TYPE_URI,
118 private Response createPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
119 final ToscaPolicy policy = toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet()
120 .iterator().next().getValue();
121 return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON),
122 CREATE_POLICY_TYPE_URI + policy.getType() + "/versions/" + policy.getTypeVersion() + "/policies", true);
125 private Response deployPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
126 final PdpDeployPolicies pdpPolicies = new PdpDeployPolicies();
127 final List<ToscaPolicyIdentifierOptVersion> policyIdentifierList = new ArrayList<>();
128 for (final Map<String, ToscaPolicy> policyMap : toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()) {
129 final String policyId = policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-id");
130 final String policyVersion =
131 policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-version");
132 final ToscaPolicyIdentifierOptVersion toscaPolicyIdentifier =
133 new ToscaPolicyIdentifierOptVersion(policyId, policyVersion);
134 policyIdentifierList.add(toscaPolicyIdentifier);
136 pdpPolicies.setPolicies(policyIdentifierList);
137 return invokeHttpClient(Entity.entity(pdpPolicies, MediaType.APPLICATION_JSON), DEPLOY_POLICY_URI, false);
140 private Response invokeHttpClient(final Entity<?> entity, final String path, final boolean wantApi)
141 throws PolicyForwardingException {
142 Response response = null;
144 response = getHttpClient(wantApi).post(path, entity, ImmutableMap.of(HttpHeaders.ACCEPT,
145 MediaType.APPLICATION_JSON, HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
146 if (response.getStatus() != Status.OK.getStatusCode()) {
148 "Invocation of path {} failed for entity {}. Response status: {}, Response status info: {}",
149 path, entity, response.getStatus(), response.getStatusInfo());
150 throw new PolicyForwardingException("Failed creating the entity - " + entity);
152 } catch (final HttpClientConfigException exception) {
153 throw new PolicyForwardingException("Invocation of path " + path + " failed for entity " + entity,
159 private HttpClient getHttpClient(final boolean wantApi) throws HttpClientConfigException {
160 final boolean https = forwarderParameters.isHttps();
161 final LifecycleApiParameters parameters =
162 (wantApi ? forwarderParameters.getApiParameters() : forwarderParameters.getPapParameters());
163 final BusTopicParams params = BusTopicParams.builder().clientName("Policy Distribution").useHttps(https)
164 .hostname(parameters.getHostName()).port(parameters.getPort()).userName(parameters.getUserName())
165 .password(parameters.getPassword())
167 return HttpClientFactoryInstance.getClientFactory().build(params);