Changes for checkstyle 8.32
[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  *  Modifications Copyright (C) 2020 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.client.editor.rest;
23
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertTrue;
28
29 import java.io.ByteArrayInputStream;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.util.concurrent.TimeUnit;
33 import javax.ws.rs.client.Client;
34 import javax.ws.rs.client.ClientBuilder;
35 import javax.ws.rs.client.Entity;
36 import javax.ws.rs.client.Invocation.Builder;
37 import javax.ws.rs.client.WebTarget;
38 import javax.xml.bind.JAXBException;
39 import org.eclipse.persistence.jpa.jpql.Assert;
40 import org.junit.AfterClass;
41 import org.junit.BeforeClass;
42 import org.junit.Test;
43 import org.onap.policy.apex.client.editor.rest.ApexEditorMain.EditorState;
44 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
45 import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
46 import org.onap.policy.apex.model.basicmodel.handling.ApexModelStringWriter;
47 import org.onap.policy.apex.model.modelapi.ApexApiResult;
48 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
49 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
50 import org.onap.policy.common.utils.resources.ResourceUtils;
51
52 /**
53  * The RestInterface Test.
54  */
55 public class RestInterfaceTest {
56     // CHECKSTYLE:OFF: MagicNumber
57
58     private static final String TESTMODELFILE = "models/PolicyModel.json";
59     private static final String TESTPORTNUM = "18989";
60     private static final long MAX_WAIT = 15000; // 15 sec
61     private static final InputStream SYSIN = System.in;
62     private static final String[] EDITOR_MAIN_ARGS = new String[] { "-p", TESTPORTNUM };
63
64     private static ApexEditorMain editorMain;
65     private static WebTarget target;
66
67     private static AxPolicyModel localmodel = null;
68     private static String localmodelString = null;
69
70     /**
71      * Sets up the tests.
72      *
73      * @throws Exception if an error happens
74      */
75     @BeforeClass
76     public static void setUp() throws Exception {
77         // Start the editor
78         editorMain = new ApexEditorMain(EDITOR_MAIN_ARGS, System.out);
79         // prevent a stray stdin value from killing the editor
80         final ByteArrayInputStream input = new ByteArrayInputStream("".getBytes());
81         System.setIn(input);
82         // Init the editor in a separate thread
83         final Runnable testThread = new Runnable() {
84             @Override
85             public void run() {
86                 editorMain.init();
87             }
88         };
89         new Thread(testThread).start();
90         // wait until editorMain is in state RUNNING
91         await().atMost(MAX_WAIT, TimeUnit.MILLISECONDS).until(() -> !(editorMain.getState().equals(EditorState.READY)
92                 || editorMain.getState().equals(EditorState.INITIALIZING)));
93
94         if (editorMain.getState().equals(EditorState.STOPPED)) {
95             Assert.fail("Rest endpoint (" + editorMain + ") shut down before it could be used");
96         }
97
98         // create the client
99         final Client c = ClientBuilder.newClient();
100         // Create the web target
101         target = c.target(new ApexEditorParameters().getBaseUri());
102
103         // load a test model locally
104         localmodel = new ApexModelReader<>(AxPolicyModel.class, false)
105                 .read(ResourceUtils.getResourceAsStream(TESTMODELFILE));
106         localmodelString =
107                 new ApexModelStringWriter<AxPolicyModel>(false).writeJsonString(localmodel, AxPolicyModel.class);
108
109         // initialize a session ID
110         createNewSession();
111     }
112
113     /**
114      * Clean up streams.
115      *
116      * @throws IOException Signals that an I/O exception has occurred.
117      * @throws InterruptedException the interrupted exception
118      */
119     @AfterClass
120     public static void cleanUpStreams() throws IOException, InterruptedException {
121         editorMain.shutdown();
122         // wait until editorMain is in state STOPPED
123         await().atMost(MAX_WAIT, TimeUnit.MILLISECONDS).until(() -> editorMain.getState().equals(EditorState.STOPPED));
124         System.setIn(SYSIN);
125     }
126
127     /**
128      * Test to see that the message create Model with model id -1 .
129      */
130     @Test
131     public void createSession() {
132         createNewSession();
133     }
134
135     /**
136      * Creates a new session.
137      *
138      * @return the session ID
139      */
140     private static int createNewSession() {
141         final ApexApiResult responseMsg = target.path("editor/-1/Session/Create").request().get(ApexApiResult.class);
142         assertEquals(ApexApiResult.Result.SUCCESS, responseMsg.getResult());
143         assertTrue(responseMsg.getMessages().size() == 1);
144         return Integer.parseInt(responseMsg.getMessages().get(0));
145     }
146
147     /**
148      * Upload policy.
149      *
150      * @param sessionId the session ID
151      * @param modelAsJsonString the model as json string
152      */
153     private void uploadPolicy(final int sessionId, final String modelAsJsonString) {
154         final Builder requestbuilder = target.path("editor/" + sessionId + "/Model/Load").request();
155         final ApexApiResult responseMsg = requestbuilder.put(Entity.json(modelAsJsonString), ApexApiResult.class);
156         assertTrue(responseMsg.isOk());
157     }
158
159     /**
160      * Create a new session, Upload a test policy model, then get a policy, parse it, and compare it to the same policy
161      * in the original model.
162      *
163      * @throws ApexException if there is an Apex Error
164      * @throws JAXBException if there is a JaxB Error
165      **/
166     @Test
167     public void testUploadThenGet() throws ApexException, JAXBException {
168
169         final int sessionId = createNewSession();
170
171         uploadPolicy(sessionId, localmodelString);
172
173         final ApexApiResult responseMsg = target.path("editor/" + sessionId + "/Policy/Get")
174                 .queryParam("name", "policy").queryParam("version", "0.0.1").request().get(ApexApiResult.class);
175         assertTrue(responseMsg.isOk());
176
177         // The string in responseMsg.Messages[0] is a JSON representation of a AxPolicy object. Lets parse it
178         final String returnedPolicyAsString = responseMsg.getMessages().get(0);
179         ApexModelReader<AxPolicy> apexPolicyReader = new ApexModelReader<>(AxPolicy.class, false);
180         final AxPolicy returnedpolicy = apexPolicyReader.read(returnedPolicyAsString);
181         // AxPolicy returnedpolicy = RestUtils.getConceptFromJSON(returnedPolicyAsString, AxPolicy.class);
182
183         // Extract the local copy of that policy from the local Apex Policy Model
184         final AxPolicy localpolicy = localmodel.getPolicies().get("policy", "0.0.1");
185
186         // Write that local copy of the AxPolicy object to a Json String, ten parse it again
187         final ApexModelStringWriter<AxPolicy> apexModelWriter = new ApexModelStringWriter<>(false);
188         final String localPolicyString = apexModelWriter.writeJsonString(localpolicy, AxPolicy.class);
189         apexPolicyReader = new ApexModelReader<>(AxPolicy.class, false);
190         final AxPolicy localpolicyReparsed = apexPolicyReader.read(localPolicyString);
191         // AxPolicy localpolicy_reparsed = RestUtils.getConceptFromJSON(returnedPolicyAsString, AxPolicy.class);
192
193         assertNotNull(returnedpolicy);
194         assertNotNull(localpolicy);
195         assertNotNull(localpolicyReparsed);
196         assertEquals(localpolicy, localpolicyReparsed);
197         assertEquals(localpolicy, returnedpolicy);
198     }
199
200     // TODO Full unit testing of REST interface
201
202 }