Merge "Adding Apex docs for Plugins module"
[policy/apex-pdp.git] / client / client-editor / src / test / java / org / onap / policy / apex / client / editor / rest / RestInterfaceTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.client.editor.rest;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26
27 import java.io.ByteArrayInputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30
31 import javax.ws.rs.client.Client;
32 import javax.ws.rs.client.ClientBuilder;
33 import javax.ws.rs.client.Entity;
34 import javax.ws.rs.client.Invocation.Builder;
35 import javax.ws.rs.client.WebTarget;
36 import javax.xml.bind.JAXBException;
37
38 import org.eclipse.persistence.jpa.jpql.Assert;
39 import org.junit.AfterClass;
40 import org.junit.BeforeClass;
41 import org.junit.Test;
42 import org.onap.policy.apex.client.editor.rest.ApexEditorMain.EditorState;
43 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
44 import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
45 import org.onap.policy.apex.model.basicmodel.handling.ApexModelStringWriter;
46 import org.onap.policy.apex.model.modelapi.ApexAPIResult;
47 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
48 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
49 import org.onap.policy.common.utils.resources.ResourceUtils;
50
51 /**
52  * The RestInterface Test.
53  */
54 public class RestInterfaceTest {
55     // CHECKSTYLE:OFF: MagicNumber
56
57     private static final String TESTMODELFILE = "models/SamplePolicyModelMVEL.json";
58     private static final String TESTPORTNUM = "18989";
59     private static final long MAX_WAIT = 15000; // 15 sec
60     private static final InputStream SYSIN = System.in;
61     private static final String[] EDITOR_MAIN_ARGS = new String[] { "-p", TESTPORTNUM };
62
63     private static ApexEditorMain editorMain;
64     private static WebTarget target;
65
66     private static AxPolicyModel localmodel = null;
67     private static String localmodelString = null;
68
69     /**
70      * Sets up the tests.
71      *
72      * @throws Exception if an error happens
73      */
74     @BeforeClass
75     public static void setUp() throws Exception {
76         // Start the editor
77         editorMain = new ApexEditorMain(EDITOR_MAIN_ARGS, System.out);
78         // prevent a stray stdin value from killing the editor
79         final ByteArrayInputStream input = new ByteArrayInputStream("".getBytes());
80         System.setIn(input);
81         // Init the editor in a separate thread
82         final Runnable testThread = new Runnable() {
83             @Override
84             public void run() {
85                 editorMain.init();
86             }
87         };
88         new Thread(testThread).start();
89         // wait until editorMain is in state RUNNING
90         final long startwait = System.currentTimeMillis();
91         while (editorMain.getState().equals(EditorState.STOPPED) || editorMain.getState().equals(EditorState.READY)
92                 || editorMain.getState().equals(EditorState.INITIALIZING)) {
93             if (editorMain.getState().equals(EditorState.STOPPED)) {
94                 Assert.fail("Rest endpoint (" + editorMain + ") shut down before it could be used");
95             }
96             if (System.currentTimeMillis() - startwait > MAX_WAIT) {
97                 Assert.fail("Rest endpoint (" + editorMain + ") for test failed to start fast enough");
98             }
99             Thread.sleep(100);
100         }
101
102         // create the client
103         final Client c = ClientBuilder.newClient();
104         // Create the web target
105         target = c.target(new ApexEditorParameters().getBaseURI());
106
107         // load a test model locally
108         localmodel = new ApexModelReader<>(AxPolicyModel.class, false)
109                 .read(ResourceUtils.getResourceAsStream(TESTMODELFILE));
110         localmodelString =
111                 new ApexModelStringWriter<AxPolicyModel>(false).writeJSONString(localmodel, AxPolicyModel.class);
112
113         // initialize a session ID
114         createNewSession();
115     }
116
117     /**
118      * Clean up streams.
119      *
120      * @throws IOException Signals that an I/O exception has occurred.
121      * @throws InterruptedException the interrupted exception
122      */
123     @AfterClass
124     public static void cleanUpStreams() throws IOException, InterruptedException {
125         editorMain.shutdown();
126         // wait until editorMain is in state STOPPED
127         final long startwait = System.currentTimeMillis();
128         while (!editorMain.getState().equals(EditorState.STOPPED)) {
129             if (System.currentTimeMillis() - startwait > MAX_WAIT) {
130                 Assert.fail("Rest endpoint (" + editorMain + ") for test failed to shutdown fast enough");
131             }
132             Thread.sleep(50);
133         }
134         System.setIn(SYSIN);
135     }
136
137     /**
138      * Test to see that the message create Model with model id -1 .
139      */
140     @Test
141     public void createSession() {
142         createNewSession();
143     }
144
145     /**
146      * Creates a new session.
147      *
148      * @return the session ID
149      */
150     private static int createNewSession() {
151         final ApexAPIResult responseMsg = target.path("editor/-1/Session/Create").request().get(ApexAPIResult.class);
152         assertEquals(responseMsg.getResult(), ApexAPIResult.RESULT.SUCCESS);
153         assertTrue(responseMsg.getMessages().size() == 1);
154         return Integer.parseInt(responseMsg.getMessages().get(0));
155     }
156
157     /**
158      * Upload policy.
159      *
160      * @param sessionID the session ID
161      * @param modelAsJsonString the model as json string
162      */
163     private void uploadPolicy(final int sessionID, final String modelAsJsonString) {
164         final Builder requestbuilder = target.path("editor/" + sessionID + "/Model/Load").request();
165         final ApexAPIResult responseMsg = requestbuilder.put(Entity.json(modelAsJsonString), ApexAPIResult.class);
166         assertTrue(responseMsg.isOK());
167     }
168
169     /**
170      * Create a new session, Upload a test policy model, then get a policy, parse it, and compare it to the same policy
171      * in the original model.
172      *
173      * @throws ApexException if there is an Apex Error
174      * @throws JAXBException if there is a JaxB Error
175      **/
176     @Test
177     public void testUploadThenGet() throws ApexException, JAXBException {
178
179         final int sessionID = createNewSession();
180
181         uploadPolicy(sessionID, localmodelString);
182
183         final ApexAPIResult responseMsg = target.path("editor/" + sessionID + "/Policy/Get")
184                 .queryParam("name", "Policy0").queryParam("version", "0.0.1").request().get(ApexAPIResult.class);
185         assertTrue(responseMsg.isOK());
186
187         // The string in responseMsg.Messages[0] is a JSON representation of a AxPolicy object. Lets parse it
188         final String returnedPolicyAsString = responseMsg.getMessages().get(0);
189         ApexModelReader<AxPolicy> apexPolicyReader = new ApexModelReader<>(AxPolicy.class, false);
190         final AxPolicy returnedpolicy = apexPolicyReader.read(returnedPolicyAsString);
191         // AxPolicy returnedpolicy = RestUtils.getConceptFromJSON(returnedPolicyAsString, AxPolicy.class);
192
193         // Extract the local copy of that policy from the local Apex Policy Model
194         final AxPolicy localpolicy = localmodel.getPolicies().get("Policy0", "0.0.1");
195
196         // Write that local copy of the AxPolicy object to a Json String, ten parse it again
197         final ApexModelStringWriter<AxPolicy> apexModelWriter = new ApexModelStringWriter<>(false);
198         final String localPolicyString = apexModelWriter.writeJSONString(localpolicy, AxPolicy.class);
199         apexPolicyReader = new ApexModelReader<>(AxPolicy.class, false);
200         final AxPolicy localpolicyReparsed = apexPolicyReader.read(localPolicyString);
201         // AxPolicy localpolicy_reparsed = RestUtils.getConceptFromJSON(returnedPolicyAsString, AxPolicy.class);
202
203         assertNotNull(returnedpolicy);
204         assertNotNull(localpolicy);
205         assertNotNull(localpolicyReparsed);
206         assertEquals(localpolicy, localpolicyReparsed);
207         assertEquals(localpolicy, returnedpolicy);
208     }
209
210     // TODO Full unit testing of REST interface
211
212 }