Add yaml support to xacml-pdp rest server
[policy/xacml-pdp.git] / applications / common / src / test / java / org / onap / policy / pdp / xacml / application / common / std / StdMatchableTranslatorTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pdp.xacml.application.common.std;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.mockito.Mockito.mock;
27 import static org.mockito.Mockito.when;
28
29 import java.io.IOException;
30 import java.util.Map;
31 import java.util.Properties;
32 import java.util.UUID;
33 import javax.ws.rs.Consumes;
34 import javax.ws.rs.GET;
35 import javax.ws.rs.HeaderParam;
36 import javax.ws.rs.Path;
37 import javax.ws.rs.PathParam;
38 import javax.ws.rs.Produces;
39 import javax.ws.rs.core.Response;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
41 import org.junit.AfterClass;
42 import org.junit.BeforeClass;
43 import org.junit.ClassRule;
44 import org.junit.Test;
45 import org.junit.rules.TemporaryFolder;
46 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
47 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
48 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
49 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
50 import org.onap.policy.common.gson.GsonMessageBodyHandler;
51 import org.onap.policy.common.utils.coder.CoderException;
52 import org.onap.policy.common.utils.coder.StandardYamlCoder;
53 import org.onap.policy.common.utils.network.NetworkUtil;
54 import org.onap.policy.common.utils.resources.ResourceUtils;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
56 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
57 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
58 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
59 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 public class StdMatchableTranslatorTest {
64
65     private static final Logger logger = LoggerFactory.getLogger(StdMatchableTranslatorTest.class);
66     private static final String CLIENT_NAME = "policy-api";
67     private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
68     private static int port;
69     private static RestServerParameters clientParams;
70     private static ToscaPolicyType testPolicyType;
71
72     @ClassRule
73     public static final TemporaryFolder policyFolder = new TemporaryFolder();
74
75     /**
76      * Initializes {@link #clientParams} and starts a simple REST server to handle the
77      * test requests.
78      *
79      * @throws IOException if an error occurs
80      */
81     @BeforeClass
82     public static void setUpBeforeClass() throws Exception {
83         System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
84         System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
85         //
86         // Setup our api server simulator
87         //
88         port = NetworkUtil.allocPort();
89
90         clientParams = mock(RestServerParameters.class);
91         when(clientParams.getHost()).thenReturn("localhost");
92         when(clientParams.getPort()).thenReturn(port);
93
94         Properties props = new Properties();
95         props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
96
97         final String svcpfx =
98                         PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
99
100         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHost());
101         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
102                         Integer.toString(clientParams.getPort()));
103         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
104                         ApiRestController.class.getName());
105         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
106         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
107         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, "false");
108         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
109                         GsonMessageBodyHandler.class.getName());
110
111         HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
112
113         assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHost(), clientParams.getPort(), 100, 100));
114         //
115         // Load our test policy type
116         //
117         String policyYaml = ResourceUtils.getResourceAsString("matchable/onap.policies.Test-1.0.0.yaml");
118         //
119         // Serialize it into a class
120         //
121         ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
122         //
123         // Make sure all the fields are setup properly
124         //
125         JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
126         jtst.fromAuthorative(serviceTemplate);
127         ToscaServiceTemplate completedJtst = jtst.toAuthorative();
128         //
129         // Find the Policy Type - SHOULD only be one
130         //
131         assertEquals(1, completedJtst.getPolicyTypes().size());
132         testPolicyType = completedJtst.getPolicyTypes().get("onap.policies.Test");
133         assertNotNull(testPolicyType);
134         logger.info("Test Policy Type {}{}", System.lineSeparator(), testPolicyType);
135     }
136
137     @AfterClass
138     public static void tearDownAfterClass() {
139         HttpServletServerFactoryInstance.getServerFactory().destroy();
140     }
141
142     @Test
143     public void test() throws CoderException, ToscaPolicyConversionException {
144         //
145         // Create our translator
146         //
147         StdMatchableTranslator translator = new StdMatchableTranslator();
148         assertNotNull(translator);
149         //
150         // Set it up
151         //
152         translator.setPathForData(policyFolder.getRoot().toPath());
153         translator.setApiRestParameters(clientParams);
154         //
155         // Load policies to test
156         //
157         String policyYaml = ResourceUtils.getResourceAsString(
158                 "src/test/resources/matchable/test.policies.input.tosca.yaml");
159         //
160         // Serialize it into a class
161         //
162         ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
163         //
164         // Make sure all the fields are setup properly
165         //
166         JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
167         jtst.fromAuthorative(serviceTemplate);
168         ToscaServiceTemplate completedJtst = jtst.toAuthorative();
169         //
170         // Get the policies
171         //
172         for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
173             for (ToscaPolicy policy : policies.values()) {
174                 PolicyType translatedPolicy = translator.convertPolicy(policy);
175                 assertNotNull(translatedPolicy);
176                 logger.info("Translated policy {} {}", System.lineSeparator(), translatedPolicy);
177             }
178         }
179     }
180
181     /**
182      * Simple REST server to handle test requests.
183      */
184
185     @Path("/policy/api/v1")
186     @Produces({"application/json", "application/yaml"})
187     @Consumes({"application/json", "application/yaml"})
188     public static class ApiRestController {
189
190         /**
191          * Retrieves the specified version of a particular policy type.
192          *
193          * @param policyTypeId ID of desired policy type
194          * @param versionId version of desired policy type
195          * @param requestId optional request ID
196          *
197          * @return the Response object containing the results of the API operation
198          */
199         @GET
200         @Path("/policytypes/{policyTypeId}/versions/{versionId}")
201         public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
202                         @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
203             logger.info("request for policy type={} version={}", policyTypeId, versionId);
204             return Response.status(Response.Status.OK).entity(testPolicyType).build();
205
206         }
207     }
208 }