e0779ba00e20984330584900524736c046b4b504
[policy/drools-pdp.git] / feature-test-transaction / src / test / java / org / onap / policy / drools / testtransaction / TestTransactionTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * feature-test-transaction
4  * ================================================================================
5  * Copyright (C) 2017-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.testtransaction;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25
26 import java.io.IOException;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.Properties;
31 import java.util.Set;
32 import java.util.concurrent.CountDownLatch;
33 import java.util.concurrent.TimeUnit;
34 import org.junit.BeforeClass;
35 import org.junit.Test;
36 import org.onap.policy.drools.persistence.SystemPersistence;
37 import org.onap.policy.drools.properties.DroolsProperties;
38 import org.onap.policy.drools.system.PolicyController;
39 import org.onap.policy.drools.system.PolicyEngine;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public class TestTransactionTest {
44     /** Test JUnit Controller Name. */
45     public static final String TEST_CONTROLLER_NAME = "unnamed";
46     /** Controller Configuration File. */
47     public static final String TEST_CONTROLLER_FILE = TEST_CONTROLLER_NAME + "-controller.properties";
48
49     /** Controller Configuration Backup File. */
50     public static final String TEST_CONTROLLER_FILE_BAK =
51             TEST_CONTROLLER_NAME + "-controller.properties.bak";
52
53     /** logger. */
54     private static Logger logger = LoggerFactory.getLogger(TestTransactionTest.class);
55
56     /**
57      * Start up.
58      * 
59      * @throws IOException exception
60      */
61     @BeforeClass
62     public static void startUp() throws IOException {
63         logger.info("enter");
64
65         cleanUpWorkingDir();
66
67         /* ensure presence of config directory */
68         SystemPersistence.manager.setConfigurationDir(null);
69     }
70
71     @Test
72     public void registerUnregisterTest() throws InterruptedException {
73         final Properties controllerProperties = new Properties();
74         controllerProperties.put(DroolsProperties.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME);
75         final PolicyController controller =
76                 PolicyEngine.manager.createPolicyController(TEST_CONTROLLER_NAME, controllerProperties);
77         assertNotNull(PolicyController.factory.get(TEST_CONTROLLER_NAME));
78         logger.info(controller.toString());
79         
80         CountDownLatch latch = new CountDownLatch(1);
81         
82         // use our own impl so we can decrement the latch when run() completes
83         TtImpl impl = new TtImpl() {
84             @Override
85             protected TtControllerTask makeControllerTask(PolicyController controller) {
86                 return new TtControllerTask(controller) {
87                     @Override
88                     public void run() {
89                         super.run();
90                         latch.countDown();
91                     }
92                 };
93             }            
94         };
95
96         impl.register(controller);
97         assertNotNull(TestTransaction.manager);
98
99         /*
100          * Unregistering the controller should terminate its TestTransaction thread if it hasn't already
101          * been terminated
102          */
103         impl.unregister(controller);
104
105         Thread ttThread = getThread(latch, "tt-controller-task-" + TEST_CONTROLLER_NAME);
106         assertEquals(null, ttThread);
107     }
108
109     /**
110      * Returns thread object based on String name.
111      * @param latch indicates when the thread has finished running 
112      * @param threadName thread name
113      * @return the thread
114      * @throws InterruptedException exception
115      */
116     public Thread getThread(CountDownLatch latch, String threadName) throws InterruptedException {
117         // give a chance to the transaction thread to be spawned/destroyed
118         latch.await(5, TimeUnit.SECONDS);
119
120         final Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
121         for (final Thread thread : threadSet) {
122             if (thread.getName().equals(threadName)) {
123                 return thread;
124             }
125         }
126         return null;
127     }
128
129     /** clean up working directory. */
130     protected static void cleanUpWorkingDir() {
131         final Path testControllerPath =
132                 Paths.get(
133                         SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE);
134         try {
135             Files.deleteIfExists(testControllerPath);
136         } catch (final Exception e) {
137             logger.info("Problem cleaning {}", testControllerPath, e);
138         }
139
140         final Path testControllerBakPath =
141                 Paths.get(
142                         SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE_BAK);
143         try {
144             Files.deleteIfExists(testControllerBakPath);
145         } catch (final Exception e) {
146             logger.info("Problem cleaning {}", testControllerBakPath, e);
147         }
148     }
149 }