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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.pdp.xacml.application.common.std;
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;
29 import java.io.IOException;
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.StandardCoder;
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 import org.yaml.snakeyaml.Yaml;
64 public class StdMatchableTranslatorTest {
66 private static final Logger logger = LoggerFactory.getLogger(StdMatchableTranslatorTest.class);
67 private static final String CLIENT_NAME = "policy-api";
68 private static final StandardCoder standardCoder = new StandardCoder();
69 private static int port;
70 private static RestServerParameters clientParams;
71 private static ToscaPolicyType testPolicyType;
74 public static final TemporaryFolder policyFolder = new TemporaryFolder();
77 * Initializes {@link #clientParams} and starts a simple REST server to handle the
80 * @throws IOException if an error occurs
83 public static void setUpBeforeClass() throws Exception {
84 System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
85 System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
87 // Setup our api server simulator
89 port = NetworkUtil.allocPort();
91 clientParams = mock(RestServerParameters.class);
92 when(clientParams.getHost()).thenReturn("localhost");
93 when(clientParams.getPort()).thenReturn(port);
95 Properties props = new Properties();
96 props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
99 PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
101 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHost());
102 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
103 Integer.toString(clientParams.getPort()));
104 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
105 ApiRestController.class.getName());
106 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
107 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
108 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, "false");
109 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
110 GsonMessageBodyHandler.class.getName());
112 HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
114 assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHost(), clientParams.getPort(), 100, 100));
116 // Load our test policy type
118 String policyYaml = ResourceUtils.getResourceAsString("matchable/onap.policies.Test-1.0.0.yaml");
119 Yaml yaml = new Yaml();
120 Object yamlObject = yaml.load(policyYaml);
121 String yamlAsJsonString = standardCoder.encode(yamlObject);
123 // Serialize it into a class
125 ToscaServiceTemplate serviceTemplate = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
127 // Make sure all the fields are setup properly
129 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
130 jtst.fromAuthorative(serviceTemplate);
131 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
133 // Find the Policy Type - SHOULD only be one
135 assertEquals(1, completedJtst.getPolicyTypes().size());
136 testPolicyType = completedJtst.getPolicyTypes().get("onap.policies.Test");
137 assertNotNull(testPolicyType);
138 logger.info("Test Policy Type {}{}", System.lineSeparator(), testPolicyType);
142 public static void tearDownAfterClass() {
143 HttpServletServerFactoryInstance.getServerFactory().destroy();
147 public void test() throws CoderException, ToscaPolicyConversionException {
149 // Create our translator
151 StdMatchableTranslator translator = new StdMatchableTranslator();
152 assertNotNull(translator);
156 translator.setPathForData(policyFolder.getRoot().toPath());
157 translator.setApiRestParameters(clientParams);
159 // Load policies to test
161 String policyYaml = ResourceUtils.getResourceAsString(
162 "src/test/resources/matchable/test.policies.input.tosca.yaml");
163 Yaml yaml = new Yaml();
164 Object yamlObject = yaml.load(policyYaml);
165 String yamlAsJsonString = standardCoder.encode(yamlObject);
167 // Serialize it into a class
169 ToscaServiceTemplate serviceTemplate = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
171 // Make sure all the fields are setup properly
173 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
174 jtst.fromAuthorative(serviceTemplate);
175 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
179 for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
180 for (ToscaPolicy policy : policies.values()) {
181 PolicyType translatedPolicy = translator.convertPolicy(policy);
182 assertNotNull(translatedPolicy);
183 logger.info("Translated policy {} {}", System.lineSeparator(), translatedPolicy);
189 * Simple REST server to handle test requests.
192 @Path("/policy/api/v1")
193 @Produces({"application/json", "application/yaml"})
194 @Consumes({"application/json", "application/yaml"})
195 public static class ApiRestController {
198 * Retrieves the specified version of a particular policy type.
200 * @param policyTypeId ID of desired policy type
201 * @param versionId version of desired policy type
202 * @param requestId optional request ID
204 * @return the Response object containing the results of the API operation
207 @Path("/policytypes/{policyTypeId}/versions/{versionId}")
208 public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
209 @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
210 logger.info("request for policy type={} version={}", policyTypeId, versionId);
211 return Response.status(Response.Status.OK).entity(testPolicyType).build();