Consolidate PolicyRestAdapter setup
[policy/engine.git] / POLICY-SDK-APP / src / test / java / org / onap / policy / controller / CreateOptimizationControllerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (C) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.controller;
24
25 import static org.easymock.EasyMock.createMock;
26 import static org.easymock.EasyMock.expect;
27 import static org.easymock.EasyMock.replay;
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertTrue;
30 import static org.junit.Assert.fail;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.when;
33
34 import com.fasterxml.jackson.databind.DeserializationFeature;
35 import com.fasterxml.jackson.databind.JsonNode;
36 import com.fasterxml.jackson.databind.ObjectMapper;
37 import com.github.fge.jackson.JsonLoader;
38
39 import java.io.BufferedReader;
40 import java.io.File;
41 import java.io.FileInputStream;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.StringReader;
45 import java.util.ArrayList;
46 import java.util.List;
47
48 import javax.servlet.ReadListener;
49 import javax.servlet.ServletInputStream;
50 import javax.servlet.http.HttpServletRequest;
51
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
59
60 import org.junit.Before;
61 import org.junit.Test;
62 import org.onap.policy.common.logging.flexlogger.FlexLogger;
63 import org.onap.policy.common.logging.flexlogger.Logger;
64 import org.onap.policy.rest.adapter.PolicyRestAdapter;
65 import org.onap.policy.rest.dao.CommonClassDao;
66 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
67 import org.onap.policy.rest.jpa.OptimizationModels;
68 import org.onap.policy.rest.jpa.PolicyEntity;
69 import org.springframework.mock.web.MockHttpServletResponse;
70
71 /**
72  * The class <code>CreateOptimizationControllerTest</code> contains tests for the class
73  *
74  * <p/>All JUnits are designed to run in the local development environment where they have write
75  * privileges and can execute time-sensitive tasks.
76  */
77 public class CreateOptimizationControllerTest {
78
79     private static Logger logger = FlexLogger.getLogger(CreateOptimizationControllerTest.class);
80     private static CommonClassDao commonClassDao;
81     private String jsonString = null;
82     private String configBodyString = null;
83     private HttpServletRequest request = null;
84
85     @Before
86     public void setUp() throws Exception {
87
88         logger.info("setUp: Entering");
89         commonClassDao = mock(CommonClassDao.class);
90         List<Object> optimizationModelsData = new ArrayList<Object>();
91         OptimizationModels testData = new OptimizationModels();
92         testData.setVersion("OpenOnap-Junit");
93         optimizationModelsData.add(testData);
94
95         // mock the getDataById() call
96         when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "test"))
97                 .thenReturn(optimizationModelsData);
98
99         jsonString = "{\"policyData\": {\"error\": \"\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
100                 + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,"
101                 + "\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\",\"createdBy\": \"someone\","
102                 + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false},"
103                 + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"},"
104                 + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"OOF\","
105                 + "\"policyName\": \"testPolicy\",\"policyDescription\": \"testing input\","
106                 + "\"onapName\": \"test\",\"guard\": \"False\",\"riskType\": \"Risk12345\","
107                 + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\","
108                 + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}},"
109                 + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}";
110
111         configBodyString = "{\"service\":\"PolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\","
112                 + "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\","
113                 + "\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\","
114                 + "\"retiredDate\":\"test\",\"scope\":\"TEST_PLACEMENT_VDHV\",\"name\":\"test\","
115                 + "\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\","
116                 + "\"target\":\"TEST\"}}";
117
118         request = mock(HttpServletRequest.class);
119         BufferedReader br = new BufferedReader(new StringReader(jsonString));
120         // mock the getReader() call
121         when(request.getReader()).thenReturn(br);
122
123         logger.info("setUp: exit");
124     }
125
126     /**
127      * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test.
128      */
129
130     @Test
131     public void testSetDataToPolicyRestAdapter() {
132
133         logger.debug("testSetDataToPolicyRestAdapter: enter");
134
135         CreateOptimizationController controller = new CreateOptimizationController();
136         CreateOptimizationController.setCommonClassDao(commonClassDao);
137
138         JsonNode root = null;
139         ObjectMapper mapper = new ObjectMapper();
140         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
141         PolicyRestAdapter policyData = null;
142         try {
143             root = JsonLoader.fromString(jsonString);
144             policyData = mapper.readValue(root.get("policyData").get("policy").toString(),
145                     PolicyRestAdapter.class);
146         } catch (Exception e) {
147             logger.error("testSetDataToPolicyRestAdapter", e);
148         }
149
150         PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root);
151         assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty());
152
153         logger.debug("result.getJsonBody() : " + result.getJsonBody());
154         logger.debug("testSetDataToPolicyRestAdapter: exit");
155     }
156
157     /**
158      * Run the ModelAndView getOptimizationTemplateData(HttpServletRequest, HttpServletResponse)
159      * method test.
160      */
161
162     @Test
163     public void testGetOptimizationTemplateData() {
164
165         logger.debug("testGetOptimizationTemplateData: enter");
166
167         CreateOptimizationController controller = new CreateOptimizationController();
168         MockHttpServletResponse response = new MockHttpServletResponse();
169         String modelJson = "{\"policyData\":\"testPolicyBody\"}";
170         try {
171
172             CreateOptimizationController.setCommonClassDao(commonClassDao);
173
174             BufferedReader br = new BufferedReader(new StringReader(modelJson));
175             // mock the getReader() call
176             when(request.getReader()).thenReturn(br);
177
178             List<Object> optimizationModelsData = new ArrayList<Object>();
179             OptimizationModels testData = new OptimizationModels();
180             testData.setVersion("1707.4.1.2-Junit");
181             optimizationModelsData.add(testData);
182             // mock the getDataById() call with the same MS model name
183             when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "testPolicyBody"))
184                     .thenReturn(optimizationModelsData);
185
186             controller.getOptimizationTemplateData(request, response);
187
188             assertTrue(response.getContentAsString() != null
189                     && response.getContentAsString().contains("optimizationModelData"));
190
191             logger.debug("response: " + response.getContentAsString());
192
193         } catch (Exception e) {
194             logger.error("testGetOptimizationTemplateData", e);
195         }
196
197         logger.debug("testGetOptimizationTemplateData: exit");
198     }
199
200     /**
201      * Run the ModelAndView getModelServiceVersionData(HttpServletRequest, HttpServletResponse)
202      * method test.
203      */
204
205     @Test
206     public void testGetModelServiceVersionData() {
207
208         logger.debug("testGetModelServiceVersionData: enter");
209
210         CreateOptimizationController controller = new CreateOptimizationController();
211         MockHttpServletResponse response = new MockHttpServletResponse();
212         String modelJson = "{\"policyData\":\"TestPolicyBody\"}";
213         try {
214
215             CreateOptimizationController.setCommonClassDao(commonClassDao);
216
217             BufferedReader br = new BufferedReader(new StringReader(modelJson));
218             // mock the getReader() call
219             when(request.getReader()).thenReturn(br);
220
221             List<Object> optimizationModelsData = new ArrayList<Object>();
222             OptimizationModels testData = new OptimizationModels();
223             testData.setVersion("1707.4.1.2-Junit");
224             optimizationModelsData.add(testData);
225
226             // mock the getDataById() call with the same MS model name
227             when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "TestPolicyBody"))
228                     .thenReturn(optimizationModelsData);
229             controller.getModelServiceVersionData(request, response);
230
231             assertTrue(response.getContentAsString() != null
232                     && response.getContentAsString().contains("1707.4.1.2-Junit"));
233
234             logger.debug("response: " + response.getContentAsString());
235
236         } catch (Exception e) {
237             logger.error("testGetModelServiceVersionData", e);
238             fail("testGetModelServiceVersionData failed due to: " + e);
239         }
240
241         logger.debug("testGetModelServiceVersionData: exit");
242     }
243
244     /**
245      * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test.
246      */
247
248     @Test
249     public void testPrePopulatePolicyData() {
250
251         logger.debug("testPrePopulatePolicyData: enter");
252
253         CreateOptimizationController controller = new CreateOptimizationController();
254
255         // populate an entity object for testing
256         PolicyEntity entity = new PolicyEntity();
257         ConfigurationDataEntity configData = new ConfigurationDataEntity();
258         configData.setConfigBody(configBodyString);
259         entity.setConfigurationData(configData);
260
261         JsonNode root = null;
262         ObjectMapper mapper = new ObjectMapper();
263         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
264         PolicyRestAdapter restAdapter = null;
265
266         try {
267             root = JsonLoader.fromString(jsonString);
268             restAdapter = mapper.readValue(root.get("policyData").get("policy").toString(),
269                     PolicyRestAdapter.class);
270             PolicyType policyType = new PolicyType();
271             TargetType target = new TargetType();
272
273             // create guard attribute
274             AnyOfType anyOfType = new AnyOfType();
275             AllOfType alltype = new AllOfType();
276             MatchType matchType = new MatchType();
277             // set value
278             AttributeValueType attributeValue1 = new AttributeValueType();
279             attributeValue1.getContent().add("True");
280             matchType.setAttributeValue(attributeValue1);
281             // set Id
282             AttributeDesignatorType designator = new AttributeDesignatorType();
283             designator.setAttributeId("guard");
284             matchType.setAttributeDesignator(designator);
285             alltype.getMatch().add(matchType);
286
287             // add a dummy MatchType object since while (matchList.size()>1 ...)
288             MatchType matchDummy = new MatchType();
289             // set value
290             AttributeValueType dummyValue = new AttributeValueType();
291             dummyValue.getContent().add("dummy");
292             matchDummy.setAttributeValue(dummyValue);
293             // set Id
294             AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
295             designatorDummy.setAttributeId("dummyId");
296             matchDummy.setAttributeDesignator(designatorDummy);
297
298             alltype.getMatch().add(matchDummy);
299             anyOfType.getAllOf().add(alltype);
300
301             target.getAnyOf().add(anyOfType);
302
303             // create RiskType attribute
304             AnyOfType anyRiskType = new AnyOfType();
305             AllOfType allRiskType = new AllOfType();
306             MatchType matchRiskType = new MatchType();
307             // set value
308             AttributeValueType riskTypeValue = new AttributeValueType();
309             riskTypeValue.getContent().add("test");
310             matchRiskType.setAttributeValue(riskTypeValue);
311             // set Id
312             AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
313             designatorRiskType.setAttributeId("RiskType");
314             matchRiskType.setAttributeDesignator(designatorRiskType);
315             allRiskType.getMatch().add(matchRiskType);
316
317             // add a dummy MatchType object since while (matchList.size()>1 ...)
318             MatchType matchDummy1 = new MatchType();
319             // set value
320             AttributeValueType dummy1Value = new AttributeValueType();
321             dummy1Value.getContent().add("dummy");
322             matchDummy1.setAttributeValue(dummy1Value);
323             // set Id
324             AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
325             designatorDummy1.setAttributeId("dummyId");
326             matchDummy1.setAttributeDesignator(designatorDummy1);
327
328             allRiskType.getMatch().add(matchDummy1);
329
330             anyRiskType.getAllOf().add(allRiskType);
331
332             target.getAnyOf().add(anyRiskType);
333
334             // create RiskLevel attribute
335             AnyOfType anyRiskLevel = new AnyOfType();
336             AllOfType allRiskLevel = new AllOfType();
337             MatchType matchRiskLevel = new MatchType();
338             // set value
339             AttributeValueType riskLevel = new AttributeValueType();
340             riskLevel.getContent().add("3");
341             matchRiskLevel.setAttributeValue(riskLevel);
342             // set Id
343             AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
344             designatorRiskLevel.setAttributeId("RiskLevel");
345             matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
346             allRiskLevel.getMatch().add(matchRiskLevel);
347
348             // add a dummy MatchType object since while (matchList.size()>1 ...)
349             MatchType matchDummy2 = new MatchType();
350             // set value
351             AttributeValueType dummy2Value = new AttributeValueType();
352             dummy2Value.getContent().add("dummy");
353             matchDummy2.setAttributeValue(dummy2Value);
354             // set Id
355             AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
356             designatorDummy2.setAttributeId("dummyId");
357             matchDummy2.setAttributeDesignator(designatorDummy2);
358
359             allRiskLevel.getMatch().add(matchDummy2);
360
361             anyRiskLevel.getAllOf().add(allRiskLevel);
362             target.getAnyOf().add(anyRiskLevel);
363
364             policyType.setTarget(target);
365
366             restAdapter.setPolicyData(policyType);
367
368             controller.prePopulatePolicyData(restAdapter, entity);
369
370             logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
371             logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
372             logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
373
374             assertEquals("True", restAdapter.getGuard());
375             assertEquals("3", restAdapter.getRiskLevel());
376             assertEquals("test", restAdapter.getRiskType());
377
378         } catch (Exception e) {
379             logger.error("testPrePopulatePolicyData", e);
380             fail("testPrePopulatePolicyData failed due to: " + e);
381         }
382
383         logger.debug("testPrePopulatePolicyData: exit");
384
385     }
386
387     /**
388      * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test.
389      */
390
391     @Test
392     public void testSetModelData() {
393
394         logger.debug("testSetModelData: enter");
395
396         CreateOptimizationController controller = new CreateOptimizationController();
397         HttpServletRequest request = createMock(HttpServletRequest.class);
398         MockHttpServletResponse response = new MockHttpServletResponse();
399         expect(request.getContentType())
400                 .andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p");
401         expect(request.getMethod()).andReturn("post");
402         expect(request.getHeader("Content-length")).andReturn("7809");
403
404         expect(request.getContentLength()).andReturn(7809);
405
406         try {
407             // value of fileName needs to be matched to your local directory
408             String fileName = "";
409             try {
410                 ClassLoader classLoader = getClass().getClassLoader();
411                 fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath();
412             } catch (Exception e1) {
413                 logger.error("Exception Occured while loading file" + e1);
414             }
415             expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));
416             expect(request.getCharacterEncoding()).andReturn("UTF-8");
417             expect(request.getContentLength()).andReturn(1024);
418             replay(request);
419             controller.setModelData(request, response);
420
421         } catch (Exception e) {
422             logger.error("testSetModelData" + e);
423             e.printStackTrace();
424         }
425
426         logger.debug("testSetModelData: exit");
427     }
428
429     /**
430      * @ Get File Stream.
431      */
432     private class MockServletInputStream extends ServletInputStream {
433
434         InputStream fis = null;
435
436         public MockServletInputStream(String fileName) {
437             try {
438                 fis = new FileInputStream(fileName);
439             } catch (Exception genExe) {
440                 genExe.printStackTrace();
441             }
442         }
443
444         @Override
445         public int read() throws IOException {
446             if (fis.available() > 0) {
447                 return fis.read();
448             }
449             return 0;
450         }
451
452         @Override
453         public int read(byte[] bytes, int len, int size) throws IOException {
454             if (fis.available() > 0) {
455                 int length = fis.read(bytes, len, size);
456                 return length;
457             }
458             return -1;
459         }
460
461         @Override
462         public boolean isFinished() {
463             return false;
464         }
465
466         @Override
467         public boolean isReady() {
468             return false;
469         }
470
471         @Override
472         public void setReadListener(ReadListener arg0) {
473
474         }
475     }
476 }