64661845b2ed5637cd5ecfeed4ac51080ecbc889
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.drools.protocol.coders;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import java.io.IOException;
26 import java.nio.file.Files;
27 import java.nio.file.Paths;
28 import java.util.List;
29 import java.util.Properties;
30 import org.junit.Assert;
31 import org.junit.Before;
32 import org.junit.Test;
33 import org.kie.api.builder.ReleaseId;
34 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
35 import org.onap.policy.common.endpoints.event.comm.TopicSink;
36 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
37 import org.onap.policy.drools.controller.DroolsController;
38 import org.onap.policy.drools.controller.internal.MavenDroolsControllerTest;
39 import org.onap.policy.drools.properties.DroolsProperties;
40 import org.onap.policy.drools.protocol.coders.EventProtocolCoder.CoderFilters;
41 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder;
42 import org.onap.policy.drools.util.KieUtils;
43 import org.onap.policy.drools.utils.Triple;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * ProtocolCoder Toolset JUNITs.
49  */
50 public class ProtocolCoderToolsetTest {
51     public static final String JUNIT_PROTOCOL_CODER_ARTIFACT_ID = "protocolcoder";
52     public static final String JUNIT_PROTOCOL_CODER_TOPIC = JUNIT_PROTOCOL_CODER_ARTIFACT_ID;
53     public static final String CONTROLLER_ID = "blah";
54     public static final String ARTIFACT_ID_ECHO = "echo";
55     public static final String ARTIFACT_ID_POM_LINE = "<artifactId>" + ARTIFACT_ID_ECHO + "</artifactId>";
56
57     private static Logger logger = LoggerFactory.getLogger(ProtocolCoderToolset.class);
58
59     private volatile ReleaseId releaseId;
60
61     public static final Gson customCoder = new GsonBuilder().create();
62
63     /**
64      * Setup.
65      *
66      * @throws IOException throws IO Exception
67      */
68     @Before
69     public void setUp() throws IOException {
70         if (releaseId != null) {
71             return;
72         }
73
74         String pom = new String(Files.readAllBytes(Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_POM_PATH)));
75
76         if (!pom.contains(ARTIFACT_ID_POM_LINE)) {
77             throw new IllegalArgumentException("unexpected junit test pom");
78         }
79
80         String newPom = pom.replace(ARTIFACT_ID_ECHO, JUNIT_PROTOCOL_CODER_ARTIFACT_ID);
81
82         String kmodule = new String(Files.readAllBytes(Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_PATH)));
83
84         String drl = new String(Files.readAllBytes(Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_DRL_PATH)));
85
86         releaseId = KieUtils.installArtifact(kmodule, newPom, MavenDroolsControllerTest.JUNIT_ECHO_KJAR_DRL_PATH, drl);
87     }
88
89     @Test
90     public void testToolsets() {
91         createController();
92         testGsonToolset(createFilterSet());
93     }
94
95     /**
96      * Test the Gson toolset.
97      *
98      * @param protocolFilter protocol filter
99      */
100     public void testGsonToolset(JsonProtocolFilter protocolFilter) {
101         GsonProtocolCoderToolset gsonToolset = new GsonProtocolCoderToolset(
102                 EventProtocolParams.builder().topic(JUNIT_PROTOCOL_CODER_TOPIC)
103                         .groupId(this.releaseId.getGroupId())
104                         .artifactId(this.releaseId.getArtifactId())
105                         .eventClass(Triple.class.getName())
106                         .protocolFilter(protocolFilter)
107                         .customGsonCoder(null)
108                         .modelClassLoaderHash(12345678), CONTROLLER_ID);
109
110         Assert.assertNotNull(gsonToolset.getEncoder());
111         Assert.assertNotNull(gsonToolset.getDecoder());
112
113         testToolset(protocolFilter, gsonToolset);
114
115         Triple<String, String, String> triple = createTriple();
116         gsonToolset.setCustomCoder(new CustomGsonCoder(this.getClass().getName(), "customCoder"));
117         String tripleEncoded = encode(gsonToolset, triple);
118         decode(protocolFilter, gsonToolset, triple, tripleEncoded);
119     }
120
121     private Triple<String, String, String> createTriple() {
122         return new Triple<>("v1", "v2", "v3");
123     }
124
125     private void testToolset(JsonProtocolFilter protocolFilter, ProtocolCoderToolset coderToolset) {
126
127         validateInitialization(protocolFilter, coderToolset);
128
129         updateCoderFilterRule(coderToolset);
130
131         addRemoveCoder(coderToolset);
132
133         /* restore original filters */
134         coderToolset.addCoder(Triple.class.getName(), protocolFilter, 654321);
135
136         Triple<String, String, String> triple = createTriple();
137
138         String tripleEncoded = encode(coderToolset, triple);
139
140         decode(protocolFilter, coderToolset, triple, tripleEncoded);
141     }
142
143     @SuppressWarnings("unchecked")
144     private void decode(JsonProtocolFilter protocolFilter, ProtocolCoderToolset coderToolset,
145             Triple<String, String, String> triple, String tripleEncoded) {
146
147         Triple<String, String, String> tripleDecoded = null;
148         try {
149             tripleDecoded = (Triple<String, String, String>) coderToolset.decode(tripleEncoded);
150         } catch (UnsupportedOperationException e) {
151             /* OK */
152             logger.trace("Junit expected exception - decode does not pass filtering", e);
153         }
154
155         CoderFilters coderFilters = coderToolset.getCoder(Triple.class.getName());
156         Assert.assertTrue(coderFilters.getCodedClass() == Triple.class.getName());
157         Assert.assertTrue(coderFilters.getFilter() == protocolFilter);
158         Assert.assertTrue(coderFilters.getFilter().getRule() != null);
159
160         coderFilters.getFilter().setRule("[?($.second =~ /^v2$/ && $.third =~ /.*v3.*/)]");
161
162         tripleDecoded = (Triple<String, String, String>) coderToolset.decode(tripleEncoded);
163
164         Assert.assertTrue(tripleDecoded.first().equals(triple.first()));
165         Assert.assertTrue(tripleDecoded.second().equals(triple.second()));
166         Assert.assertTrue(tripleDecoded.third().equals(triple.third()));
167
168         coderFilters.getFilter().setRule(null);
169         Assert.assertEquals("[?($ =~ /.*/)]", coderFilters.getFilter().getRule());
170
171         tripleDecoded = (Triple<String, String, String>) coderToolset.decode(tripleEncoded);
172
173         Assert.assertTrue(tripleDecoded.first().equals(triple.first()));
174         Assert.assertTrue(tripleDecoded.second().equals(triple.second()));
175         Assert.assertTrue(tripleDecoded.third().equals(triple.third()));
176
177         coderFilters.getFilter().setRule("[?($.third =~ /.*v3.*/)]");
178     }
179
180     private String encode(ProtocolCoderToolset coderToolset, Triple<String, String, String> triple) {
181         String tripleEncoded = coderToolset.encode(triple);
182         Assert.assertTrue(!tripleEncoded.isEmpty());
183         return tripleEncoded;
184     }
185
186     private void addRemoveCoder(ProtocolCoderToolset coderToolset) {
187         coderToolset.addCoder(this.getClass().getName(),
188                 new JsonProtocolFilter("[?($.second =~ /.*/)]"), 654321);
189         Assert.assertTrue(coderToolset.getCoders().size() == 2);
190
191         coderToolset.removeCoders(this.getClass().getName());
192         Assert.assertTrue(coderToolset.getCoders().size() == 1);
193     }
194
195     private void updateCoderFilterRule(ProtocolCoderToolset coderToolset) {
196         coderToolset.addCoder(Triple.class.getName(), new JsonProtocolFilter("[?($.third =~ /.*/)]"), 654321);
197
198         Assert.assertTrue(coderToolset.getCoders().size() == 1);
199
200         Assert.assertTrue(coderToolset.getCoder(Triple.class.getName()).getModelClassLoaderHash() == 654321);
201
202         Assert.assertTrue(
203                 coderToolset.getCoder(
204                         Triple.class.getName()).getFilter().getRule() != null);
205
206         Assert.assertTrue("[?($.third =~ /.*/)]".equals(coderToolset.getCoder(Triple.class.getName())
207                 .getFilter().getRule()));
208     }
209
210     private void validateInitialization(JsonProtocolFilter protocolFilter, ProtocolCoderToolset coderToolset) {
211         Assert.assertTrue(CONTROLLER_ID.equals(coderToolset.getControllerId()));
212         Assert.assertTrue(this.releaseId.getGroupId().equals(coderToolset.getGroupId()));
213         Assert.assertTrue(this.releaseId.getArtifactId().equals(coderToolset.getArtifactId()));
214         Assert.assertNull(coderToolset.getCustomCoder());
215
216         Assert.assertTrue(coderToolset.getCoders().size() == 1);
217
218         CoderFilters coderFilters = coderToolset.getCoder(CONTROLLER_ID);
219         Assert.assertTrue(coderFilters == null);
220
221         coderFilters = coderToolset.getCoder(Triple.class.getName());
222         Assert.assertNotNull(coderFilters);
223
224         Assert.assertEquals(coderFilters.getFilter(), protocolFilter);
225     }
226
227     private void createController() {
228         if (releaseId == null) {
229             throw new IllegalStateException("no prereq artifact installed in maven repository");
230         }
231
232         Properties sinkConfig = new Properties();
233         sinkConfig.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, JUNIT_PROTOCOL_CODER_TOPIC);
234         final List<? extends TopicSink> noopTopics = TopicEndpointManager.getManager().addTopicSinks(sinkConfig);
235
236         Properties droolsControllerConfig = new Properties();
237         droolsControllerConfig.put(DroolsProperties.RULES_GROUPID, releaseId.getGroupId());
238         droolsControllerConfig.put(DroolsProperties.RULES_ARTIFACTID, releaseId.getArtifactId());
239         droolsControllerConfig.put(DroolsProperties.RULES_VERSION, releaseId.getVersion());
240         droolsControllerConfig.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS + "." + JUNIT_PROTOCOL_CODER_TOPIC
241                 + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX, Triple.class.getName());
242
243         DroolsController.factory.build(droolsControllerConfig, null, noopTopics);
244     }
245
246     private JsonProtocolFilter createFilterSet() {
247         return new JsonProtocolFilter("[?($.first =~ /.*/ && $.second =~ /^blah.*/ && $.third =~ /^hello$/)]");
248     }
249 }