3506dab9d741148b5e2f7f1f2d0af8d68341574a
[policy/gui.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020 Nordix Foundation.
5  *  Modifications Copyright (C) 2021 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  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.gui.editors.apex.rest;
24
25 import static org.awaitility.Awaitility.await;
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertTrue;
29
30 import java.io.ByteArrayInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.util.concurrent.TimeUnit;
34 import javax.ws.rs.client.Client;
35 import javax.ws.rs.client.ClientBuilder;
36 import javax.ws.rs.client.Entity;
37 import javax.ws.rs.client.Invocation.Builder;
38 import javax.ws.rs.client.WebTarget;
39 import javax.xml.bind.JAXBException;
40 import org.eclipse.persistence.jpa.jpql.Assert;
41 import org.junit.AfterClass;
42 import org.junit.BeforeClass;
43 import org.junit.Test;
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.modelapi.ApexApiResult;
47 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
48 import org.onap.policy.common.parameters.ParameterService;
49 import org.onap.policy.common.utils.resources.ResourceUtils;
50 import org.onap.policy.gui.editors.apex.rest.ApexEditorMain.EditorState;
51
52 /**
53  * The RestInterface Test.
54  */
55 public class RestInterfaceTest {
56     // CHECKSTYLE:OFF: MagicNumber
57
58     private static final String TESTMODELFILE = "models/PolicyModel.yaml";
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 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         ParameterService.clear();
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 var input = new ByteArrayInputStream("".getBytes());
81         System.setIn(input);
82         // Init the editor in a separate thread
83         final var 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         localModelString = ResourceUtils.getResourceAsString(TESTMODELFILE);
105
106         // initialize a session ID
107         createNewSession();
108     }
109
110     /**
111      * Clean up streams.
112      *
113      * @throws IOException          Signals that an I/O exception has occurred.
114      * @throws InterruptedException the interrupted exception
115      */
116     @AfterClass
117     public static void cleanUpStreams() throws IOException, InterruptedException {
118         editorMain.shutdown();
119         // wait until editorMain is in state STOPPED
120         await().atMost(MAX_WAIT, TimeUnit.MILLISECONDS).until(() -> editorMain.getState().equals(EditorState.STOPPED));
121         System.setIn(SYSIN);
122     }
123
124     /**
125      * Test to see that the message create Model with model id -1 .
126      */
127     @Test
128     public void createSession() {
129         createNewSession();
130     }
131
132     /**
133      * Creates a new session.
134      *
135      * @return the session ID
136      */
137     private static int createNewSession() {
138         final ApexApiResult responseMsg = target.path("editor/-1/Session/Create").request().get(ApexApiResult.class);
139         assertEquals(ApexApiResult.Result.SUCCESS, responseMsg.getResult());
140         assertEquals(1, responseMsg.getMessages().size());
141         return Integer.parseInt(responseMsg.getMessages().get(0));
142     }
143
144     /**
145      * Upload policy.
146      *
147      * @param sessionId         the session ID
148      * @param modelAsJsonString the model as json string
149      */
150     private void uploadPolicy(final int sessionId, final String modelAsJsonString) {
151         final Builder requestbuilder = target.path("editor/" + sessionId + "/Model/Load").request();
152         final ApexApiResult responseMsg = requestbuilder.put(Entity.json(modelAsJsonString), ApexApiResult.class);
153         assertTrue(responseMsg.isOk());
154     }
155
156     /**
157      * Create a new session, Upload a test policy model, then get a policy, parse it, and compare it to the same policy
158      * in the original model.
159      *
160      * @throws ApexException if there is an Apex Error
161      * @throws JAXBException if there is a JaxB Error
162      **/
163     @Test
164     public void testUploadThenGet() throws ApexException, JAXBException {
165
166         final int sessionId = createNewSession();
167
168         uploadPolicy(sessionId, localModelString);
169
170         final ApexApiResult responseMsg = target.path("editor/" + sessionId + "/Policy/Get")
171             .queryParam("name", "policy").queryParam("version", "0.0.1").request().get(ApexApiResult.class);
172         assertTrue(responseMsg.isOk());
173
174         // The string in responseMsg.Messages[0] is a JSON representation of a AxPolicy
175         // object. Lets parse it
176         final String returnedPolicyAsString = responseMsg.getMessages().get(0);
177         ApexModelReader<AxPolicy> apexPolicyReader = new ApexModelReader<>(AxPolicy.class, false);
178         final AxPolicy returnedPolicy = apexPolicyReader.read(returnedPolicyAsString);
179
180         assertNotNull(returnedPolicy);
181         assertEquals("state", returnedPolicy.getFirstState());
182         assertEquals(1, returnedPolicy.getStateMap().size());
183     }
184 }