| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- 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<String,Object> 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> T execute(Class<T> retType){
- RequestCallback requestCallback;
- if(request==null){
- requestCallback = RESTTEMPLATE.acceptHeaderRequestCallback(retType);
- }else {
- requestCallback = RESTTEMPLATE.httpEntityCallback(request, retType);
- }
- HttpMessageConverterExtractor<T> responseExtractor =
- new HttpMessageConverterExtractor<T>(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```";
- }
- }
|