1 package org.onap.simulator.controller;
3 import static org.apache.commons.lang3.StringUtils.isEmpty;
4 import static org.mockserver.integration.ClientAndServer.startClientAndServer;
5 import static org.mockserver.matchers.Times.exactly;
6 import static org.mockserver.model.JsonBody.json;
8 import com.fasterxml.jackson.databind.DeserializationFeature;
9 import com.fasterxml.jackson.databind.ObjectMapper;
10 import com.google.common.collect.ImmutableMap;
11 import com.google.gson.Gson;
12 import java.io.BufferedInputStream;
13 import java.io.DataInputStream;
15 import java.io.FileInputStream;
16 import java.io.FileNotFoundException;
17 import java.io.IOException;
19 import java.net.URISyntaxException;
20 import java.net.URLEncoder;
21 import java.nio.file.Files;
22 import java.nio.file.Path;
23 import java.nio.file.Paths;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.Enumeration;
28 import java.util.List;
30 import java.util.Properties;
31 import java.util.Scanner;
32 import java.util.stream.Collectors;
33 import java.util.stream.Stream;
34 import javax.annotation.PostConstruct;
35 import javax.annotation.PreDestroy;
36 import javax.persistence.EntityManager;
37 import javax.persistence.EntityManagerFactory;
38 import javax.persistence.Persistence;
39 import javax.persistence.TypedQuery;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42 import org.mockserver.integration.ClientAndServer;
43 import org.mockserver.matchers.MatchType;
44 import org.mockserver.matchers.Times;
45 import org.mockserver.model.HttpRequest;
46 import org.mockserver.model.HttpResponse;
47 import org.mockserver.model.JsonBody;
48 import org.onap.simulator.db.entities.Function;
49 import org.onap.simulator.db.entities.User;
50 import org.onap.simulator.errorHandling.VidSimulatorException;
51 import org.onap.simulator.model.SimulatorRequestResponseExpectation;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.springframework.core.io.ClassPathResource;
55 import org.springframework.core.io.Resource;
56 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
57 import org.springframework.core.io.support.PropertiesLoaderUtils;
58 import org.springframework.core.io.support.ResourcePatternResolver;
59 import org.springframework.http.HttpEntity;
60 import org.springframework.http.HttpHeaders;
61 import org.springframework.http.HttpMethod;
62 import org.springframework.http.HttpStatus;
63 import org.springframework.http.ResponseEntity;
64 import org.springframework.stereotype.Component;
65 import org.springframework.web.bind.annotation.RequestBody;
66 import org.springframework.web.bind.annotation.RequestMapping;
67 import org.springframework.web.bind.annotation.RequestMethod;
68 import org.springframework.web.bind.annotation.ResponseBody;
69 import org.springframework.web.bind.annotation.ResponseStatus;
70 import org.springframework.web.bind.annotation.RestController;
71 import org.springframework.web.client.HttpClientErrorException;
72 import org.springframework.web.client.RestTemplate;
73 import org.springframework.web.servlet.View;
77 public class SimulatorController {
79 private static final Times DEFAULT_NUMBER_OF_TIMES = Times.unlimited();
80 private ClientAndServer mockServer;
81 private String mockServerProtocol;
82 private String mockServerHost;
83 private Integer mockServerPort;
84 private Boolean enablePresetRegistration;
85 private Boolean enableJPA;
86 private volatile boolean isInitialized = false;
88 private EntityManager entityManager;
89 private EntityManagerFactory entityManagerFactory;
92 private static final Logger logger = LoggerFactory.getLogger(SimulatorController.class);
96 logger.info("Starting VID Simulator....");
98 mockServer = startClientAndServer(mockServerPort);
102 } catch (RuntimeException e) {
103 isInitialized = false;
104 logger.error("Error during the JPA initialization:", e);
107 isInitialized = true;
108 logger.info("VID Simulator started successfully");
111 private void initJPA() {
113 entityManagerFactory = Persistence.createEntityManagerFactory("vid", overrideConnectionUrl());
114 entityManager = entityManagerFactory.createEntityManager();
118 private Map<Object, Object> overrideConnectionUrl() {
119 final String connectionUrlEnvProperty = "hibernate.connection.url";
120 if (isEmpty(System.getProperty(connectionUrlEnvProperty))) {
121 return Collections.emptyMap();
123 return ImmutableMap.of(connectionUrlEnvProperty, System.getProperty(connectionUrlEnvProperty));
128 public void tearDown(){
129 logger.info("Stopping VID Simulator....");
130 entityManager.close();
131 entityManagerFactory.close();
132 isInitialized = false;
133 mockServer.stop(false);
137 private void presetRegister() {
139 if (enablePresetRegistration == null || !enablePresetRegistration){
140 logger.info("Preset registration property is false or not set - skipping preset registration...");
143 ClassLoader cl = this.getClass().getClassLoader();
144 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
145 List<Path> resources = new ArrayList<>();
147 File presetDir = resolver.getResource("/preset_registration/").getFile();
148 if (presetDir.exists() && presetDir.isDirectory()) {
149 try (Stream<Path> files = Files.walk(Paths.get(presetDir.getPath()))) {
151 .filter(p -> p.toString().endsWith(".json"))
152 .collect(Collectors.toList());
155 logger.error("preset_registration directory is not exists");
157 } catch (IOException e) {
158 logger.error("Error performing preset registration, error: ", e);
161 logger.info("Starting preset registrations, number of requests: {}", resources.size());
162 for (Path resource: resources){
164 try (Scanner scanner = new Scanner(resource).useDelimiter("\\Z")){
165 content = scanner.next();
166 } catch (IOException e){
167 logger.error("Error reading preset registration file {}, skipping to next one. Error: ", resource.getFileName(), e);
170 //register the preset request
173 } catch (VidSimulatorException e) {
174 logger.error("Error proceeding preset registration file {},skipping to next one. Check if the JSON is in correct format. Error: ", resource.getFileName(), e);
181 private void setProperties() {
182 Resource resource = new ClassPathResource("simulator.properties");
183 Properties props = new Properties();
185 props = PropertiesLoaderUtils.loadProperties(resource);
186 } catch (IOException e) {
187 logger.error("Error loading simulator properties, error: ", e);
190 logger.info("Simulator properties are {}", props);
191 mockServerProtocol = (String)props.get("simulator.mockserver.protocol");
192 mockServerHost = (String)props.get("simulator.mockserver.host");
193 mockServerPort = Integer.parseInt((String)props.get("simulator.mockserver.port"));
194 enablePresetRegistration = Boolean.parseBoolean((String)props.get("simulator.enablePresetRegistration"));
195 enableJPA = Boolean.parseBoolean((String)props.get("simulator.enableCentralizedRoleAccess"));
198 @RequestMapping(value = {"/registerToVidSimulator"}, method = RequestMethod.POST)
200 ResponseEntity registerRequest(HttpServletRequest request, @RequestBody String expectation) {
202 register(expectation);
203 } catch (VidSimulatorException e) {
204 return new ResponseEntity<>("Registration failure! Error: "+e.getMessage(),HttpStatus.BAD_REQUEST);
206 return new ResponseEntity<>("Registration successful!",HttpStatus.OK);
209 @RequestMapping(value = {"/echo"}, method = RequestMethod.GET)
210 ResponseEntity echo(HttpServletRequest request) {
211 return isInitialized ? new ResponseEntity<>("",HttpStatus.OK) : new ResponseEntity<>("",HttpStatus.SERVICE_UNAVAILABLE);
214 @RequestMapping(value = {"/retrieveRecordedRequests"}, method = RequestMethod.GET)
215 public List<HttpRequest> retrieveRecordedRequests() {
216 return Arrays.asList(mockServer.retrieveRecordedRequests(null));
219 @RequestMapping(value = {"/registerToVidSimulator"}, method = RequestMethod.DELETE)
220 @ResponseStatus(value = HttpStatus.OK)
221 public void wipeOutAllExpectations() {
225 private void register(String expectation) throws VidSimulatorException{
226 ObjectMapper mapper = new ObjectMapper()
227 .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
229 SimulatorRequestResponseExpectation[] expectationModels;
231 expectationModels = mapper.readValue(expectation, SimulatorRequestResponseExpectation[].class);
232 } catch (IOException e) {
233 logger.error("Couldn't deserialize register expectation {}, error:", expectation, e);
234 throw new VidSimulatorException(e.getMessage());
237 for (SimulatorRequestResponseExpectation expectationModel : expectationModels) {
238 logger.info("Proceeding registration request: {}", expectationModel);
239 register(expectationModel);
243 //*******portal role access simulator (added by ag137v)
245 @RequestMapping(value = {"/ecompportal_att/auxapi//{ver}/user/*", "/ONAPPORTAL/auxapi//{ver}/user/*"}, method = RequestMethod.GET)
247 ResponseEntity auxapiGetUser(HttpServletRequest request) {
249 return new ResponseEntity<>("Centralized Role Access is disabled", HttpStatus.SERVICE_UNAVAILABLE);
251 entityManager.clear();
252 String reqUri = request.getRequestURI();
253 String userName = reqUri.substring(reqUri.lastIndexOf('/') + 1);
254 TypedQuery<User> userQuery = entityManager.createQuery("select u from fn_user u where u.loginId = :userName", User.class);
255 userQuery.setParameter("userName", userName);
256 User user = userQuery.getSingleResult();
259 String jsonString = g.toJson(user);
261 return new ResponseEntity<>(jsonString, HttpStatus.OK);
265 @RequestMapping(value = {"/ecompportal_att/auxapi//{ver}/functions", "/ONAPPORTAL/auxapi//{ver}/functions"}, method = RequestMethod.GET)
267 ResponseEntity auxapiGetFunctions(HttpServletRequest request) {
269 return new ResponseEntity<>("Centralized Role Access is disabled", HttpStatus.SERVICE_UNAVAILABLE);
271 TypedQuery<Function> userQuery = entityManager.createQuery("select f from fn_function f", Function.class);
272 List<Function> functions = userQuery.getResultList();
274 String jsonString = g.toJson(functions);
276 return new ResponseEntity<>(jsonString, HttpStatus.OK);
280 //*******portal role access simulator end
282 @RequestMapping(value = {"/ecompportal_att/auxapi//{ver}/getSessionSlotCheckInterval", "/ONAPPORTAL/auxapi//{ver}/getSessionSlotCheckInterval"}, method = RequestMethod.GET)
284 public String getSessionSlotCheckInterval() {
288 @RequestMapping(value = {"/**"})
289 public ResponseEntity redirectToMockServer(HttpServletRequest request, HttpServletResponse response) throws IOException {
290 //This is needed to allow POST redirect - see http://www.baeldung.com/spring-redirect-and-forward
291 request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
293 //Building the redirect URL
294 // String restOfTheUrl = (String) request.getAttribute(
295 // HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
296 String requestUri = URLEncoder.encode(request.getRequestURI(), "UTF-8");
297 requestUri = requestUri.replaceAll("%2F", "/");
298 String restOfTheUrl = requestUri.replaceFirst(request.getContextPath(), "");
300 StringBuilder sb = new StringBuilder();
301 sb.append(mockServerProtocol).append("://").append(mockServerHost).append(":").append(mockServerPort).append(restOfTheUrl);
302 String queryString = request.getQueryString();
303 if (queryString != null){
304 sb.append("?").append(queryString);
306 String redirectUrl = sb.toString();
307 logger.info("Redirecting the request to : {}", redirectUrl);
311 uri = new URI("http", null, "localhost", 1080, restOfTheUrl, request.getQueryString(), null);
312 } catch (URISyntaxException e) {
313 logger.error("Error during proxying request {}, error: ", request.getRequestURI(), e.getMessage());
314 return new ResponseEntity(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
316 RestTemplate restTemplate = new RestTemplate();
317 //Preparing the headers
318 HttpHeaders headers = new HttpHeaders();
319 Enumeration<String> headerNames = request.getHeaderNames();
320 while (headerNames.hasMoreElements()){
321 String headerToSet = headerNames.nextElement();
322 headers.set(headerToSet, request.getHeader(headerToSet));
324 HttpEntity<String> proxyRequest;
325 if ("POST".equalsIgnoreCase(request.getMethod()))
327 String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
328 proxyRequest = new HttpEntity<>(body, headers);
330 proxyRequest = new HttpEntity<>(headers);
333 ResponseEntity<String> responseEntity;
336 restTemplate.exchange(uri, HttpMethod.resolve(request.getMethod()), proxyRequest, String.class);
337 } catch (HttpClientErrorException exception) {
338 responseEntity = new ResponseEntity<>(exception.getResponseBodyAsString(), exception.getStatusCode());
341 return responseEntity;
344 private void register(SimulatorRequestResponseExpectation expectationModel) throws VidSimulatorException{
345 //Setting request according to what is passed
346 HttpRequest request = HttpRequest.request();
347 String id = expectationModel.getSimulatorRequest().getId();
349 request.withHeader("x-simulator-id", id);
352 if (expectationModel.getSimulatorRequest().getHeaders()!=null) {
353 expectationModel.getSimulatorRequest().getHeaders().forEach(
354 request::withHeader);
357 String method = expectationModel.getSimulatorRequest().getMethod();
358 if (method != null) {
359 request.withMethod(method);
361 String path = expectationModel.getSimulatorRequest().getPath();
363 request.withPath(path);
365 String body = expectationModel.getSimulatorRequest().getBody();
367 if (expectationModel.getSimulatorRequest().getStrict()) {
368 request.withBody(json(body, MatchType.STRICT));
370 request.withBody(new JsonBody(body));
375 final Map<String, List<String>> queryParams = expectationModel.getSimulatorRequest().getQueryParams();
376 if (queryParams != null){
377 String[] arr = new String[0];
378 queryParams.forEach((key, value) -> request.withQueryStringParameter(key, value.toArray(arr)));
381 //Setting response according to what is passed
382 HttpResponse response = HttpResponse.response();
383 Integer responseCode = expectationModel.getSimulatorResponse().getResponseCode();
384 if (responseCode != null) {
385 response.withStatusCode(responseCode);
387 logger.error("Invalid registration - response code cannot be empty");
388 throw new VidSimulatorException("Invalid registration - response code cannot be empty");
391 String respBody = expectationModel.getSimulatorResponse().getBody();
392 if (respBody != null) {
393 response.withBody(respBody);
396 String file = expectationModel.getSimulatorResponse().getFile();
398 response.withBody(loadFileString(file));
401 Map<String, String> responseHeaders = expectationModel.getSimulatorResponse().getResponseHeaders();
402 if (responseHeaders != null) {
403 responseHeaders.forEach(response::withHeader);
406 Times numberOfTimes = getExpectationNumberOfTimes(expectationModel);
408 if (expectationModel.getMisc().getReplace()) {
409 logger.info("Unregistering request expectation, if previously set, request: {}", expectationModel.getSimulatorRequest());
410 mockServer.clear(request);
414 .when(request, numberOfTimes).respond(response);
418 private byte[] loadFileString(String filePath) {
422 file = new ClassPathResource("download_files/" + filePath).getFile();
423 try(DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(file.getPath())))) {
424 bytes = new byte[(int)file.length()];
425 dataInputStream.readFully(bytes);
427 } catch (FileNotFoundException e) {
428 logger.error("File not found for file:" + filePath);
430 } catch (IOException e) {
431 logger.error("Error reading file:" + filePath);
437 private Times getExpectationNumberOfTimes(SimulatorRequestResponseExpectation expectationModel) {
438 Integer expectationModelNumberOfTimes = expectationModel.getMisc().getNumberOfTimes();
439 Times effectiveNumberOfTimes;
440 if (expectationModelNumberOfTimes == null || expectationModelNumberOfTimes < 0) {
441 effectiveNumberOfTimes = DEFAULT_NUMBER_OF_TIMES;
443 effectiveNumberOfTimes = exactly(expectationModelNumberOfTimes);
445 return effectiveNumberOfTimes;