Skip to content

Instantly share code, notes, and snippets.

@HiroNakamura
Last active October 16, 2022 19:56
Show Gist options
  • Save HiroNakamura/7ae81c06c89793fdf9a28d5624d5a44a to your computer and use it in GitHub Desktop.
Save HiroNakamura/7ae81c06c89793fdf9a28d5624d5a44a to your computer and use it in GitHub Desktop.
Spring Boot - Ejemplos de RestTemplate

Spring Boot

Spring boot - Ejemplos de RestTemplate

Definiendo un @Bean de RestTemplate

@Bean
public RestTemplate restTemplate() {
   return new RestTemplate();
}

Usando HttpComponentsClientHttpRequestFactory, esto como una mejora del código de arriba.

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    restTemplate.setRequestFactory(requestFactory);
    return restTemplate;
}

Inyectando el @Bean, usualmente en el Controller.

@Autowire
private RestTemplate restTemplate;

Haciendo uso de restTemplate.

String objRecuperado = restTemplate.exchange("http://localhost:8080/users", HttpMethod.POST, httpEntity, String.class);

2. Consumir Servicio Spring Boot + JWT con JAVA. Ejemplo visto en http://jambrocio.blogspot.com/2019/09/consumir-servicio-spring-boot-jwt.html

Consumidor.java

package com.util;

import java.nio.charset.Charset;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class Consumidor {

 static final String URL_LOGIN = "http://192.168.20.64:8071/oauth/token";
 
 public static void main(String[] args) {
  
  String usernameHeader = "angularapp";
        String passwordHeader = "12345";
     
  String usernameBody = "42596272";
        String passwordBody = "12345";
     
        postLogin(usernameHeader, passwordHeader, usernameBody, passwordBody);

 }
 
 private static void postLogin(String usernameHeader, String passwordHeader, String usernameBody, String passwordBody) {
  
        // Request Header
        HttpHeaders headers = new HttpHeaders();
             
        headers = createHeaders(usernameHeader, passwordHeader);
     
        // Request Body
        MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
        body.add("username", usernameBody);
        body.add("password", passwordBody);
        body.add("grant_type", "password");

        // Request Entity
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);

        // RestTemplate
        RestTemplate restTemplate = new RestTemplate();

        // POST Login
        ResponseEntity<String> response = restTemplate.exchange(URL_LOGIN, HttpMethod.POST, requestEntity, String.class);

        HttpHeaders responseHeaders = response.getHeaders();
        String responseBody = response.getBody();
        String responseStatus = String.valueOf(response.getStatusCodeValue());

        System.out.println("Status : " + responseStatus);
        System.out.println("Body : " + responseBody);
     
    }
 
 private static HttpHeaders createHeaders(String username, String password){
     return new HttpHeaders() {{
           String auth = username + ":" + password;
           byte[] encodedAuth = Base64.encodeBase64(
              auth.getBytes(Charset.forName("US-ASCII")) );
           String authHeader = "Basic " + new String( encodedAuth );
           set( "Authorization", authHeader );
     }};
 }
 
}

The LaxRedirectStrategy allows us to redirect in case of HEAD, GET, POST, DELETE.

Método GET

RestTemplate restTemplate = new RestTemplate();
ResponseEntitymybean<MyBean>response = restTemplate.getForEntity("webservice endPoint url", MyBean.class);

Método POST.

final RestTemplate restTemplate = new RestTemplate();
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final HttpClient httpClient = HttpClientBuilder.create()
                                               .setRedirectStrategy(new LaxRedirectStrategy())
                                               .build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);

Map<String, String> params = new HashMap<String, String>();
params.put("email", "yourname@gmail.com");

ResponseEntity response = restTemplate.postForEntity(""webservice endPoint url"", params, String.class);

UserControllerTest

package main;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Collections;

import static org.hamcrest.Matchers.*;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;


@RunWith (SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration (classes = Config.class)
@WebAppConfiguration
@IntegrationTest
public class UserControllerTest
{
  final String BASE_URL = "http://localhost:9999/customer/";

  @Test
  public void shouldCreateNewUser() {

    final String USER_NAME = "Leif Ericson";
    final String USER_ADDRESS = "Vinland";

    User user = new User();
    user.setName(USER_NAME);
    user.setAddress(USER_ADDRESS);

    RestTemplate rest = new TestRestTemplate();

    ResponseEntity<User> response = 
       rest.postForEntity(BASE_URL, user, User.class, Collections.EMPTY_MAP);
    assertThat( response.getStatusCode() , equalTo(HttpStatus.CREATED));

    User userCreated = response.getBody();
    assertThat( userCreated.getId() , notNullValue() );
    assertThat( userCreated.getName() , equalTo(CUSTOMER_NAME) );
    assertThat( userCreated.getAddress() , equalTo(CUSTOMER_ADDRESS) );
  }

  @Test
  public void shouldFailToGetUnknownUser()
  throws IOException {

    final int UNKNOWN_ID = Integer.MAX_VALUE;
    final String EXPECTED_ANSWER_MESSAGE = "user with id : '" + UNKNOWN_ID+ "' does not exist";

    RestTemplate rest = new TestRestTemplate();

    ResponseEntity<String> response = rest.getForEntity(BASE_URL + UNKNOWN_ID, String.class);

    assertThat( response.getStatusCode() , equalTo(HttpStatus.NOT_FOUND));

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode responseJson = objectMapper.readTree(response.getBody());
    JsonNode messageJson = responseJson.path("message");

    assertThat( messageJson.isMissingNode() , is(false) );
    assertThat( messageJson.asText() , equalTo(EXPECTED_ANSWER_MESSAGE) );
  }
}

Usando GET

String pong = new RestTemplate().getForObject(address + PING, String.class);
Validate.isTrue(PONG.equals(pong));

Usando POST

HttpHeaders  headers = new HttpHeaders();
 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
 HttpEntity req = new HttpEntity<>(urlEncodeYourParams(), headers);
 RestTemplate rest = new RestTemplate();
 ResponseEntity result = rest.postForEntity(address, req, String.class);
 System.out.println( result.getBody() );
private RestTemplateHelper restTemplateHelper;

// other codes...

// find by id
UserDto userDto = restTemplateHelper.getForEntity(UserDto.class, "http://localhost:8080/users/{id}", id);

// find all
UserDto userDto = restTemplateHelper.getForList(UserDto.class, "http://localhost:8080/users");

// save
UserDto userDto = restTemplateHelper.postForEntity(UserDto.class, "http://localhost:8080/users", userDto);
                                                   
// update
UserDto userDto = restTemplateHelper.putForEntity(UserDto.class, "http://localhost:8080/users/{id}", userDto, id);

// delete
restTemplateHelper.delete("http://localhost:8080/users/{id}", id);
@RestResource(urlMapping = '/Account/*')  
 global with sharing class MyRestResource {  
   @HttpGet  
   global static List<Account> getAccounts() {  
     List<Account> result = [SELECT Id, Name, Phone, Website FROM Account LIMIT 2];  
     return result;  
   }  
 }  

Student.java

package com.school.model;

public class Student {

    private String firstName;
    private String lastName;
    private int age;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

StudentRepository.java

import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository < Student, Integer > {

    Student findById(int id);

}

IStudentService.java

import java.util.List;

public interface IStudentService {
    Student saveStudent(Student student);
    Student getStudentById(Integer id);
}

StudentServiceImpl.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class StudentServiceImpl implements IStudentService {

    @Autowired
    StudentRepository studentRepository;

    //add a new student to h2 database
    @Override
    public String saveStudent(Cards card) {
        try {
            studentRepository.save(card);
            return "Saved to database successfully !";
        } catch (Exception e) {
            e.printStackTrace();
            return "Error in saving the value";
        }
    }

    //get the specific student from the h2 database
    @Override
    public Student getStudentById(String cardNumber) {
        return studentRepository.findById(cardNumber);
    }
}

StudentController.java

@Controller
public class StudentController {

    @Autowired
    StudentServiceImpl studentService;

    @PostMapping(
        value = "/addstudent", consumes = "application/json", produces = "application/json")
    public Person createPerson(@RequestBody Student student) {
        return studentService.saveStudent(student);
    }

    @PostMapping(
        value = "/updatestudent", consumes = "application/json",
        produces = "application/json")
    public Student updateStudent(@RequestBody Student student, 
               HttpServletResponse response) {
        response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentContextPath()
            .path("/findStudent/" + student.getId()).toUriString());

        return studentService.saveStudent(student);
    }

}

Usando @BeforeClass

@BeforeClass
public static void runBeforeAllTestMethods() {
    createPersonUrl = "http://localhost:8080/addstudent";
    updatePersonUrl = "http://localhost:8080/updatestudent";

    restTemplate = new RestTemplate();
    headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    JsonObjectStudent = new JSONObject();
    JsonObjectStudent.put("id", 1);
    JsonObjectStudent.put("name", "John");
}

Usando @Test

@Test
public void postforEnityMethod()
throws IOException {
    HttpEntity < String > request =
        new HttpEntity < String > (.toString(), headers);

    ResponseEntity < String > responseEntityStr = restTemplate.
    postForEntity(JsonObjectStudent, request, String.class);
    JsonNode root = objectMapper.readTree(responseEntityStr.getBody());

    assertNotNull(responseEntityStr.getBody());
    assertNotNull(root.path("name").asText());
}

Usando @Test

@Test
public void postJsonObject()
throws IOException {
    HttpEntity < String > request =
        new HttpEntity < String > (studentJsonObject.toString(), headers);

    String personResultAsJsonStr =
        restTemplate.postForObject(createStudentUrl, request, String.class);
    JsonNode root = objectMapper.readTree(personResultAsJsonStr);

    assertNotNull(studentResultInJsonUrl);
    assertNotNull(root);
    assertNotNull(root.path("name").asText());
}
@Test
public void postJsonLocationObject()
throws JsonProcessingException {
    HttpEntity < String > request = new HttpEntity <String> (studentJsonObject.toString(),
                                                       headers);
    URI locationHeader = restTemplate.postForLocation(updateStudentUrl, request);

    assertNotNull(locationHeader);
}
restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
list.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(list);
...
Payment payment= new Payment("Aa4bhs");
Payment res = restTemplate.postForObject("http://localhost:8080/aurest/rest/payment",
                    payment, Payment.class);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.put(url, entity);
RestTemplate restTemplate = new RestTemplate();
 
String url = "endpoint url";
String requestJson = "{\"queriedQuestion\":\"Is there pain in your hand?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
 
HttpEntity < String > entity = new HttpEntity < String > (requestJson, headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);

Obtener todos los empleados

@GetMapping(value = "/employees", 
  produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public EmployeeListVO getAllEmployees(
  @RequestHeader(name = "X-COM-PERSIST", required = true) String headerPersist,
        @RequestHeader(name = "X-COM-LOCATION", defaultValue = "ASIA") String headerLocation) 
{
  LOGGER.info("Header X-COM-PERSIST :: " + headerPersist);
  LOGGER.info("Header X-COM-LOCATION :: " + headerLocation);
   
    EmployeeListVO employees = getEmployeeList();
    return employees;
}

Consumiendo API

RestTemplate restTemplate = new RestTemplate();
     
final String baseUrl = "http://localhost:" + randomServerPort + "/employees";
URI uri = new URI(baseUrl);
 
ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);
     
//Verify request succeed
Assert.assertEquals(200, result.getStatusCodeValue());
Assert.assertEquals(true, result.getBody().contains("employeeList"));

Solicitud exitosa

RestTemplate restTemplate = new RestTemplate();
     
final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
URI uri = new URI(baseUrl);
     
HttpHeaders headers = new HttpHeaders();
headers.set("X-COM-PERSIST", "true");  
headers.set("X-COM-LOCATION", "USA");
 
HttpEntity<Employee> requestEntity = new HttpEntity<>(null, headers);
 
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
     
//Verify request succeed
Assert.assertEquals(200, result.getStatusCodeValue());
Assert.assertEquals(true, result.getBody().contains("employeeList"));

Solicitud fallida

RestTemplate restTemplate = new RestTemplate();
     
final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
URI uri = new URI(baseUrl);
     
HttpHeaders headers = new HttpHeaders();
headers.set("X-COM-LOCATION", "USA");
 
HttpEntity<Employee> requestEntity = new HttpEntity<>(null, headers);
 
try
{
    restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
    Assert.fail();
}
catch(HttpClientErrorException ex) 
{
    //Verify bad request and missing header
    Assert.assertEquals(400, ex.getRawStatusCode());
    Assert.assertEquals(true, ex.getResponseBodyAsString().contains("Missing request header"));
}

Enlaces:

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="requestFactory">
<bean id="clientHttpRequestFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory" />
</property>
<property name="messageConverters">
<list>
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<bean id="jsonMediaTypeTextPlain" class="org.springframework.http.MediaType">
<constructor-arg value="text"/>
<constructor-arg value="plain"/>
</bean>
<bean id="jsonMediaTypeApplicationJson" class="org.springframework.http.MediaType">
<constructor-arg value="application"/>
<constructor-arg value="json"/>
</bean>
</list>
</property>
</bean>
</list>
</property>
</bean>
package com.util;
import java.nio.charset.Charset;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
public class Consumidor {
static final String URL_LOGIN = "http://192.168.20.64:8071/oauth/token";
public static void main(String[] args) {
String usernameHeader = "angularapp";
String passwordHeader = "12345";
String usernameBody = "42596272";
String passwordBody = "12345";
postLogin(usernameHeader, passwordHeader, usernameBody, passwordBody);
}
private static void postLogin(String usernameHeader, String passwordHeader, String usernameBody, String passwordBody) {
// Request Header
HttpHeaders headers = new HttpHeaders();
headers = createHeaders(usernameHeader, passwordHeader);
// Request Body
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add("username", usernameBody);
body.add("password", passwordBody);
body.add("grant_type", "password");
// Request Entity
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);
// RestTemplate
RestTemplate restTemplate = new RestTemplate();
// POST Login
ResponseEntity<String> response = restTemplate.exchange(URL_LOGIN, HttpMethod.POST, requestEntity, String.class);
HttpHeaders responseHeaders = response.getHeaders();
String responseBody = response.getBody();
String responseStatus = String.valueOf(response.getStatusCodeValue());
System.out.println("Status : " + responseStatus);
System.out.println("Body : " + responseBody);
}
private static HttpHeaders createHeaders(String username, String password){
return new HttpHeaders() {{
String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(Charset.forName("US-ASCII")) );
String authHeader = "Basic " + new String( encodedAuth );
set( "Authorization", authHeader );
}};
}
}
final String URL = "http://localhost:9080/api/documento";
RestTemplate restTemplate = new RestTemplate();
Documento doc = restTemplate.getForObject(URL, Documento.class);
final String URL_TODO = "http://localhost:9080/api/documento/all";
RestTemplate restTemplate = new RestTemplate();
Documento[] docs = restTemplate.getForObject(URL_ALL, Documento[].class);
List<Documento> listDocs = Arrays.asList(docs);
List<Documento> soloPDF = listDocs.stream().filter((Documento d)-> d.endsWith("pdf")).collect(toList());
soloPDF.forEach(System.out::println);
package com.example.consumingrest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumingRestApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Quote quote = restTemplate.getForObject(
"https://quoters.apps.pcfone.io/api/random", Quote.class);
log.info(quote.toString());
};
}
}
package main;
// imports
@ResController
@RequestMapping("/api")
public class EjemploController{
@GetMapping("/saludo")
public String getSaludo(){
return "Este es un simple saludo";
}
@GetMapping("/resultado")
public String getResultado(){
final String URL = "http://localhost:9080/api/saludo";
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForObject(URL, String.class);
}
}
package com.howtodoinjava.rest.controller;
import java.net.URI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.howtodoinjava.rest.dao.EmployeeDAO;
import com.howtodoinjava.rest.model.Employee;
import com.howtodoinjava.rest.model.Employees;
@RestController
@RequestMapping(path = "/employees")
public class EmployeeController
{
@Autowired
private EmployeeDAO employeeDao;
@PostMapping(path= "/", consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> addEmployee(
@RequestHeader(name = "X-COM-PERSIST", required = true) String headerPersist,
@RequestHeader(name = "X-COM-LOCATION", defaultValue = "ASIA") String headerLocation,
@RequestBody Employee employee)
throws Exception
{
//Generate resource id
Integer id = employeeDao.getAllEmployees().getEmployeeList().size() + 1;
employee.setId(id);
//add resource
employeeDao.addEmployee(employee);
//Create resource location
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(employee.getId())
.toUri();
//Send location in response
return ResponseEntity.created(location).build();
}
}
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
@Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
package main;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.http.client.CommonsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
public class RestJsonTest {
private static RestJsonTest instance;
private RestTemplate restTemplate;
private String url ="http://rest.service.url";
public static RestJsonTest getInstance() {
if (instance == null) {
instance = new RestJsonTest();
}
return instance;
}
private RestJsonTest() {
// Setup the RestTemplate configuration.
restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new CommonsClientHttpRequestFactory());
List<HttpMessageConverter<?>> messageConverterList = restTemplate.getMessageConverters();
// Set HTTP Message converter using a JSON implementation.
MappingJacksonHttpMessageConverter jsonMessageConverter = new MappingJacksonHttpMessageConverter();
// Add supported media type returned by BI API.
List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
supportedMediaTypes.add(new MediaType("text", "plain"));
supportedMediaTypes.add(new MediaType("application", "json"));
jsonMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
messageConverterList.add(jsonMessageConverter);
restTemplate.setMessageConverters(messageConverterList);
}
public SearchResults searchResults() {
return restTemplate.getForObject(url, SearchResults.class);
}
public static void main(String[] args) {
RestJsonTest jsonTest = RestJsonTest.getInstance();
SearchResults results = jsonTest.searchResults();
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
@Component
public class RestTemplateConfig {
@Bean
public ClientHttpRequestFactory clientHttpRequestFactory() {
int timeout = 5000;
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(timeout);
clientHttpRequestFactory.setConnectionRequestTimeout(timeout);
clientHttpRequestFactory.setReadTimeout(timeout);
return clientHttpRequestFactory;
}
}
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.List;
@Component
public class RestTemplateHelper {
private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateHelper.class);
private RestTemplate restTemplate;
private ObjectMapper objectMapper;
@Autowired
public RestTemplateHelper(RestTemplateBuilder restTemplateBuilder, ObjectMapper objectMapper) {
this.restTemplate = restTemplateBuilder.build();
this.objectMapper = objectMapper;
}
public <T> T getForEntity(Class<T> clazz, String url, Object... uriVariables) {
try {
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, uriVariables);
JavaType javaType = objectMapper.getTypeFactory().constructType(clazz);
return readValue(response, javaType);
} catch (HttpClientErrorException exception) {
if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
LOGGER.info("No data found {}", url);
} else {
LOGGER.info("rest client exception", exception.getMessage());
}
}
return null;
}
public <T> List<T> getForList(Class<T> clazz, String url, Object... uriVariables) {
try {
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, uriVariables);
CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, clazz);
return readValue(response, collectionType);
} catch (HttpClientErrorException exception) {
if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
LOGGER.info("No data found {}", url);
} else {
LOGGER.info("rest client exception", exception.getMessage());
}
}
return null;
}
public <T, R> T postForEntity(Class<T> clazz, String url, R body, Object... uriVariables) {
HttpEntity<R> request = new HttpEntity<>(body);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class, uriVariables);
JavaType javaType = objectMapper.getTypeFactory().constructType(clazz);
return readValue(response, javaType);
}
public <T, R> T putForEntity(Class<T> clazz, String url, R body, Object... uriVariables) {
HttpEntity<R> request = new HttpEntity<>(body);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, request, String.class, uriVariables);
JavaType javaType = objectMapper.getTypeFactory().constructType(clazz);
return readValue(response, javaType);
}
public void delete(String url, Object... uriVariables) {
try {
restTemplate.delete(url, uriVariables);
} catch (RestClientException exception) {
LOGGER.info(exception.getMessage());
}
}
private <T> T readValue(ResponseEntity<String> response, JavaType javaType) {
T result = null;
if (response.getStatusCode() == HttpStatus.OK ||
response.getStatusCode() == HttpStatus.CREATED) {
try {
result = objectMapper.readValue(response.getBody(), javaType);
} catch (IOException e) {
LOGGER.info(e.getMessage());
}
} else {
LOGGER.info("No data found {}", response.getStatusCode());
}
return result;
}
}
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.salesforce.bigobjects.config.RestTemplateConfig;
@RestController
public class RestTemplateRequestToSalesforce {
private static final Logger LOG = LoggerFactory.getLogger(RestTemplateRequestToSalesforce.class);
// Inject the Rest template configuration
@Autowired
RestTemplateConfig restConfig;
/**
* Simple Rest end point in this app to demonstrate authenticating and then calling the Salesforce REST url
*
* @return
*/
@GetMapping("/accounts")
public String callRestUrl() {
// First define the OAuth2 token URL as follows by replacing YOUR_INSTANCE
// with the actual instance that you have your org on
String oauthUrl = "https://YOUR_INSTANCE.salesforce.com/services/oauth2/token";
// Create a multi value map to put necessary attributes
// for the authentication request
MultiValueMap<String, String> mvMap = new LinkedMultiValueMap<>();
mvMap.add("grant_type", "password");
mvMap.add("client_id", "Your Client Id");
mvMap.add("client_secret", "Your Client Secret");
mvMap.add("username", "Your username");
mvMap.add("password", "Your password");
// Create an instance of the RestTemplate
RestTemplate restTemplate = new RestTemplate(restConfig.clientHttpRequestFactory());
// Send the REST request to get authenticated and receive an OAuth token
Map<String, String> token = (Map<String, String>) restTemplate.postForObject(oauthUrl, mvMap, Map.class);
LOG.info("--------------------------------------------");
LOG.info("Access Token :: " + token.get("access_token"));
LOG.info("Instance Url :: " + token.get("instance_url"));
LOG.info("Id :: " + token.get("id"));
LOG.info("Token_Type :: " + token.get("token_type"));
LOG.info("Signature :: " + token.get("signature"));
LOG.info("--------------------------------------------");
// The oauth token is now required for all further calls to the REST resources
String oauthToken = token.get("access_token");
// The REST url of your Salesforce Apex class will be of the form
String restUrl = "https://YOUR_ISTANCE.salesforce.com/services/apexrest/Account";
// Create Http headers and add the oauth token to them
HttpHeaders restHeaders = new HttpHeaders();
restHeaders.setContentType(MediaType.APPLICATION_JSON);
restHeaders.add("X-PrettyPrint", "1");
restHeaders.add("Authorization", "OAuth " + oauthToken);
// Create a Multi value map in case there are query params. In this example
// there are none so just an empty map is okay
MultiValueMap<String, String> mv2Map = new LinkedMultiValueMap<>();
// Following example code is using the RestTemplate exchange(..) method for making a GET request
// Other methods like getForEntity() or getForObject() can also be used.
HttpEntity<?> restRequest = new HttpEntity<>(mv2Map, restHeaders);
RestTemplate getRestTemplate = new RestTemplate(restConfig.clientHttpRequestFactory());
// Make a request and read the response string
ResponseEntity<String> responseStr = getRestTemplate.exchange(restUrl, HttpMethod.GET, restRequest,
String.class);
// Return just the body of the response. You can examine the headers, etc if you wish
HttpStatus responseStatus = responseStr.getStatusCode();
HttpHeaders responseHeaders = responseStr.getHeaders();
String responseBody = responseStr.getBody();
LOG.info("REST API response:" + responseBody);
return responseBody;
}
}
package main;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown=true)
public class SearchResult {
@JsonProperty("url")
private String url;
@JsonProperty("rank")
private int rank;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
}
package main;
import java.util.List;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
/**
*{
* "search_keywords":"Social Networks",
* "total_time":200,
* "results":{
* "result_01":{
* "url":"http://www.facebook.com",
* "rank": "1"
* },
* "result_02":{
* "url":"http://www.twitter.com",
* "rank": "2"
* }
* }
* }
*/
@JsonIgnoreProperties(ignoreUnknown=true)
public class SearchResults {
@JsonProperty("search_keywords")
private String keywords;
@JsonProperty("total_time")
private long totalTime;
@JsonProperty("results")
private List<SearchResult> results;
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public long getTotalTime() {
return totalTime;
}
public void setTotalTime(long totalTime) {
this.totalTime = totalTime;
}
public List<SearchResult> getResults() {
return results;
}
public void setResults(List<SearchResult> results) {
this.results = results;
}
}
package main;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.Collections;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
@RunWith (SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration (classes = Config.class)
@WebAppConfiguration
@IntegrationTest
public class UserControllerTest
{
final String BASE_URL = "http://localhost:9999/customer/";
@Test
public void shouldCreateNewUser() {
final String USER_NAME = "Leif Ericson";
final String USER_ADDRESS = "Vinland";
User user = new User();
user.setName(USER_NAME);
user.setAddress(USER_ADDRESS);
RestTemplate rest = new TestRestTemplate();
ResponseEntity<User> response =
rest.postForEntity(BASE_URL, user, User.class, Collections.EMPTY_MAP);
assertThat( response.getStatusCode() , equalTo(HttpStatus.CREATED));
User userCreated = response.getBody();
assertThat( userCreated.getId() , notNullValue() );
assertThat( userCreated.getName() , equalTo(CUSTOMER_NAME) );
assertThat( userCreated.getAddress() , equalTo(CUSTOMER_ADDRESS) );
}
@Test
public void shouldFailToGetUnknownUser()
throws IOException {
final int UNKNOWN_ID = Integer.MAX_VALUE;
final String EXPECTED_ANSWER_MESSAGE = "user with id : '" + UNKNOWN_ID+ "' does not exist";
RestTemplate rest = new TestRestTemplate();
ResponseEntity<String> response = rest.getForEntity(BASE_URL + UNKNOWN_ID, String.class);
assertThat( response.getStatusCode() , equalTo(HttpStatus.NOT_FOUND));
ObjectMapper objectMapper = new ObjectMapper();
JsonNode responseJson = objectMapper.readTree(response.getBody());
JsonNode messageJson = responseJson.path("message");
assertThat( messageJson.isMissingNode() , is(false) );
assertThat( messageJson.asText() , equalTo(EXPECTED_ANSWER_MESSAGE) );
}
}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.Collections;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
@RunWith (SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration (classes = Config.class)
@WebAppConfiguration
@IntegrationTest
public class UserControllerTest
{
final String BASE_URL = "http://localhost:9999/customer/";
@Test
public void shouldCreateNewUser() {
final String USER_NAME = "Leif Ericson";
final String USER_ADDRESS = "Vinland";
User user = new User();
user.setName(USER_NAME);
user.setAddress(USER_ADDRESS);
RestTemplate rest = new TestRestTemplate();
ResponseEntity<User> response =
rest.postForEntity(BASE_URL, user, User.class, Collections.EMPTY_MAP);
assertThat( response.getStatusCode() , equalTo(HttpStatus.CREATED));
User userCreated = response.getBody();
assertThat( userCreated.getId() , notNullValue() );
assertThat( userCreated.getName() , equalTo(CUSTOMER_NAME) );
assertThat( userCreated.getAddress() , equalTo(CUSTOMER_ADDRESS) );
}
@Test
public void shouldFailToGetUnknownUser()
throws IOException {
final int UNKNOWN_ID = Integer.MAX_VALUE;
final String EXPECTED_ANSWER_MESSAGE = "user with id : '" + UNKNOWN_ID+ "' does not exist";
RestTemplate rest = new TestRestTemplate();
ResponseEntity<String> response = rest.getForEntity(BASE_URL + UNKNOWN_ID, String.class);
assertThat( response.getStatusCode() , equalTo(HttpStatus.NOT_FOUND));
ObjectMapper objectMapper = new ObjectMapper();
JsonNode responseJson = objectMapper.readTree(response.getBody());
JsonNode messageJson = responseJson.path("message");
assertThat( messageJson.isMissingNode() , is(false) );
assertThat( messageJson.asText() , equalTo(EXPECTED_ANSWER_MESSAGE) );
}
}
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {
private Long id;
private String quote;
public Value() {
}
public Long getId() {
return this.id;
}
public String getQuote() {
return this.quote;
}
public void setId(Long id) {
this.id = id;
}
public void setQuote(String quote) {
this.quote = quote;
}
@Override
public String toString() {
return "Value{" +
"id=" + id +
", quote='" + quote + '\'' +
'}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment