cf1c4fa91899fb56a5b9da2491cdacc5d4051ea7
[policy/gui.git] /
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.gui.editors.apex.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.model.basicmodel.concepts.ApexException;
44 import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
45 import org.onap.policy.apex.model.modelapi.ApexApiResult;
46 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
47 import org.onap.policy.common.parameters.ParameterService;
48 import org.onap.policy.common.utils.resources.ResourceUtils;
49 import org.onap.policy.gui.editors.apex.rest.ApexEditorMain.EditorState;
50
51 /**
52  * The RestInterface Test.
53  */
54 public class RestInterfaceTest {
55     // CHECKSTYLE:OFF: MagicNumber
56
57     private static final String TESTMODELFILE = "models/PolicyModel.yaml";
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 String localModelString = null;
67
68     /**
69      * Sets up the tests.
70      *
71      * @throws Exception if an error happens
72      */
73     @BeforeClass
74     public static void setUp() throws Exception {
75         ParameterService.clear();
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         await().atMost(MAX_WAIT, TimeUnit.MILLISECONDS).until(() -> !(editorMain.getState().equals(EditorState.READY)
91             || editorMain.getState().equals(EditorState.INITIALIZING)));
92
93         if (editorMain.getState().equals(EditorState.STOPPED)) {
94             Assert.fail("Rest endpoint (" + editorMain + ") shut down before it could be used");
95         }
96
97         // create the client
98         final Client c = ClientBuilder.newClient();
99         // Create the web target
100         target = c.target(new ApexEditorParameters().getBaseUri());
101
102         // load a test model locally
103         localModelString = ResourceUtils.getResourceAsString(TESTMODELFILE);
104
105         // initialize a session ID
106         createNewSession();
107     }
108
109     /**
110      * Clean up streams.
111      *
112      * @throws IOException          Signals that an I/O exception has occurred.
113      * @throws InterruptedException the interrupted exception
114      */
115     @AfterClass
116     public static void cleanUpStreams() throws IOException, InterruptedException {
117         editorMain.shutdown();
118         // wait until editorMain is in state STOPPED
119         await().atMost(MAX_WAIT, TimeUnit.MILLISECONDS).until(() -> editorMain.getState().equals(EditorState.STOPPED));
120         System.setIn(SYSIN);
121     }
122
123     /**
124      * Test to see that the message create Model with model id -1 .
125      */
126     @Test
127     public void createSession() {
128         createNewSession();
129     }
130
131     /**
132      * Creates a new session.
133      *
134      * @return the session ID
135      */
136     private static int createNewSession() {
137         final ApexApiResult responseMsg = target.path("editor/-1/Session/Create").request().get(ApexApiResult.class);
138         assertEquals(ApexApiResult.Result.SUCCESS, responseMsg.getResult());
139         assertEquals(1, responseMsg.getMessages().size());
140         return Integer.parseInt(responseMsg.getMessages().get(0));
141     }
142
143     /**
144      * Upload policy.
145      *
146      * @param sessionId         the session ID
147      * @param modelAsJsonString the model as json string
148      */
149     private void uploadPolicy(final int sessionId, final String modelAsJsonString) {
150         final Builder requestbuilder = target.path("editor/" + sessionId + "/Model/Load").request();
151         final ApexApiResult responseMsg = requestbuilder.put(Entity.json(modelAsJsonString), ApexApiResult.class);
152         assertTrue(responseMsg.isOk());
153     }
154
155     /**
156      * Create a new session, Upload a test policy model, then get a policy, parse it, and compare it to the same policy
157      * in the original model.
158      *
159      * @throws ApexException if there is an Apex Error
160      * @throws JAXBException if there is a JaxB Error
161      **/
162     @Test
163     public void testUploadThenGet() throws ApexException, JAXBException {
164
165         final int sessionId = createNewSession();
166
167         uploadPolicy(sessionId, localModelString);
168
169         final ApexApiResult responseMsg = target.path("editor/" + sessionId + "/Policy/Get")
170             .queryParam("name", "policy").queryParam("version", "0.0.1").request().get(ApexApiResult.class);
171         assertTrue(responseMsg.isOk());
172
173         // The string in responseMsg.Messages[0] is a JSON representation of a AxPolicy
174         // object. Lets parse it
175         final String returnedPolicyAsString = responseMsg.getMessages().get(0);
176         ApexModelReader<AxPolicy> apexPolicyReader = new ApexModelReader<>(AxPolicy.class, false);
177         final AxPolicy returnedPolicy = apexPolicyReader.read(returnedPolicyAsString);
178
179         assertNotNull(returnedPolicy);
180         assertEquals("state", returnedPolicy.getFirstState());
181         assertEquals(1, returnedPolicy.getStateMap().size());
182     }
183 }