Skip to content

Source code

Ken Kousen edited this page Oct 9, 2018 · 4 revisions

Selected source code examples

HelloRestController.java
package com.oreilly.demo.controllers;

import com.oreilly.demo.entities.Greeting;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloRestController {

    @GetMapping(value = "/rest",
            produces = {MediaType.APPLICATION_JSON_VALUE,
                    MediaType.APPLICATION_XML_VALUE})
    public Greeting greet(@RequestParam(required = false,
            defaultValue = "World") String name) {
        return new Greeting(String.format("Hello, %s!", name));
    }
}
Greeting.java
package com.oreilly.demo.entities;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Objects;

@XmlRootElement
public class Greeting {
    @XmlElement
    private String greeting;

    public Greeting() {}

    public Greeting(String greeting) {
        this.greeting = greeting;
    }

    public String getGreeting() {
        return greeting;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Greeting)) return false;
        Greeting gr = (Greeting) o;
        return Objects.equals(greeting, gr.greeting);
    }

    @Override
    public int hashCode() {
        return Objects.hash(greeting);
    }

    @Override
    public String toString() {
        return greeting;
    }
}
HelloRestControllerTests.java
package com.oreilly.demo.controllers;

import com.oreilly.demo.entities.Greeting;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URI;

import static org.junit.Assert.assertEquals;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloRestControllerTests {
    @Autowired
    private TestRestTemplate template;

    @Test
    public void greetWithName() {
        Greeting response = template.getForObject("/rest?name=Dolly", Greeting.class);
        assertEquals("Hello, Dolly!", response.getGreeting());
    }

    @Test
    public void greetWithoutName_XML() {
//        ResponseEntity<Greeting> entity = template.getForEntity("/rest", Greeting.class);

        RequestEntity<Void> request = RequestEntity.get(URI.create("/rest"))
                                                 .accept(MediaType.APPLICATION_XML)
                                                 .build();

        ResponseEntity<Greeting> entity = template.exchange(request, Greeting.class);

        assertEquals(HttpStatus.OK, entity.getStatusCode());
        assertEquals(MediaType.APPLICATION_XML, entity.getHeaders().getContentType());
        Greeting response = entity.getBody();
        assertEquals("Hello, World!", response.getGreeting());
    }

    @Test
    public void greetWithoutName_JSON() {
//        ResponseEntity<Greeting> entity = template.getForEntity("/rest", Greeting.class);

        RequestEntity<Void> request = RequestEntity.get(URI.create("/rest"))
                                                   .accept(MediaType.APPLICATION_JSON)
                                                   .build();

        ResponseEntity<Greeting> entity = template.exchange(request, Greeting.class);

        assertEquals(HttpStatus.OK, entity.getStatusCode());
        assertEquals(MediaType.APPLICATION_JSON_UTF8, entity.getHeaders().getContentType());
        Greeting response = entity.getBody();
        assertEquals("Hello, World!", response.getGreeting());
    }

}
AppConfig.java
package com.oreilly.restclient.config;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import java.text.NumberFormat;
import java.util.Locale;

@Configuration
public class AppConfig {

    @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public NumberFormat defaultFormat() {
        return NumberFormat.getCurrencyInstance();
    }

    @Bean
    public NumberFormat deutschFormat() {
        return NumberFormat.getCurrencyInstance(Locale.GERMANY);
    }
}
RestclientApplicationTests.java
package com.oreilly.restclient;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

import java.text.NumberFormat;
import java.util.Arrays;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RestclientApplicationTests {
    @Autowired
    private ApplicationContext context;

    @Autowired @Qualifier("defaultFormat")
    private NumberFormat numberFormat;

    @Test
    public void contextLoads() {
        System.out.println("There are " + context.getBeanDefinitionCount()
            + " beans in the application context");

        System.out.println("The application context class is " +
                context.getClass().getName());

        String[] names = context.getBeanDefinitionNames();
        assertThat(names, hasItemInArray("defaultFormat"));
    }

    @Test
    public void defaultCurrencyFormat_getBean() {
        double amount = 12345678.9012345;
        NumberFormat nf = context.getBean("defaultFormat", NumberFormat.class);
        String formattedCurrency = nf.format(amount);
        assertThat(formattedCurrency, is(equalTo("$12,345,678.90")));
    }

    @Test
    public void defaultCurrencyFormat_autowired() {
        double amount = 12345678.9012345;
        String formattedCurrency = numberFormat.format(amount);
        assertThat(formattedCurrency, is(equalTo("$12,345,678.90")));
    }

    @Test
    public void deutschCurrencyFormat_getBean() {
        double amount = 12345678.9012345;
        NumberFormat nf = context.getBean("deutschFormat", NumberFormat.class);
        String formattedCurrency = nf.format(amount);
        assertThat(formattedCurrency, is(equalTo("12.345.678,90 €")));
    }

    @Test
    public void deutchFormat_isSingleton() {
        NumberFormat nf1 = context.getBean("deutschFormat", NumberFormat.class);
        NumberFormat nf2 = context.getBean("deutschFormat", NumberFormat.class);

        assertSame(nf1, nf2);
        assertEquals(nf1, nf2);
    }

    @Test
    public void defaultFormat_isNotSingleton() {
        NumberFormat nf1 = context.getBean("defaultFormat", NumberFormat.class);
        NumberFormat nf2 = context.getBean("defaultFormat", NumberFormat.class);

        assertNotSame(nf1, nf2);
        assertEquals(nf1, nf2);
    }

}
Clone this wiki locally