2  * ============LICENSE_START=======================================================
 
   3  *  Copyright (C) 2019 Nordix Foundation.
 
   4  *  Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
 
   5  *  Modifications Copyright (C) 2021 Bell Canada.
 
   6  * ================================================================================
 
   7  * Licensed under the Apache License, Version 2.0 (the "License");
 
   8  * you may not use this file except in compliance with the License.
 
   9  * You may obtain a copy of the License at
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  13  * Unless required by applicable law or agreed to in writing, software
 
  14  * distributed under the License is distributed on an "AS IS" BASIS,
 
  15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  16  * See the License for the specific language governing permissions and
 
  17  * limitations under the License.
 
  19  * SPDX-License-Identifier: Apache-2.0
 
  20  * ============LICENSE_END=========================================================
 
  23 package org.onap.policy.distribution.forwarding.lifecycle.api;
 
  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 org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
 
  35 import org.onap.policy.common.endpoints.http.client.HttpClient;
 
  36 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
 
  37 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
 
  38 import org.onap.policy.common.parameters.ParameterService;
 
  39 import org.onap.policy.distribution.forwarding.PolicyForwarder;
 
  40 import org.onap.policy.distribution.forwarding.PolicyForwardingException;
 
  41 import org.onap.policy.models.pap.concepts.PdpDeployPolicies;
 
  42 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
 
  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.ToscaServiceTemplate;
 
  46 import org.slf4j.Logger;
 
  47 import org.slf4j.LoggerFactory;
 
  50  * This class provides an implementation of {@link PolicyForwarder} interface for forwarding the given policies & policy
 
  51  * types to the life cycle api's of policy framework.
 
  53  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
 
  55 public class LifecycleApiPolicyForwarder implements PolicyForwarder {
 
  57     private static final String DEPLOY_POLICY_URI = "/policy/pap/v1/pdps/policies";
 
  58     private static final String CREATE_POLICY_TYPE_URI = "/policy/api/v1/policytypes/";
 
  59     private static final Logger LOGGER = LoggerFactory.getLogger(LifecycleApiPolicyForwarder.class);
 
  60     private LifecycleApiForwarderParameters forwarderParameters;
 
  66     public void configure(final String parameterGroupName) {
 
  67         forwarderParameters = ParameterService.get(parameterGroupName);
 
  74     public void forward(final Collection<ToscaEntity> entities) throws PolicyForwardingException {
 
  75         final List<ToscaEntity> failedEntities = new ArrayList<>();
 
  76         for (final ToscaEntity entity : entities) {
 
  77             forwardSingleEntity(failedEntities, entity);
 
  79         if (!failedEntities.isEmpty()) {
 
  80             throw new PolicyForwardingException(
 
  81                     "Failed forwarding the following entities: " + Arrays.toString(failedEntities.toArray()));
 
  85     private void forwardSingleEntity(final List<ToscaEntity> failedEntities, final ToscaEntity entity) {
 
  86         Response policyCreated = null;
 
  88             if (entity instanceof ToscaServiceTemplate) {
 
  89                 final var toscaServiceTemplate = (ToscaServiceTemplate) entity;
 
  90                 if (null != toscaServiceTemplate.getPolicyTypes() && !toscaServiceTemplate.getPolicyTypes().isEmpty()) {
 
  91                     createPolicyType(toscaServiceTemplate);
 
  93                 if (null != toscaServiceTemplate.getToscaTopologyTemplate()
 
  94                         && null != toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()
 
  95                         && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().isEmpty()
 
  96                         && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet().isEmpty()) {
 
  97                     policyCreated = createPolicy(toscaServiceTemplate);
 
  99                 if (forwarderParameters.isDeployPolicies() && policyCreated != null) {
 
 100                     deployPolicy(policyCreated.readEntity(ToscaServiceTemplate.class));
 
 103                 throw new PolicyForwardingException("The entity is not of type ToscaServiceTemplate - " + entity);
 
 105         } catch (final Exception exp) {
 
 106             LOGGER.error(exp.getMessage(), exp);
 
 107             failedEntities.add(entity);
 
 111     private Response createPolicyType(final ToscaServiceTemplate toscaServiceTemplate)
 
 112             throws PolicyForwardingException {
 
 113         return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON), CREATE_POLICY_TYPE_URI,
 
 117     private Response createPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
 
 118         final ToscaPolicy policy = toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet()
 
 119                 .iterator().next().getValue();
 
 120         return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON),
 
 121                 CREATE_POLICY_TYPE_URI + policy.getType() + "/versions/" + policy.getTypeVersion() + "/policies", true);
 
 124     private Response deployPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
 
 125         final var pdpPolicies = new PdpDeployPolicies();
 
 126         final List<ToscaConceptIdentifierOptVersion> policyIdentifierList = new ArrayList<>();
 
 127         for (final Map<String, ToscaPolicy> policyMap : toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()) {
 
 128             final String policyId = policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-id");
 
 129             final String policyVersion =
 
 130                     policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-version");
 
 131             final var toscaPolicyIdentifier =
 
 132                     new ToscaConceptIdentifierOptVersion(policyId, policyVersion);
 
 133             policyIdentifierList.add(toscaPolicyIdentifier);
 
 135         pdpPolicies.setPolicies(policyIdentifierList);
 
 136         return invokeHttpClient(Entity.entity(pdpPolicies, MediaType.APPLICATION_JSON), DEPLOY_POLICY_URI, false);
 
 139     private Response invokeHttpClient(final Entity<?> entity, final String path, final boolean wantApi)
 
 140             throws PolicyForwardingException {
 
 141         Response response = null;
 
 143             response = getHttpClient(wantApi).post(path, entity, Map.of(HttpHeaders.ACCEPT,
 
 144                     MediaType.APPLICATION_JSON, HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
 
 145             if (response.getStatus() / 100 != 2) {
 
 147                         "Invocation of path {} failed for entity {}. Response status: {}, Response status info: {}",
 
 148                         path, entity, response.getStatus(), response.getStatusInfo());
 
 149                 throw new PolicyForwardingException("Failed creating the entity - " + entity);
 
 151         } catch (final HttpClientConfigException exception) {
 
 152             throw new PolicyForwardingException("Invocation of path " + path + " failed for entity " + entity,
 
 158     private HttpClient getHttpClient(final boolean wantApi) throws HttpClientConfigException {
 
 159         final boolean https = forwarderParameters.isHttps();
 
 160         final LifecycleApiParameters parameters =
 
 161                 (wantApi ? forwarderParameters.getApiParameters() : forwarderParameters.getPapParameters());
 
 162         final BusTopicParams params = BusTopicParams.builder().clientName("Policy Distribution").useHttps(https)
 
 163                 .hostname(parameters.getHostName()).port(parameters.getPort()).userName(parameters.getUserName())
 
 164                 .password(parameters.getPassword()).allowSelfSignedCerts(forwarderParameters.isAllowSelfSignedCerts())
 
 166         return HttpClientFactoryInstance.getClientFactory().build(params);