2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controller;
24 import static org.easymock.EasyMock.createMock;
25 import static org.easymock.EasyMock.expect;
26 import static org.easymock.EasyMock.replay;
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertTrue;
29 import static org.junit.Assert.fail;
30 import static org.mockito.Mockito.mock;
31 import static org.mockito.Mockito.when;
33 import java.io.BufferedReader;
35 import java.io.FileInputStream;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.StringReader;
39 import java.util.ArrayList;
40 import java.util.List;
42 import javax.servlet.ReadListener;
43 import javax.servlet.ServletInputStream;
44 import javax.servlet.http.HttpServletRequest;
46 import org.junit.Before;
47 import org.junit.Test;
48 import org.onap.policy.common.logging.flexlogger.FlexLogger;
49 import org.onap.policy.common.logging.flexlogger.Logger;
50 import org.onap.policy.rest.adapter.PolicyRestAdapter;
51 import org.onap.policy.rest.dao.CommonClassDao;
52 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
53 import org.onap.policy.rest.jpa.OptimizationModels;
54 import org.onap.policy.rest.jpa.PolicyEntity;
55 import org.springframework.mock.web.MockHttpServletRequest;
56 import org.springframework.mock.web.MockHttpServletResponse;
58 import com.fasterxml.jackson.databind.DeserializationFeature;
59 import com.fasterxml.jackson.databind.JsonNode;
60 import com.fasterxml.jackson.databind.ObjectMapper;
61 import com.github.fge.jackson.JsonLoader;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
72 * The class <code>CreateOptimizationControllerTest</code> contains tests
73 * for the class {@link <code>CreateOptimizationController</code>}*
75 * All JUnits are designed to run in the local development environment
76 * where they have write privileges and can execute time-sensitive
79 public class CreateOptimizationControllerTest {
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;
88 public void setUp() throws Exception {
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);
97 // mock the getDataById() call
98 when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "test")).thenReturn(optimizationModelsData);
100 jsonString = "{\"policyData\": {\"error\": \"\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
101 + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
102 + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
103 + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
104 + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"OOF\",\"policyName\": \"testPolicy\", "
105 + " \"policyDescription\": \"testing input\", \"onapName\": \"test\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
106 + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
107 + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
109 configBodyString = "{\"service\":\"PolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\",\"templateVersion\":\"1607\",\"version\":\"HD\","
110 + "\"priority\":\"2\",\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\",\"retiredDate\":\"test\",\"scope\":\"TEST_PLACEMENT_VDHV\","
111 + "\"name\":\"test\",\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\",\"target\":\"TEST\"}}";
113 request = mock(HttpServletRequest.class);
114 BufferedReader br = new BufferedReader(new StringReader(jsonString));
115 // mock the getReader() call
116 when(request.getReader()).thenReturn(br);
118 logger.info("setUp: exit");
123 * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter,
124 * JsonNode) method test
128 public void testSetDataToPolicyRestAdapter() {
130 logger.debug("testSetDataToPolicyRestAdapter: enter");
132 CreateOptimizationController controller = new CreateOptimizationController();
133 CreateOptimizationController.setCommonClassDao(commonClassDao);
135 JsonNode root = null;
136 ObjectMapper mapper = new ObjectMapper();
137 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
138 PolicyRestAdapter policyData = null;
140 root = JsonLoader.fromString(jsonString);
141 policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
142 } catch (Exception e) {
143 logger.error("testSetDataToPolicyRestAdapter", e);
146 PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root);
147 assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty());
149 logger.debug("result.getJsonBody() : " + result.getJsonBody());
150 logger.debug("testSetDataToPolicyRestAdapter: exit");
155 * Run the ModelAndView getOptimizationTemplateData(HttpServletRequest,
156 * HttpServletResponse) method test
160 public void testGetOptimizationTemplateData() {
162 logger.debug("testGetOptimizationTemplateData: enter");
164 CreateOptimizationController controller = new CreateOptimizationController();
165 MockHttpServletResponse response = new MockHttpServletResponse();
166 String modelJson = "{\"policyData\":\"testPolicyBody\"}";
169 CreateOptimizationController.setCommonClassDao(commonClassDao);
171 BufferedReader br = new BufferedReader(new StringReader(modelJson));
172 // mock the getReader() call
173 when(request.getReader()).thenReturn(br);
175 List<Object> optimizationModelsData = new ArrayList<Object>();
176 OptimizationModels testData = new OptimizationModels();
177 testData.setVersion("1707.4.1.2-Junit");
178 optimizationModelsData.add(testData);
179 // mock the getDataById() call with the same MS model name
180 when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "testPolicyBody")).thenReturn(optimizationModelsData);
182 controller.getOptimizationTemplateData(request, response);
184 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("optimizationModelData"));
186 logger.debug("response: " + response.getContentAsString());
188 } catch (Exception e) {
189 logger.error("testGetOptimizationTemplateData", e);
192 logger.debug("testGetOptimizationTemplateData: exit");
196 * Run the ModelAndView getModelServiceVersionData(HttpServletRequest,
197 * HttpServletResponse) method test
201 public void testGetModelServiceVersionData() {
203 logger.debug("testGetModelServiceVersionData: enter");
205 CreateOptimizationController controller = new CreateOptimizationController();
206 MockHttpServletResponse response = new MockHttpServletResponse();
207 String modelJson = "{\"policyData\":\"TestPolicyBody\"}";
210 CreateOptimizationController.setCommonClassDao(commonClassDao);
212 BufferedReader br = new BufferedReader(new StringReader(modelJson));
213 // mock the getReader() call
214 when(request.getReader()).thenReturn(br);
216 List<Object> optimizationModelsData = new ArrayList<Object>();
217 OptimizationModels testData = new OptimizationModels();
218 testData.setVersion("1707.4.1.2-Junit");
219 optimizationModelsData.add(testData);
221 // mock the getDataById() call with the same MS model name
222 when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "TestPolicyBody")).thenReturn(optimizationModelsData);
223 controller.getModelServiceVersionData(request, response);
225 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("1707.4.1.2-Junit"));
227 logger.debug("response: " + response.getContentAsString());
229 } catch (Exception e) {
230 logger.error("testGetModelServiceVersionData", e);
231 fail("testGetModelServiceVersionData failed due to: " + e);
234 logger.debug("testGetModelServiceVersionData: exit");
238 * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter,
239 * PolicyEntity) method test
243 public void testPrePopulatePolicyData() {
245 logger.debug("testPrePopulatePolicyData: enter");
247 CreateOptimizationController controller = new CreateOptimizationController();
249 // populate an entity object for testing
250 PolicyEntity entity = new PolicyEntity();
251 ConfigurationDataEntity configData = new ConfigurationDataEntity();
252 configData.setConfigBody(configBodyString);
253 entity.setConfigurationData(configData);
255 JsonNode root = null;
256 ObjectMapper mapper = new ObjectMapper();
257 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
258 PolicyRestAdapter restAdapter = null;
261 root = JsonLoader.fromString(jsonString);
262 restAdapter = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
263 PolicyType policyType = new PolicyType();
264 TargetType target = new TargetType();
266 // create guard attribute
267 AnyOfType anyOfType = new AnyOfType();
268 AllOfType alltype = new AllOfType();
269 MatchType matchType = new MatchType();
271 AttributeValueType attributeValue1 = new AttributeValueType();
272 attributeValue1.getContent().add("True");
273 matchType.setAttributeValue(attributeValue1);
275 AttributeDesignatorType designator = new AttributeDesignatorType();
276 designator.setAttributeId("guard");
277 matchType.setAttributeDesignator(designator);
278 alltype.getMatch().add(matchType);
280 // add a dummy MatchType object since while (matchList.size()>1 ...)
281 MatchType matchDummy = new MatchType();
283 AttributeValueType dummyValue = new AttributeValueType();
284 dummyValue.getContent().add("dummy");
285 matchDummy.setAttributeValue(dummyValue);
287 AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
288 designatorDummy.setAttributeId("dummyId");
289 matchDummy.setAttributeDesignator(designatorDummy);
291 alltype.getMatch().add(matchDummy);
292 anyOfType.getAllOf().add(alltype);
294 target.getAnyOf().add(anyOfType);
296 // create RiskType attribute
297 AnyOfType anyRiskType = new AnyOfType();
298 AllOfType allRiskType = new AllOfType();
299 MatchType matchRiskType = new MatchType();
301 AttributeValueType riskTypeValue = new AttributeValueType();
302 riskTypeValue.getContent().add("test");
303 matchRiskType.setAttributeValue(riskTypeValue);
305 AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
306 designatorRiskType.setAttributeId("RiskType");
307 matchRiskType.setAttributeDesignator(designatorRiskType);
308 allRiskType.getMatch().add(matchRiskType);
310 // add a dummy MatchType object since while (matchList.size()>1 ...)
311 MatchType matchDummy1 = new MatchType();
313 AttributeValueType dummy1Value = new AttributeValueType();
314 dummy1Value.getContent().add("dummy");
315 matchDummy1.setAttributeValue(dummy1Value);
317 AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
318 designatorDummy1.setAttributeId("dummyId");
319 matchDummy1.setAttributeDesignator(designatorDummy1);
321 allRiskType.getMatch().add(matchDummy1);
323 anyRiskType.getAllOf().add(allRiskType);
325 target.getAnyOf().add(anyRiskType);
327 // create RiskLevel attribute
328 AnyOfType anyRiskLevel = new AnyOfType();
329 AllOfType allRiskLevel = new AllOfType();
330 MatchType matchRiskLevel = new MatchType();
332 AttributeValueType riskLevel = new AttributeValueType();
333 riskLevel.getContent().add("3");
334 matchRiskLevel.setAttributeValue(riskLevel);
336 AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
337 designatorRiskLevel.setAttributeId("RiskLevel");
338 matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
339 allRiskLevel.getMatch().add(matchRiskLevel);
341 // add a dummy MatchType object since while (matchList.size()>1 ...)
342 MatchType matchDummy2 = new MatchType();
344 AttributeValueType dummy2Value = new AttributeValueType();
345 dummy2Value.getContent().add("dummy");
346 matchDummy2.setAttributeValue(dummy2Value);
348 AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
349 designatorDummy2.setAttributeId("dummyId");
350 matchDummy2.setAttributeDesignator(designatorDummy2);
352 allRiskLevel.getMatch().add(matchDummy2);
354 anyRiskLevel.getAllOf().add(allRiskLevel);
355 target.getAnyOf().add(anyRiskLevel);
357 policyType.setTarget(target);
359 restAdapter.setPolicyData(policyType);
361 controller.prePopulatePolicyData(restAdapter, entity);
363 logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
364 logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
365 logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
367 assertEquals("True", restAdapter.getGuard());
368 assertEquals("3", restAdapter.getRiskLevel());
369 assertEquals("test", restAdapter.getRiskType());
371 } catch (Exception e) {
372 logger.error("testPrePopulatePolicyData", e);
373 fail("testPrePopulatePolicyData failed due to: " + e);
376 logger.debug("testPrePopulatePolicyData: exit");
381 * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse)
386 public void testSetModelData() {
388 logger.debug("testSetModelData: enter");
390 CreateOptimizationController controller = new CreateOptimizationController();
391 HttpServletRequest request = createMock(HttpServletRequest.class);
392 MockHttpServletResponse response = new MockHttpServletResponse();
393 expect(request.getContentType()).andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p");
394 expect(request.getMethod()).andReturn("post");
395 expect(request.getHeader("Content-length")).andReturn("7809");
397 expect(request.getContentLength()).andReturn(7809);
400 // value of fileName needs to be matched to your local directory
401 String fileName = "";
403 ClassLoader classLoader = getClass().getClassLoader();
404 fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath();
405 } catch (Exception e1) {
406 logger.error("Exception Occured while loading file"+e1);
408 expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));
409 expect(request.getCharacterEncoding()).andReturn("UTF-8");
410 expect(request.getContentLength()).andReturn(1024);
412 controller.setModelData(request, response);
414 } catch (Exception e) {
415 logger.error("testSetModelData" + e);
420 logger.debug("testSetModelData: exit");
428 private class MockServletInputStream extends ServletInputStream {
430 InputStream fis = null;
431 public MockServletInputStream(String fileName) {
433 fis = new FileInputStream(fileName);
434 } catch (Exception genExe) {
435 genExe.printStackTrace();
439 public int read() throws IOException {
440 if(fis.available() > 0) {
447 public int read(byte[] bytes, int len, int size) throws IOException {
448 if(fis.available() > 0) {
449 int length = fis.read(bytes, len, size);
455 public boolean isFinished() {
459 public boolean isReady() {
463 public void setReadListener(ReadListener arg0) {