2bcb38feca5a5a196aa61c80df44341054a59816
[policy/apex-pdp.git] / testsuites / integration / integration-context-test / src / test / java / org / onap / policy / apex / testsuites / integration / context / locking / ConcurrentContext.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.testsuites.integration.context.locking;
23
24 import java.io.Closeable;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.TimeUnit;
33
34 import org.onap.policy.apex.context.ContextAlbum;
35 import org.onap.policy.apex.context.ContextException;
36 import org.onap.policy.apex.context.Distributor;
37 import org.onap.policy.apex.context.test.concepts.TestContextLongItem;
38 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
39 import org.onap.policy.apex.testsuites.integration.context.utils.ConfigrationProvider;
40 import org.slf4j.ext.XLogger;
41 import org.slf4j.ext.XLoggerFactory;
42
43 /**
44  * The Class TestConcurrentContext tests concurrent use of context.
45  *
46  * @author Liam Fallon (liam.fallon@ericsson.com)
47  */
48 public class ConcurrentContext {
49     // Logger for this class
50     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ConcurrentContext.class);
51
52     // The context distributor and map used by each test
53     private Distributor contextDistributor = null;
54     private ContextAlbum ltypeAlbum = null;
55
56     private final ConfigrationProvider configrationProvider;
57
58     public ConcurrentContext(final ConfigrationProvider configrationProvider) {
59         this.configrationProvider = configrationProvider;
60     }
61
62     /**
63      * The method tests concurrent use of context.
64      *
65      * @return the verified context
66      * @throws ApexException the Apex exception occurs in handling Apex
67      */
68     public Map<String, TestContextLongItem> testConcurrentContext() throws ApexException {
69
70         try {
71             setupAndVerifyContext();
72         } catch (final Exception exception) {
73             LOGGER.error("Error occured while setting up and verifying concurrent context", exception);
74             throw exception;
75         }
76
77         LOGGER.debug("starting JVMs and threads . . .");
78
79         final ExecutorService executorService = configrationProvider.getExecutorService();
80
81         final List<Closeable> tasks = new ArrayList<>(configrationProvider.getThreadCount());
82
83         addShutDownHook(tasks);
84
85         // Check if we have a single JVM or multiple JVMs
86         if (configrationProvider.getJvmCount() == 1) {
87             // Run everything in this JVM
88             for (int t = 0; t < configrationProvider.getThreadCount(); t++) {
89                 final ConcurrentContextThread task = new ConcurrentContextThread(0, t, configrationProvider);
90                 tasks.add(task);
91                 executorService.execute(task);
92             }
93
94         } else {
95             // Spawn JVMs to run the tests
96             for (int j = 0; j < configrationProvider.getJvmCount(); j++) {
97                 final ConcurrentContextJvmThread task = new ConcurrentContextJvmThread(j, configrationProvider);
98                 tasks.add(task);
99                 executorService.execute(task);
100             }
101         }
102
103         try {
104             executorService.shutdown();
105             // wait for threads to finish, if not Timeout
106             executorService.awaitTermination(10, TimeUnit.MINUTES);
107         } catch (final InterruptedException interruptedException) {
108             LOGGER.error("Exception while waiting for threads to finish", interruptedException);
109             // restore the interrupt status
110             Thread.currentThread().interrupt();
111         }
112
113         LOGGER.info("Shutting down now ...");
114         executorService.shutdownNow();
115
116         return verifyAndClearContext();
117     }
118
119
120     private void addShutDownHook(final List<Closeable> tasks) {
121         Runtime.getRuntime().addShutdownHook(new Thread() {
122             @Override
123             public void run() {
124                 LOGGER.info("Shutting down ...");
125                 for (final Closeable task : tasks) {
126                     try {
127                         task.close();
128                     } catch (final IOException ioException) {
129                         LOGGER.error("Unable to close task ... ", ioException);
130                     }
131                 }
132             }
133         });
134     }
135
136     /**
137      * Setup and verify context.
138      *
139      * @throws ContextException the context exception
140      */
141     private void setupAndVerifyContext() {
142         contextDistributor = configrationProvider.getDistributor();
143         ltypeAlbum = configrationProvider.getContextAlbum(contextDistributor);
144         final Map<String, Object> initValues = configrationProvider.getContextAlbumInitValues();
145
146         for (final Entry<String, Object> entry : initValues.entrySet()) {
147             ltypeAlbum.put(entry.getKey(), entry.getValue());
148         }
149     }
150
151     private Map<String, TestContextLongItem> verifyAndClearContext() throws ContextException {
152         final Map<String, TestContextLongItem> values = new HashMap<>();
153         try {
154
155             for (final Entry<String, Object> entry : ltypeAlbum.entrySet()) {
156                 values.put(entry.getKey(), (TestContextLongItem) entry.getValue());
157             }
158         } catch (final Exception exception) {
159             LOGGER.error("Error: ", exception);
160         }
161         contextDistributor.clear();
162         contextDistributor = null;
163
164         return values;
165     }
166 }