package com.seec.bok.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Builder; import lombok.Data; import lombok.Setter; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpMethod; import org.springframework.web.client.HttpMessageConverterExtractor; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.RestTemplate; import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.Map; public class Request { public static int PORT; private static ObjectMapper mapper = new ObjectMapper(); @LocalServerPort public void setRandomServerPort(int randomServerPort) { PORT = randomServerPort; } private static RestTemplate RESTTEMPLATE = new RestTemplate();; @NotNull HttpMethod requestMethod; @NotNull String url; @NotNull String path; @Setter Object request; Map urlVariables; Object resDemo; public String getRequestJson() throws JsonProcessingException { return mapper.writeValueAsString(request); } public String getResDemoJson() throws JsonProcessingException { return mapper.writeValueAsString(resDemo); } public Request(@NotNull HttpMethod requestMethod, @NotNull String path) { this.requestMethod = requestMethod; this.url = "http://localhost:" + PORT +path; this.path=path; urlVariables=new HashMap<>(); } public Object put(String key, Object value) { return urlVariables.put(key, value); } public T execute(Class retType){ RequestCallback requestCallback; if(request==null){ requestCallback = RESTTEMPLATE.acceptHeaderRequestCallback(retType); }else { requestCallback = RESTTEMPLATE.httpEntityCallback(request, retType); } HttpMessageConverterExtractor responseExtractor = new HttpMessageConverterExtractor(retType, RESTTEMPLATE.getMessageConverters()); T ret= RESTTEMPLATE.execute(url,requestMethod,requestCallback,responseExtractor,urlVariables); resDemo=ret; return ret; } public String OutToString(String methodMessage) throws JsonProcessingException { return "\n### Request \n" +methodMessage+ "\n#### requestMethod \n" + requestMethod + "\n#### url \n" + url + "\n#### path \n" + path + "\n#### urlVariables \n" + mapper.writeValueAsString(urlVariables) + "\n#### reqBodyDemo \n``` json\n" + mapper.writeValueAsString(request) + "\n```" + "\n#### resBodyDemo \n``` json\n" + mapper.writeValueAsString(resDemo)+ "\n```"; } }