1 package org.onap.vid.api;
3 import com.fasterxml.jackson.core.JsonProcessingException;
4 import com.google.common.primitives.Ints;
5 import org.apache.commons.io.IOUtils;
6 import org.apache.log4j.LogManager;
7 import org.apache.log4j.Logger;
8 import org.codehaus.jackson.map.ObjectMapper;
9 import org.codehaus.jackson.map.SerializationConfig;
10 import org.glassfish.jersey.client.ClientProperties;
11 import org.glassfish.jersey.uri.internal.JerseyUriBuilder;
12 import org.openecomp.sdc.ci.tests.datatypes.UserCredentials;
13 import org.springframework.http.HttpHeaders;
14 import org.springframework.http.MediaType;
15 import org.springframework.http.client.ClientHttpRequestInterceptor;
16 import org.springframework.http.client.ClientHttpResponse;
17 import org.springframework.web.client.DefaultResponseErrorHandler;
18 import org.springframework.web.client.RestTemplate;
19 import org.testng.annotations.AfterClass;
20 import org.testng.annotations.BeforeClass;
21 import vid.automation.test.infra.FeaturesTogglingConfiguration;
22 import vid.automation.test.services.UsersService;
23 import vid.automation.test.utils.CookieAndJsonHttpHeadersInterceptor;
25 import javax.ws.rs.client.Client;
26 import javax.ws.rs.client.ClientBuilder;
27 import java.io.IOException;
28 import java.io.InputStream;
31 import java.sql.Connection;
32 import java.sql.DriverManager;
33 import java.sql.SQLException;
34 import java.sql.Statement;
35 import java.util.List;
36 import java.util.Properties;
37 import java.util.Random;
39 import static java.util.Collections.singletonList;
40 import static org.apache.commons.text.StringEscapeUtils.unescapeJson;
41 import static org.hamcrest.CoreMatchers.everyItem;
42 import static org.hamcrest.MatcherAssert.assertThat;
43 import static org.hamcrest.Matchers.greaterThan;
45 public class BaseApiTest {
46 protected static final Logger LOGGER = LogManager.getLogger(BaseApiTest.class);
48 @SuppressWarnings("WeakerAccess")
50 @SuppressWarnings("WeakerAccess")
51 protected ObjectMapper objectMapper = new ObjectMapper();
52 @SuppressWarnings("WeakerAccess")
53 protected Client client;
54 protected Random random;
55 protected final RestTemplate restTemplate = new RestTemplate();
57 protected final UsersService usersService = new UsersService();
58 protected final RestTemplate restTemplateErrorAgnostic = new RestTemplate();
63 objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
64 client = ClientBuilder.newClient();
65 client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
66 random = new Random(System.currentTimeMillis());
67 FeaturesTogglingConfiguration.initializeFeatureManager();
70 private URI getUri() {
71 String host = System.getProperty("VID_HOST", "127.0.0.1");
72 Integer port = Integer.valueOf(System.getProperty("VID_PORT", "8080"));
73 return new JerseyUriBuilder().host(host).port(port).scheme("http").path("vid").build();
77 UserCredentials userCredentials = getUserCredentials();
78 final List<ClientHttpRequestInterceptor> interceptors = singletonList(new CookieAndJsonHttpHeadersInterceptor(getUri(), userCredentials));
79 restTemplate.setInterceptors(interceptors);
81 restTemplateErrorAgnostic.setInterceptors(interceptors);
82 restTemplateErrorAgnostic.setErrorHandler(new DefaultResponseErrorHandler() {
84 public boolean hasError(ClientHttpResponse response) {
91 static class DB_CONFIG {
92 static String url = String.format("jdbc:mariadb://%s:%d/vid_portal",
93 System.getProperty("DB_HOST", System.getProperty("VID_HOST", "127.0.0.1")),
94 Integer.valueOf(System.getProperty("DB_PORT", "3306"))
96 static String username = "euser";
97 static String password = "euser";
99 static final int userId = 2222;
100 static final String loginId = "vid1";
101 static final int roleId = 2222221;
102 static final int logRoleId = 2222222;
107 protected void createNewTestUser() {
111 LOGGER.debug("Connecting database...");
113 try (Connection connection = DriverManager.getConnection(DB_CONFIG.url, DB_CONFIG.username, DB_CONFIG.password)) {
115 LOGGER.debug("Database connected!");
116 //create new user with specific role
117 Statement stmt = connection.createStatement();
118 stmt.addBatch("INSERT INTO `fn_user` (`USER_ID`, `ORG_USER_ID`, `LOGIN_ID`, `LOGIN_PWD`) VALUES (" + DB_CONFIG.userId + ", 'Porfirio Gerhardt', '" + DB_CONFIG.loginId + "', '" + DB_CONFIG.loginId + "')");
119 stmt.addBatch("INSERT INTO `fn_role` (`ROLE_ID`, `ROLE_NAME`, `ACTIVE_YN`, `PRIORITY`) VALUES (" + DB_CONFIG.roleId + ", 'PACKET CORE___vFlowLogic', 'Y', 5)");
120 stmt.addBatch("INSERT INTO `fn_role` (`ROLE_ID`, `ROLE_NAME`, `ACTIVE_YN`, `PRIORITY`) VALUES (" + DB_CONFIG.logRoleId + ", 'READ___LOGS___PERMITTED', 'Y', 5)");
121 stmt.addBatch("INSERT INTO `fn_user_role` (`USER_ID`, `ROLE_ID`, `PRIORITY`, `APP_ID`) VALUES (" + DB_CONFIG.userId + ", " + DB_CONFIG.roleId + ", NULL, 1)");
122 stmt.addBatch("INSERT INTO `fn_user_role` (`USER_ID`, `ROLE_ID`, `PRIORITY`, `APP_ID`) VALUES (" + DB_CONFIG.userId + ", " + DB_CONFIG.logRoleId + ", NULL, 1)");
125 int[] executeBatch = stmt.executeBatch();
126 assertThat(Ints.asList(executeBatch), everyItem(greaterThan(0)));
128 } catch (SQLException e) {
129 throw new IllegalStateException("Cannot connect the database!", e);
135 protected void deleteNewTestUser() {
136 LOGGER.debug("Connecting database...");
138 try (Connection connection = DriverManager.getConnection(DB_CONFIG.url, DB_CONFIG.username, DB_CONFIG.password)) {
139 LOGGER.debug("Database connected!");
140 Statement stmt = connection.createStatement();
141 stmt.addBatch("DELETE FROM `fn_user_role` WHERE `USER_ID` = " + DB_CONFIG.userId);
142 stmt.addBatch("DELETE FROM `fn_user` WHERE `USER_ID` = " + DB_CONFIG.userId);
143 stmt.addBatch("DELETE FROM `fn_role` WHERE `ROLE_ID` = " + DB_CONFIG.roleId);
144 stmt.addBatch("DELETE FROM `fn_role` WHERE `ROLE_ID` = " + DB_CONFIG.logRoleId);
147 int[] executeBatch = stmt.executeBatch();
149 } catch (SQLException e) {
150 throw new IllegalStateException("Cannot connect the database!", e);
154 protected UserCredentials getUserCredentials() {
155 final Properties configProp = new Properties();
157 InputStream input = ClassLoader.getSystemResourceAsStream("test_config.properties");
158 configProp.load(input);
159 } catch (IOException e) {
160 throw new RuntimeException(e);
163 HttpHeaders loginRequestHeaders = new HttpHeaders();
164 loginRequestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
165 String loginId = configProp.getProperty("test.loginId", "i'm illegal");
166 String loginPassword = configProp.getProperty("test.loginPassword", "i'm illegal");
167 return new UserCredentials(loginId, loginPassword, null, null, null);
173 protected String getCleanJsonString(String jsonString) {
174 // remove leading/trailing double-quotes and unescape
175 String res = unescapeJson(jsonString.replaceAll("^\"|\"$", ""));
176 LOGGER.debug("getCleanJsonString: " + jsonString + " ==> " + res);
180 protected String getCleanJsonString(Object object) throws JsonProcessingException {
181 if (object instanceof String) {
182 return getCleanJsonString((String) object);
184 return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(object);
188 protected String buildUri(String path) {
189 return uri + "/" + path;
192 public static String getResourceAsString(String resourcePath) {
193 // load expected result
194 final URL resource = BaseApiTest.class.getClassLoader().getResource(resourcePath);
195 if (resource == null) throw new RuntimeException("resource file not found: " + resourcePath);
197 return IOUtils.toString(resource, "UTF-8");
198 } catch (IOException e) {
199 throw new RuntimeException(e);