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