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;
 
  26 import java.util.ArrayList;
 
  27 import java.util.Arrays;
 
  28 import java.util.Collection;
 
  29 import java.util.List;
 
  32 import javax.ws.rs.client.Entity;
 
  33 import javax.ws.rs.core.HttpHeaders;
 
  34 import javax.ws.rs.core.MediaType;
 
  35 import javax.ws.rs.core.Response;
 
  36 import javax.ws.rs.core.Response.Status;
 
  38 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
 
  39 import org.onap.policy.common.endpoints.http.client.HttpClient;
 
  40 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
 
  41 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
 
  42 import org.onap.policy.common.gson.GsonMessageBodyHandler;
 
  43 import org.onap.policy.common.parameters.ParameterService;
 
  44 import org.onap.policy.distribution.forwarding.PolicyForwarder;
 
  45 import org.onap.policy.distribution.forwarding.PolicyForwardingException;
 
  46 import org.onap.policy.models.pap.concepts.PdpDeployPolicies;
 
  47 import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity;
 
  48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
 
  49 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion;
 
  50 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
 
  51 import org.slf4j.Logger;
 
  52 import org.slf4j.LoggerFactory;
 
  55  * This class provides an implementation of {@link PolicyForwarder} interface for forwarding the given policies & policy
 
  56  * types to the life cycle api's of policy framework.
 
  58  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
 
  60 public class LifecycleApiPolicyForwarder implements PolicyForwarder {
 
  62     private static final String DEPLOY_POLICY_URI = "/policy/pap/v1/pdps/policies";
 
  63     private static final String CREATE_POLICY_TYPE_URI = "/policy/api/v1/policytypes/";
 
  64     private static final Logger LOGGER = LoggerFactory.getLogger(LifecycleApiPolicyForwarder.class);
 
  65     private LifecycleApiForwarderParameters forwarderParameters;
 
  71     public void configure(final String parameterGroupName) {
 
  72         forwarderParameters = ParameterService.get(parameterGroupName);
 
  79     public void forward(final Collection<ToscaEntity> entities) throws PolicyForwardingException {
 
  80         final List<ToscaEntity> failedEntities = new ArrayList<>();
 
  81         for (final ToscaEntity entity : entities) {
 
  82             forwardSingleEntity(failedEntities, entity);
 
  84         if (!failedEntities.isEmpty()) {
 
  85             throw new PolicyForwardingException(
 
  86                     "Failed forwarding the following entities: " + Arrays.toString(failedEntities.toArray()));
 
  90     private void forwardSingleEntity(final List<ToscaEntity> failedEntities, final ToscaEntity entity) {
 
  91         Response policyCreated = null;
 
  93             if (entity instanceof ToscaServiceTemplate) {
 
  94                 final ToscaServiceTemplate toscaServiceTemplate = (ToscaServiceTemplate) entity;
 
  95                 if (null != toscaServiceTemplate.getPolicyTypes() && !toscaServiceTemplate.getPolicyTypes().isEmpty()) {
 
  96                     createPolicyType(toscaServiceTemplate);
 
  98                 if (null != toscaServiceTemplate.getToscaTopologyTemplate()
 
  99                         && null != toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()
 
 100                         && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().isEmpty()
 
 101                         && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet().isEmpty()) {
 
 102                     policyCreated = createPolicy(toscaServiceTemplate);
 
 104                 if (forwarderParameters.isDeployPolicies() && policyCreated != null) {
 
 105                     deployPolicy(policyCreated.readEntity(ToscaServiceTemplate.class));
 
 108                 throw new PolicyForwardingException("The entity is not of type ToscaServiceTemplate - " + entity);
 
 110         } catch (final Exception exp) {
 
 111             LOGGER.error(exp.getMessage(), exp);
 
 112             failedEntities.add(entity);
 
 116     private Response createPolicyType(final ToscaServiceTemplate toscaServiceTemplate)
 
 117             throws PolicyForwardingException {
 
 118         return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON), CREATE_POLICY_TYPE_URI,
 
 122     private Response createPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
 
 123         final ToscaPolicy policy = toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet()
 
 124                 .iterator().next().getValue();
 
 125         return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON),
 
 126                 CREATE_POLICY_TYPE_URI + policy.getType() + "/versions/" + policy.getTypeVersion() + "/policies", true);
 
 129     private Response deployPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
 
 130         final PdpDeployPolicies pdpPolicies = new PdpDeployPolicies();
 
 131         final List<ToscaPolicyIdentifierOptVersion> policyIdentifierList = new ArrayList<>();
 
 132         for (final Map<String, ToscaPolicy> policyMap : toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()) {
 
 133             final String policyId = policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-id");
 
 134             final String policyVersion =
 
 135                     policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-version");
 
 136             final ToscaPolicyIdentifierOptVersion toscaPolicyIdentifier =
 
 137                     new ToscaPolicyIdentifierOptVersion(policyId, policyVersion);
 
 138             policyIdentifierList.add(toscaPolicyIdentifier);
 
 140         pdpPolicies.setPolicies(policyIdentifierList);
 
 141         return invokeHttpClient(Entity.entity(pdpPolicies, MediaType.APPLICATION_JSON), DEPLOY_POLICY_URI, false);
 
 144     private Response invokeHttpClient(final Entity<?> entity, final String path, final boolean wantApi)
 
 145             throws PolicyForwardingException {
 
 146         Response response = null;
 
 148             response = getHttpClient(wantApi).post(path, entity, ImmutableMap.of(HttpHeaders.ACCEPT,
 
 149                     MediaType.APPLICATION_JSON, HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
 
 150             if (response.getStatus() != Status.OK.getStatusCode()) {
 
 152                         "Invocation of path {} failed for entity {}. Response status: {}, Response status info: {}",
 
 153                         path, entity, response.getStatus(), response.getStatusInfo());
 
 154                 throw new PolicyForwardingException("Failed creating the entity - " + entity);
 
 156         } catch (final HttpClientConfigException exception) {
 
 157             throw new PolicyForwardingException("Invocation of path " + path + " failed for entity  " + entity,
 
 163     private HttpClient getHttpClient(final boolean wantApi) throws HttpClientConfigException {
 
 164         final boolean https = forwarderParameters.isHttps();
 
 165         final LifecycleApiParameters parameters =
 
 166                 (wantApi ? forwarderParameters.getApiParameters() : forwarderParameters.getPapParameters());
 
 167         final BusTopicParams params = BusTopicParams.builder().clientName("Policy Distribution").useHttps(https)
 
 168                 .hostname(parameters.getHostName()).port(parameters.getPort()).userName(parameters.getUserName())
 
 169                 .password(parameters.getPassword()).serializationProvider(GsonMessageBodyHandler.class.getName())
 
 171         return HttpClientFactoryInstance.getClientFactory().build(params);