BAEL-3091: The Prototype Pattern in Java (changed code based on valid comments from a reader)

This commit is contained in:
Vivek Balasubramaniam
2019-10-29 22:27:15 +05:30
parent db85c8f275
commit d3d5b060e7
20517 changed files with 1642290 additions and 0 deletions
@@ -0,0 +1,17 @@
package com.baeldung.changeport;
import java.util.Collections;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CustomApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(CustomApplication.class);
app.setDefaultProperties(Collections.singletonMap("server.port", "8083"));
app.run(args);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.changeport;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;
//@Component
public class ServerPortCustomizer implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {
@Override
public void customize(ConfigurableWebServerFactory factory) {
factory.setPort(8086);
}
}
@@ -0,0 +1,76 @@
package com.baeldung.controllers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import java.util.concurrent.ForkJoinPool;
@RestController
public class DeferredResultController {
private final static Logger LOG = LoggerFactory.getLogger(DeferredResultController.class);
@GetMapping("/async-deferredresult")
public DeferredResult<ResponseEntity<?>> handleReqDefResult(Model model) {
LOG.info("Received async-deferredresult request");
DeferredResult<ResponseEntity<?>> output = new DeferredResult<>();
ForkJoinPool.commonPool().submit(() -> {
LOG.info("Processing in separate thread");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
}
output.setResult(ResponseEntity.ok("ok"));
});
LOG.info("servlet thread freed");
return output;
}
public DeferredResult<ResponseEntity<?>> handleReqWithTimeouts(Model model) {
LOG.info("Received async request with a configured timeout");
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(500l);
deferredResult.onTimeout(new Runnable() {
@Override
public void run() {
deferredResult.setErrorResult(
ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT).body("Request timeout occurred."));
}
});
ForkJoinPool.commonPool().submit(() -> {
LOG.info("Processing in separate thread");
try {
Thread.sleep(600l);
deferredResult.setResult(ResponseEntity.ok("ok"));
} catch (InterruptedException e) {
LOG.info("Request processing interrupted");
deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("INTERNAL_SERVER_ERROR occurred."));
}
});
LOG.info("servlet thread freed");
return deferredResult;
}
public DeferredResult<ResponseEntity<?>> handleAsyncFailedRequest(Model model) {
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
ForkJoinPool.commonPool().submit(() -> {
try {
// Exception occurred in processing
throw new Exception();
} catch (Exception e) {
LOG.info("Request processing failed");
deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("INTERNAL_SERVER_ERROR occurred."));
}
});
return deferredResult;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ViewController {
@GetMapping("/")
public String welcome() {
return "index";
}
}
@@ -0,0 +1,13 @@
package com.baeldung.produceimage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@EnableAutoConfiguration
@ComponentScan("com.baeldung.produceimage")
public class ImageApplication {
public static void main(final String[] args) {
SpringApplication.run(ImageApplication.class, args);
}
}
@@ -0,0 +1,38 @@
package com.baeldung.produceimage.controller;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
import java.io.InputStream;
@Controller
public class DataProducerController {
@GetMapping("/get-text")
public @ResponseBody String getText() {
return "Hello world";
}
@GetMapping("/get-image")
public @ResponseBody byte[] getImage() throws IOException {
final InputStream in = getClass().getResourceAsStream("/com/baeldung/produceimage/image.jpg");
return IOUtils.toByteArray(in);
}
@GetMapping(value = "/get-image-with-media-type", produces = MediaType.IMAGE_JPEG_VALUE)
public @ResponseBody byte[] getImageWithMediaType() throws IOException {
final InputStream in = getClass().getResourceAsStream("/com/baeldung/produceimage/image.jpg");
return IOUtils.toByteArray(in);
}
@GetMapping(value = "/get-file", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody byte[] getFile() throws IOException {
final InputStream in = getClass().getResourceAsStream("/com/baeldung/produceimage/data.txt");
return IOUtils.toByteArray(in);
}
}
@@ -0,0 +1,12 @@
package com.baeldung.propertyeditor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PropertyEditorApplication {
public static void main(String[] args) {
SpringApplication.run(PropertyEditorApplication.class, args);
}
}
@@ -0,0 +1,36 @@
package com.baeldung.propertyeditor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.propertyeditor.creditcard.CreditCard;
import com.baeldung.propertyeditor.exotictype.editor.CustomExoticTypeEditor;
import com.baeldung.propertyeditor.exotictype.model.ExoticType;
@RestController
@RequestMapping(value = "/property-editor")
public class PropertyEditorRestController {
@GetMapping(value = "/credit-card/{card-no}",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public CreditCard parseCreditCardNumber(@PathVariable("card-no") CreditCard creditCard) {
return creditCard;
}
@GetMapping(value = "/exotic-type/{value}",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ExoticType parseExoticType(@PathVariable("value") ExoticType exoticType) {
return exoticType;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(ExoticType.class, new CustomExoticTypeEditor());
}
}
@@ -0,0 +1,41 @@
package com.baeldung.propertyeditor.creditcard;
public class CreditCard {
private String rawCardNumber;
private Integer bankIdNo;
private Integer accountNo;
private Integer checkCode;
public String getRawCardNumber() {
return rawCardNumber;
}
public void setRawCardNumber(String rawCardNumber) {
this.rawCardNumber = rawCardNumber;
}
public Integer getBankIdNo() {
return bankIdNo;
}
public void setBankIdNo(Integer bankIdNo) {
this.bankIdNo = bankIdNo;
}
public Integer getAccountNo() {
return accountNo;
}
public void setAccountNo(Integer accountNo) {
this.accountNo = accountNo;
}
public Integer getCheckCode() {
return checkCode;
}
public void setCheckCode(Integer checkCode) {
this.checkCode = checkCode;
}
}
@@ -0,0 +1,39 @@
package com.baeldung.propertyeditor.creditcard;
import java.beans.PropertyEditorSupport;
import org.springframework.util.StringUtils;
public class CreditCardEditor extends PropertyEditorSupport {
@Override
public String getAsText() {
CreditCard creditCard = (CreditCard) getValue();
return creditCard == null ? "" : creditCard.getRawCardNumber();
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (StringUtils.isEmpty(text)) {
setValue(null);
} else {
CreditCard creditCard = new CreditCard();
creditCard.setRawCardNumber(text);
String cardNo = text.replaceAll("-", "");
if (cardNo.length() != 16)
throw new IllegalArgumentException("Credit card format should be xxxx-xxxx-xxxx-xxxx");
try {
creditCard.setBankIdNo( Integer.valueOf(cardNo.substring(0, 6)) );
creditCard.setAccountNo( Integer.valueOf(cardNo.substring(6, cardNo.length() - 1)) );
creditCard.setCheckCode( Integer.valueOf(cardNo.substring(cardNo.length() - 1)) );
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException(nfe);
}
setValue(creditCard);
}
}
}
@@ -0,0 +1,23 @@
package com.baeldung.propertyeditor.exotictype.editor;
import java.beans.PropertyEditorSupport;
import com.baeldung.propertyeditor.exotictype.model.ExoticType;
public class CustomExoticTypeEditor extends PropertyEditorSupport {
@Override
public String getAsText() {
ExoticType exoticType = (ExoticType) getValue();
return exoticType == null ? "" : exoticType.getName();
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
ExoticType exoticType = new ExoticType();
exoticType.setName(text.toUpperCase());
setValue(exoticType);
}
}
@@ -0,0 +1,14 @@
package com.baeldung.propertyeditor.exotictype.model;
public class ExoticType {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.responseheaders;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@SpringBootApplication
public class ResponseHeadersApplication {
public static void main(String[] args) {
SpringApplication.run(ResponseHeadersApplication.class, args);
}
}
@@ -0,0 +1,24 @@
package com.baeldung.responseheaders.controllers;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/filter-response-header")
public class FilterResponseHeaderController {
@GetMapping("/no-extra-header")
public String FilterHeaderResponseWithNoExtraHeader() {
return "Response body with Filter header and no extra header";
}
@GetMapping("/extra-header")
public String FilterHeaderResponseWithExtraHeader(HttpServletResponse response) {
response.addHeader("Baeldung-Example-Header", "Value-ExtraHeader");
return "Response body with Filter header and one extra header";
}
}
@@ -0,0 +1,70 @@
package com.baeldung.responseheaders.controllers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/single-response-header")
public class ResponseHeaderController {
@GetMapping("/http-servlet-response")
public String usingHttpServletResponse(HttpServletResponse response) {
response.addHeader("Baeldung-Example-Header", "Value-HttpServletResponse");
return "Response with header using HttpServletResponse";
}
@GetMapping("/response-entity-constructor")
public ResponseEntity<String> usingResponseEntityConstructor() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityContructor");
String responseBody = "Response with header using ResponseEntity (constructor)";
HttpStatus responseStatus = HttpStatus.OK;
return new ResponseEntity<String>(responseBody, responseHeaders, responseStatus);
}
@GetMapping("/response-entity-contructor-multiple-headers")
public ResponseEntity<String> usingResponseEntityConstructorAndMultipleHeaders() {
List<MediaType> acceptableMediaTypes = new ArrayList<>(Arrays.asList(MediaType.APPLICATION_JSON));
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityConstructorAndHeaders");
responseHeaders.setAccept(acceptableMediaTypes);
String responseBody = "Response with header using ResponseEntity (constructor)";
HttpStatus responseStatus = HttpStatus.OK;
return new ResponseEntity<String>(responseBody, responseHeaders, responseStatus);
}
@GetMapping("/response-entity-builder")
public ResponseEntity<String> usingResponseEntityBuilder() {
String responseHeaderKey = "Baeldung-Example-Header";
String responseHeaderValue = "Value-ResponseEntityBuilder";
String responseBody = "Response with header using ResponseEntity (builder)";
return ResponseEntity.ok()
.header(responseHeaderKey, responseHeaderValue)
.body(responseBody);
}
@GetMapping("/response-entity-builder-with-http-headers")
public ResponseEntity<String> usingResponseEntityBuilderAndHttpHeaders() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityBuilderWithHttpHeaders");
String responseBody = "Response with header using ResponseEntity (builder)";
return ResponseEntity.ok()
.headers(responseHeaders)
.body(responseBody);
}
}
@@ -0,0 +1,41 @@
package com.baeldung.responseheaders.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebFilter("/filter-response-header/*")
public class AddResponseHeaderFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(AddResponseHeaderFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// add special initialization requirements here
LOGGER.trace("Initializing filter...");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("Baeldung-Example-Filter-Header", "Value-Filter");
chain.doFilter(request, response);
}
@Override
public void destroy() {
// clean up any resource being held by the filter here
LOGGER.trace("Destroying filter...");
}
}
@@ -0,0 +1,16 @@
package com.baeldung.resttemplate.lists;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Sample application used to demonstrate working with Lists and RestTemplate.
*/
@SpringBootApplication
public class EmployeeApplication
{
public static void main(String[] args)
{
SpringApplication.run(EmployeeApplication.class, args);
}
}
@@ -0,0 +1,120 @@
package com.baeldung.resttemplate.lists.client;
import com.baeldung.resttemplate.lists.dto.Employee;
import com.baeldung.resttemplate.lists.dto.EmployeeList;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
/**
* Application that shows how to use Lists with RestTemplate.
*/
public class EmployeeClient {
public static void main(String[] args) {
EmployeeClient employeeClient = new EmployeeClient();
System.out.println("Calling GET for entity using arrays");
employeeClient.getForEntityEmployeesAsArray();
System.out.println("Calling GET using ParameterizedTypeReference");
employeeClient.getAllEmployeesUsingParameterizedTypeReference();
System.out.println("Calling GET using wrapper class");
employeeClient.getAllEmployeesUsingWrapperClass();
System.out.println("Calling POST using normal lists");
employeeClient.createEmployeesUsingLists();
System.out.println("Calling POST using wrapper class");
employeeClient.createEmployeesUsingWrapperClass();
}
public EmployeeClient() {
}
public Employee[] getForEntityEmployeesAsArray() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Employee[]> response =
restTemplate.getForEntity(
"http://localhost:8082/spring-rest/employees/",
Employee[].class);
Employee[] employees = response.getBody();
assert employees != null;
asList(employees).forEach(System.out::println);
return employees;
}
public List<Employee> getAllEmployeesUsingParameterizedTypeReference() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Employee>> response =
restTemplate.exchange(
"http://localhost:8082/spring-rest/employees/",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<Employee>>() {
});
List<Employee> employees = response.getBody();
assert employees != null;
employees.forEach(System.out::println);
return employees;
}
public List<Employee> getAllEmployeesUsingWrapperClass() {
RestTemplate restTemplate = new RestTemplate();
EmployeeList response =
restTemplate.getForObject(
"http://localhost:8082/spring-rest/employees/v2",
EmployeeList.class);
List<Employee> employees = response.getEmployees();
employees.forEach(System.out::println);
return employees;
}
public void createEmployeesUsingLists() {
RestTemplate restTemplate = new RestTemplate();
List<Employee> newEmployees = new ArrayList<>();
newEmployees.add(new Employee(3, "Intern"));
newEmployees.add(new Employee(4, "CEO"));
restTemplate.postForObject(
"http://localhost:8082/spring-rest/employees/",
newEmployees,
ResponseEntity.class);
}
public void createEmployeesUsingWrapperClass() {
RestTemplate restTemplate = new RestTemplate();
List<Employee> newEmployees = new ArrayList<>();
newEmployees.add(new Employee(3, "Intern"));
newEmployees.add(new Employee(4, "CEO"));
restTemplate.postForObject(
"http://localhost:8082/spring-rest/employees/v2/",
new EmployeeList(newEmployees),
ResponseEntity.class);
}
}
@@ -0,0 +1,46 @@
package com.baeldung.resttemplate.lists.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.resttemplate.lists.dto.Employee;
import com.baeldung.resttemplate.lists.dto.EmployeeList;
import com.baeldung.resttemplate.lists.service.EmployeeService;
import java.util.List;
@RestController
@RequestMapping("/employees")
public class EmployeeResource
{
@Autowired
private EmployeeService employeeService;
@RequestMapping(method = RequestMethod.GET, path = "/")
public List<Employee> getEmployees()
{
return employeeService.getAllEmployees();
}
@RequestMapping(method = RequestMethod.GET, path = "/v2")
public EmployeeList getEmployeesUsingWrapperClass()
{
List<Employee> employees = employeeService.getAllEmployees();
return new EmployeeList(employees);
}
@RequestMapping(method = RequestMethod.POST, path = "/")
public void addEmployees(@RequestBody List<Employee> employees)
{
employeeService.addEmployees(employees);
}
@RequestMapping(method = RequestMethod.POST, path = "/v2")
public void addEmployeesUsingWrapperClass(@RequestBody EmployeeList employeeWrapper)
{
employeeService.addEmployees(employeeWrapper.getEmployees());
}
}
@@ -0,0 +1,40 @@
package com.baeldung.resttemplate.lists.dto;
public class Employee {
public long id;
public String title;
public Employee()
{
}
public Employee(long id, String title)
{
this.id = id;
this.title = title;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString()
{
return "Employee #" + id + "[" + title + "]";
}
}
@@ -0,0 +1,29 @@
package com.baeldung.resttemplate.lists.dto;
import java.util.ArrayList;
import java.util.List;
public class EmployeeList
{
public List<Employee> employees;
public EmployeeList()
{
employees = new ArrayList<>();
}
public EmployeeList(List<Employee> employees)
{
this.employees = employees;
}
public void setEmployees(List<Employee> employees)
{
this.employees = employees;
}
public List<Employee> getEmployees()
{
return employees;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.resttemplate.lists.service;
import org.springframework.stereotype.Service;
import com.baeldung.resttemplate.lists.dto.Employee;
import java.util.ArrayList;
import java.util.List;
@Service
public class EmployeeService
{
public List<Employee> getAllEmployees()
{
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, "Manager"));
employees.add(new Employee(2, "Java Developer"));
return employees;
}
public void addEmployees(List<Employee> employees)
{
employees.forEach(e -> System.out.println("Adding new employee " + e));
}
}
@@ -0,0 +1,15 @@
package com.baeldung.sampleapp.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableAutoConfiguration
@ComponentScan("com.baeldung.sampleapp")
public class MainApplication implements WebMvcConfigurer {
public static void main(final String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
@@ -0,0 +1,29 @@
package com.baeldung.sampleapp.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import com.baeldung.sampleapp.interceptors.RestTemplateHeaderModifierInterceptor;
@Configuration
public class RestClientConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<ClientHttpRequestInterceptor>();
}
interceptors.add(new RestTemplateHeaderModifierInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
}
@@ -0,0 +1,42 @@
package com.baeldung.sampleapp.config;
import java.text.SimpleDateFormat;
import java.util.List;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/*
* Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml
*/
@Configuration
@EnableWebMvc
@ComponentScan({ "com.baeldung.sampleapp.web" })
public class WebConfig implements WebMvcConfigurer {
public WebConfig() {
super();
}
/*
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true)
.dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm"));
messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
// messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
// messageConverters.add(new MappingJackson2HttpMessageConverter());
// messageConverters.add(new ProtobufHttpMessageConverter());
}
*/
}
@@ -0,0 +1,18 @@
package com.baeldung.sampleapp.interceptors;
import java.io.IOException;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
public class RestTemplateHeaderModifierInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
ClientHttpResponse response = execution.execute(request, body);
response.getHeaders().add("Foo", "bar");
return response;
}
}
@@ -0,0 +1,28 @@
package com.baeldung.sampleapp.repository;
import java.util.Map;
import com.baeldung.sampleapp.web.dto.HeavyResource;
import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly;
public class HeavyResourceRepository {
public void save(HeavyResource heavyResource) {
}
public void save(HeavyResourceAddressOnly partialUpdate) {
}
public void save(Map<String, Object> updates, String id) {
}
public void save(HeavyResource heavyResource, String id) {
}
public void save(HeavyResourceAddressOnly partialUpdate, String id) {
}
}
@@ -0,0 +1,47 @@
package com.baeldung.sampleapp.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/ex")
public class BarMappingExamplesController {
public BarMappingExamplesController() {
super();
}
// API
// with @RequestParam
@RequestMapping(value = "/bars")
@ResponseBody
public String getBarBySimplePathWithRequestParam(@RequestParam("id") final long id) {
return "Get a specific Bar with id=" + id;
}
@RequestMapping(value = "/bars", params = "id")
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") final long id) {
return "Get a specific Bar with id=" + id;
}
@RequestMapping(value = "/bars", params = { "id", "second" })
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") final long id) {
return "Get a specific Bar with id=" + id;
}
// with @PathVariable
@RequestMapping(value = "/bars/{numericId:[\\d]+}")
@ResponseBody
public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) {
return "Get a specific Bar with id=" + numericId;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.sampleapp.web.controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.sampleapp.web.dto.Company;
@RestController
public class CompanyController {
@RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE)
public Company getCompanyRest() {
final Company company = new Company(1, "Xpto");
return company;
}
}
@@ -0,0 +1,85 @@
package com.baeldung.sampleapp.web.controller;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
@RestController
public class DeferredResultController {
private final static Logger LOG = LoggerFactory.getLogger(DeferredResultController.class);
@GetMapping("/async-deferredresult")
public DeferredResult<ResponseEntity<?>> handleReqDefResult(Model model) {
LOG.info("Received request");
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
deferredResult.onCompletion(() -> LOG.info("Processing complete"));
CompletableFuture.supplyAsync(() -> {
LOG.info("Processing in separate thread");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "OK";
})
.whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result)));
LOG.info("Servlet thread freed");
return deferredResult;
}
@GetMapping("/process-blocking")
public ResponseEntity<?> handleReqSync(Model model) {
// ...
return ResponseEntity.ok("ok");
}
@GetMapping("/async-deferredresult-timeout")
public DeferredResult<ResponseEntity<?>> handleReqWithTimeouts(Model model) {
LOG.info("Received async request with a configured timeout");
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(500l);
deferredResult.onTimeout(() -> deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT)
.body("Request timeout occurred.")));
CompletableFuture.supplyAsync(() -> {
LOG.info("Processing in separate thread");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "error";
})
.whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result)));
LOG.info("servlet thread freed");
return deferredResult;
}
@GetMapping("/async-deferredresult-error")
public DeferredResult<ResponseEntity<?>> handleAsyncFailedRequest(Model model) {
LOG.info("Received async request with a configured error handler");
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
deferredResult.onError(new Consumer<Throwable>() {
@Override
public void accept(Throwable t) {
deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An error occurred."));
}
});
LOG.info("servlet thread freed");
return deferredResult;
}
}
@@ -0,0 +1,42 @@
package com.baeldung.sampleapp.web.controller;
import java.util.Map;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.sampleapp.repository.HeavyResourceRepository;
import com.baeldung.sampleapp.web.dto.HeavyResource;
import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly;
@RestController
public class HeavyResourceController {
private HeavyResourceRepository heavyResourceRepository = new HeavyResourceRepository();
@RequestMapping(value = "/heavyresource/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> saveResource(@RequestBody HeavyResource heavyResource, @PathVariable("id") String id) {
heavyResourceRepository.save(heavyResource, id);
return ResponseEntity.ok("resource saved");
}
@RequestMapping(value = "/heavyresource/{id}", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> partialUpdateName(@RequestBody HeavyResourceAddressOnly partialUpdate, @PathVariable("id") String id) {
heavyResourceRepository.save(partialUpdate, id);
return ResponseEntity.ok("resource address updated");
}
@RequestMapping(value = "/heavyresource2/{id}", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> partialUpdateGeneric(@RequestBody Map<String, Object> updates,
@PathVariable("id") String id) {
heavyResourceRepository.save(updates, id);
return ResponseEntity.ok("resource updated");
}
}
@@ -0,0 +1,39 @@
package com.baeldung.sampleapp.web.controller;
import java.util.Date;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.sampleapp.web.dto.Item;
import com.baeldung.sampleapp.web.dto.ItemManager;
import com.baeldung.sampleapp.web.dto.Views;
import com.fasterxml.jackson.annotation.JsonView;
@RestController
public class ItemController {
@JsonView(Views.Public.class)
@RequestMapping("/items/{id}")
public Item getItemPublic(@PathVariable final int id) {
return ItemManager.getById(id);
}
@JsonView(Views.Internal.class)
@RequestMapping("/items/internal/{id}")
public Item getItemInternal(@PathVariable final int id) {
return ItemManager.getById(id);
}
@RequestMapping("/date")
public Date getCurrentDate() throws Exception {
return new Date();
}
@RequestMapping("/delay/{seconds}")
public void getCurrentTime(@PathVariable final int seconds) throws Exception {
Thread.sleep(seconds * 1000);
}
}
@@ -0,0 +1,85 @@
package com.baeldung.sampleapp.web.controller;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.baeldung.sampleapp.web.dto.Foo;
import com.baeldung.sampleapp.web.exception.ResourceNotFoundException;
@Controller
@RequestMapping(value = "/foos")
public class MyFooController {
private final Map<Long, Foo> myfoos;
public MyFooController() {
super();
myfoos = new HashMap<Long, Foo>();
myfoos.put(1L, new Foo(1L, "sample foo"));
}
// API - read
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" })
@ResponseBody
public Collection<Foo> findAll() {
return myfoos.values();
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = { "application/json" })
@ResponseBody
public Foo findById(@PathVariable final long id) {
final Foo foo = myfoos.get(id);
if (foo == null) {
throw new ResourceNotFoundException();
}
return foo;
}
// API - write
@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) {
myfoos.put(id, foo);
return foo;
}
@RequestMapping(method = RequestMethod.PATCH, value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void updateFoo2(@PathVariable("id") final long id, @RequestBody final Foo foo) {
myfoos.put(id, foo);
}
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Foo createFoo(@RequestBody final Foo foo, HttpServletResponse response) {
myfoos.put(foo.getId(), foo);
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentRequest()
.path("/" + foo.getId())
.toUriString());
return foo;
}
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void deleteById(@PathVariable final long id) {
myfoos.remove(id);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.sampleapp.web.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.sampleapp.web.dto.PactDto;
@RestController
public class PactController {
List<PactDto> pacts = new ArrayList<>();
@GetMapping(value = "/pact", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public PactDto getPact() {
return new PactDto(true, "tom");
}
@PostMapping("/pact")
@ResponseStatus(HttpStatus.CREATED)
public void createPact(PactDto pact) {
pacts.add(pact);
}
}
@@ -0,0 +1,74 @@
package com.baeldung.sampleapp.web.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.baeldung.sampleapp.web.dto.Foo;
// used to test HttpClientPostingTest
@RestController
public class SimplePostController {
@RequestMapping(value = "/users", method = RequestMethod.POST)
public String postUser(@RequestParam final String username, @RequestParam final String password) {
return "Success" + username;
}
@RequestMapping(value = "/users/detail", method = RequestMethod.POST)
public String postUserDetail(@RequestBody final Foo entity) {
return "Success" + entity.getId();
}
@RequestMapping(value = "/users/multipart", method = RequestMethod.POST)
public String uploadFile(@RequestParam final String username, @RequestParam final String password, @RequestParam("file") final MultipartFile file) {
if (!file.isEmpty()) {
try {
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
final String fileName = dateFormat.format(new Date());
final File fileServer = new File(fileName);
fileServer.createNewFile();
final byte[] bytes = file.getBytes();
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + username;
} catch (final Exception e) {
return "You failed to upload " + e.getMessage();
}
} else {
return "You failed to upload because the file was empty.";
}
}
@RequestMapping(value = "/users/upload", method = RequestMethod.POST)
public String postMultipart(@RequestParam("file") final MultipartFile file) {
if (!file.isEmpty()) {
try {
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
final String fileName = dateFormat.format(new Date());
final File fileServer = new File(fileName);
fileServer.createNewFile();
final byte[] bytes = file.getBytes();
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
stream.write(bytes);
stream.close();
return "You successfully uploaded ";
} catch (final Exception e) {
return "You failed to upload " + e.getMessage();
}
} else {
return "You failed to upload because the file was empty.";
}
}
}
@@ -0,0 +1,25 @@
package com.baeldung.sampleapp.web.controller.mediatypes;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.sampleapp.web.dto.BaeldungItem;
import com.baeldung.sampleapp.web.dto.BaeldungItemV2;
@RestController
@RequestMapping(value = "/", produces = "application/vnd.baeldung.api.v1+json")
public class CustomMediaTypeController {
@RequestMapping(method = RequestMethod.GET, value = "/public/api/items/{id}", produces = "application/vnd.baeldung.api.v1+json")
public @ResponseBody BaeldungItem getItem(@PathVariable("id") String id) {
return new BaeldungItem("itemId1");
}
@RequestMapping(method = RequestMethod.GET, value = "/public/api/items/{id}", produces = "application/vnd.baeldung.api.v2+json")
public @ResponseBody BaeldungItemV2 getItemSecondAPIVersion(@PathVariable("id") String id) {
return new BaeldungItemV2("itemName");
}
}
@@ -0,0 +1,68 @@
package com.baeldung.sampleapp.web.controller.redirect;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
@Controller
@RequestMapping("/")
public class RedirectController {
@RequestMapping(value = "/redirectWithXMLConfig", method = RequestMethod.GET)
public ModelAndView redirectWithUsingXMLConfig(final ModelMap model) {
model.addAttribute("attribute", "redirectWithXMLConfig");
return new ModelAndView("RedirectedUrl", model);
}
@RequestMapping(value = "/redirectWithRedirectPrefix", method = RequestMethod.GET)
public ModelAndView redirectWithUsingRedirectPrefix(final ModelMap model) {
model.addAttribute("attribute", "redirectWithRedirectPrefix");
return new ModelAndView("redirect:/redirectedUrl", model);
}
@RequestMapping(value = "/redirectWithRedirectAttributes", method = RequestMethod.GET)
public RedirectView redirectWithRedirectAttributes(final RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("flashAttribute", "redirectWithRedirectAttributes");
redirectAttributes.addAttribute("attribute", "redirectWithRedirectAttributes");
return new RedirectView("redirectedUrl");
}
@RequestMapping(value = "/redirectWithRedirectView", method = RequestMethod.GET)
public RedirectView redirectWithUsingRedirectView(final ModelMap model) {
model.addAttribute("attribute", "redirectWithRedirectView");
return new RedirectView("redirectedUrl");
}
@RequestMapping(value = "/forwardWithForwardPrefix", method = RequestMethod.GET)
public ModelAndView forwardWithUsingForwardPrefix(final ModelMap model) {
model.addAttribute("attribute", "redirectWithForwardPrefix");
return new ModelAndView("forward:/redirectedUrl", model);
}
@RequestMapping(value = "/redirectedUrl", method = RequestMethod.GET)
public ModelAndView redirection(final ModelMap model, @ModelAttribute("flashAttribute") final Object flashAttribute) {
model.addAttribute("redirectionAttribute", flashAttribute);
return new ModelAndView("redirection", model);
}
@RequestMapping(value = "/redirectPostToPost", method = RequestMethod.POST)
public ModelAndView redirectPostToPost(HttpServletRequest request) {
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
return new ModelAndView("redirect:/redirectedPostToPost");
}
@RequestMapping(value = "/redirectedPostToPost", method = RequestMethod.POST)
public ModelAndView redirectedPostToPost() {
return new ModelAndView("redirection");
}
}
@@ -0,0 +1,13 @@
package com.baeldung.sampleapp.web.dto;
public class BaeldungItem {
private final String itemId;
public BaeldungItem(String itemId) {
this.itemId = itemId;
}
public String getItemId() {
return itemId;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.sampleapp.web.dto;
public class BaeldungItemV2 {
private final String itemName;
public BaeldungItemV2(String itemName) {
this.itemName = itemName;
}
public String getItemName() {
return itemName;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.sampleapp.web.dto;
public class Company {
private long id;
private String name;
public Company() {
super();
}
public Company(final long id, final String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
@Override
public String toString() {
return "Company [id=" + id + ", name=" + name + "]";
}
}
@@ -0,0 +1,42 @@
package com.baeldung.sampleapp.web.dto;
public class Foo {
private long id;
private String name;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
public Foo(final long id, final String name) {
super();
this.id = id;
this.name = name;
}
// API
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
@@ -0,0 +1,62 @@
package com.baeldung.sampleapp.web.dto;
public class HeavyResource {
private Integer id;
private String name;
private String surname;
private Integer age;
private String address;
public HeavyResource() {
}
public HeavyResource(Integer id, String name, String surname, Integer age, String address) {
this.id = id;
this.name = name;
this.surname = surname;
this.age = age;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.sampleapp.web.dto;
public class HeavyResourceAddressOnly {
private Integer id;
private String address;
public HeavyResourceAddressOnly() {
}
public HeavyResourceAddressOnly(Integer id, String address) {
this.id = id;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.sampleapp.web.dto;
public class HeavyResourceAddressPartialUpdate {
private Integer id;
private String address;
public HeavyResourceAddressPartialUpdate() {
}
public HeavyResourceAddressPartialUpdate(Integer id, String address) {
this.id = id;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
@@ -0,0 +1,36 @@
package com.baeldung.sampleapp.web.dto;
import com.fasterxml.jackson.annotation.JsonView;
public class Item {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String itemName;
@JsonView(Views.Internal.class)
public String ownerName;
public Item() {
super();
}
public Item(final int id, final String itemName, final String ownerName) {
this.id = id;
this.itemName = itemName;
this.ownerName = ownerName;
}
public int getId() {
return id;
}
public String getItemName() {
return itemName;
}
public String getOwnerName() {
return ownerName;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.sampleapp.web.dto;
public class ItemManager {
public static Item getById(final int id) {
final Item item = new Item(2, "book", "John");
return item;
}
}
@@ -0,0 +1,33 @@
package com.baeldung.sampleapp.web.dto;
public class PactDto {
private boolean condition;
private String name;
public PactDto() {
}
public PactDto(boolean condition, String name) {
super();
this.condition = condition;
this.name = name;
}
public boolean isCondition() {
return condition;
}
public void setCondition(boolean condition) {
this.condition = condition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.sampleapp.web.dto;
public class Views {
public static class Public {
}
public static class Internal extends Public {
}
}
@@ -0,0 +1,8 @@
package com.baeldung.sampleapp.web.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
}
@@ -0,0 +1,31 @@
package com.baeldung.transfer;
public class LoginForm {
private String username;
private String password;
public LoginForm() {
}
public LoginForm(String username, String password) {
super();
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@@ -0,0 +1,41 @@
package com.baeldung.web.log.app;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import com.baeldung.web.log.config.CustomeRequestLoggingFilter;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@EnableAutoConfiguration
@ComponentScan("com.baeldung.web.log")
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.baeldung.web.log");
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
container.addFilter("customRequestLoggingFilter", CustomeRequestLoggingFilter.class).addMappingForServletNames(null, false, "dispatcher");
}
}
@@ -0,0 +1,44 @@
package com.baeldung.web.log.app;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import com.baeldung.web.log.util.RequestLoggingUtil;
@Component
public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter {
private final static Logger LOGGER = LoggerFactory.getLogger(TaxiFareRequestInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String postData;
HttpServletRequest requestCacheWrapperObject = null;
try {
// Uncomment to produce the stream closed issue
// postData = RequestLoggingUtil.getStringFromInputStream(request.getInputStream());
// To overcome request stream closed issue
requestCacheWrapperObject = new ContentCachingRequestWrapper(request);
requestCacheWrapperObject.getParameterMap();
} catch (Exception exception) {
exception.printStackTrace();
} finally {
postData = RequestLoggingUtil.readPayload(requestCacheWrapperObject);
LOGGER.info("REQUEST DATA: " + postData);
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
LOGGER.info("RESPONSE: " + response.getStatus());
}
}
@@ -0,0 +1,12 @@
package com.baeldung.web.log.config;
import org.springframework.web.filter.CommonsRequestLoggingFilter;
public class CustomeRequestLoggingFilter extends CommonsRequestLoggingFilter {
public CustomeRequestLoggingFilter() {
super.setIncludeQueryString(true);
super.setIncludePayload(true);
super.setMaxPayloadLength(10000);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.web.log.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CommonsRequestLoggingFilter;
@Configuration
public class RequestLoggingFilterConfig {
@Bean
public CommonsRequestLoggingFilter logFilter() {
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(true);
filter.setIncludePayload(true);
filter.setMaxPayloadLength(10000);
filter.setIncludeHeaders(false);
filter.setAfterMessagePrefix("REQUEST DATA : ");
return filter;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.web.log.config;
import com.baeldung.web.log.app.TaxiFareRequestInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class TaxiFareMVCConfig implements WebMvcConfigurer {
@Autowired
private TaxiFareRequestInterceptor taxiFareRequestInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(taxiFareRequestInterceptor).addPathPatterns("/**/taxifare/**/");
}
}
@@ -0,0 +1,40 @@
package com.baeldung.web.log.controller;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.baeldung.web.log.data.RateCard;
import com.baeldung.web.log.data.TaxiRide;
import com.baeldung.web.log.service.TaxiFareCalculatorService;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaxiFareController {
@Autowired
private TaxiFareCalculatorService taxiFareCalculatorService;
private static final Logger LOGGER = LoggerFactory.getLogger(TaxiFareController.class);
@GetMapping("/taxifare/get/")
public RateCard getTaxiFare() {
LOGGER.debug("getTaxiFare() - START");
return new RateCard();
}
@PostMapping("/taxifare/calculate/")
public String calculateTaxiFare(@RequestBody @Valid TaxiRide taxiRide) {
LOGGER.debug("calculateTaxiFare() - START");
String totalFare = taxiFareCalculatorService.calculateFare(taxiRide);
LOGGER.debug("calculateTaxiFare() - Total Fare : {}",totalFare);
LOGGER.debug("calculateTaxiFare() - END");
return totalFare;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.web.log.data;
public class RateCard {
private String nightSurcharge;
private String ratePerMile;
public RateCard() {
nightSurcharge = "Extra $ 100";
ratePerMile = "$ 10 Per Mile";
}
public String getNightSurcharge() {
return nightSurcharge;
}
public void setNightSurcharge(String nightSurcharge) {
this.nightSurcharge = nightSurcharge;
}
public String getRatePerMile() {
return ratePerMile;
}
public void setRatePerMile(String ratePerMile) {
this.ratePerMile = ratePerMile;
}
}
@@ -0,0 +1,33 @@
package com.baeldung.web.log.data;
public class TaxiRide {
private Boolean isNightSurcharge;
private Long distanceInMile;
public TaxiRide() {
}
public TaxiRide(Boolean isNightSurcharge, Long distanceInMile) {
this.isNightSurcharge = isNightSurcharge;
this.distanceInMile = distanceInMile;
}
public Boolean getIsNightSurcharge() {
return isNightSurcharge;
}
public void setIsNightSurcharge(Boolean isNightSurcharge) {
this.isNightSurcharge = isNightSurcharge;
}
public Long getDistanceInMile() {
return distanceInMile;
}
public void setDistanceInMile(Long distanceInMile) {
this.distanceInMile = distanceInMile;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.web.log.service;
import com.baeldung.web.log.data.TaxiRide;
import org.springframework.stereotype.Service;
@Service
public class TaxiFareCalculatorService {
public String calculateFare(TaxiRide taxiRide) {
return String.valueOf((Long) (taxiRide.getIsNightSurcharge()
? taxiRide.getDistanceInMile() * 10 + 100
: taxiRide.getDistanceInMile() * 10));
}
}
@@ -0,0 +1,38 @@
package com.baeldung.web.log.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.WebUtils;
public class RequestLoggingUtil {
public static String getStringFromInputStream(InputStream is) {
StringWriter writer = new StringWriter();
String encoding = "UTF-8";
try {
IOUtils.copy(is, writer, encoding);
} catch (IOException e) {
e.printStackTrace();
}
return writer.toString();
}
public static String readPayload(final HttpServletRequest request) throws IOException {
String payloadData = null;
ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
if (null != contentCachingRequestWrapper) {
byte[] buf = contentCachingRequestWrapper.getContentAsByteArray();
if (buf.length > 0) {
payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding());
}
}
return payloadData;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.web.upload.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
@EnableAutoConfiguration
@ComponentScan("com.baeldung.web.upload")
@SpringBootApplication
public class UploadApplication extends SpringBootServletInitializer {
public static void main(final String[] args) {
SpringApplication.run(UploadApplication.class, args);
}
}
@@ -0,0 +1,61 @@
package com.baeldung.web.upload.client;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class MultipartFileUploadClient {
public static void main(String[] args) throws IOException {
uploadSingleFile();
uploadMultipleFile();
}
private static void uploadSingleFile() throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", getTestFile());
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
System.out.println("Response code: " + response.getStatusCode());
}
private static void uploadMultipleFile() throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("files", getTestFile());
body.add("files", getTestFile());
body.add("files", getTestFile());
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
System.out.println("Response code: " + response.getStatusCode());
}
public static Resource getTestFile() throws IOException {
Path testFile = Files.createTempFile("test-file", ".txt");
System.out.println("Creating and Uploading Test File: " + testFile);
Files.write(testFile, "Hello World !!, This is a test file.".getBytes());
return new FileSystemResource(testFile.toFile());
}
}
@@ -0,0 +1,43 @@
package com.baeldung.web.upload.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/fileserver")
public class FileServerResource {
@RequestMapping(path = "/singlefileupload/", method = RequestMethod.POST)
public ResponseEntity<String> processFile(@RequestParam("file") MultipartFile file) throws IOException {
byte[] bytes = file.getBytes();
System.out.println("File Name: " + file.getOriginalFilename());
System.out.println("File Content Type: " + file.getContentType());
System.out.println("File Content:\n" + new String(bytes));
return (new ResponseEntity<>("Successful", null, HttpStatus.OK));
}
@RequestMapping(path = "/multiplefileupload/", method = RequestMethod.POST)
public ResponseEntity<String> processFile(@RequestParam("files") List<MultipartFile> files) throws IOException {
for (MultipartFile file : files) {
byte[] bytes = file.getBytes();
System.out.println("File Name: " + file.getOriginalFilename());
System.out.println("File Content Type: " + file.getContentType());
System.out.println("File Content:\n" + new String(bytes));
}
return (new ResponseEntity<>("Successful", null, HttpStatus.OK));
}
}
@@ -0,0 +1,2 @@
server.port= 8082
server.servlet.context-path=/spring-rest
@@ -0,0 +1 @@
This is a sample file containing text data
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework.web.filter.CommonsRequestLoggingFilter">
<level value="DEBUG" />
</logger>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,61 @@
{
"provider": {
"name": "test_provider"
},
"consumer": {
"name": "test_consumer"
},
"interactions": [
{
"description": "GET REQUEST",
"request": {
"method": "GET",
"path": "/pact"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"condition": true,
"name": "tom"
}
},
"providerStates": [
{
"name": "test GET"
}
]
},
{
"description": "POST REQUEST",
"request": {
"method": "POST",
"path": "/pact",
"headers": {
"Content-Type": "application/json"
},
"body": {
"name": "Michael"
}
},
"response": {
"status": 201
},
"providerStates": [
{
"name": "test POST"
}
]
}
],
"metadata": {
"pact-specification": {
"version": "3.0.0"
},
"pact-jvm": {
"version": "3.5.0"
}
}
}
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"
>
<context:component-scan base-package="com.baeldung.sampleapp.web" />
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" >
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<!-- <bean class="org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter"/> -->
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/WEB-INF/spring-views.xml</value>
</property>
<property name="order" value="0" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
</bean>
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/json" />
</bean>
</beans>
@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Company Data</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"
integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$('#REST-button').click(function() {
$.ajax({
url: 'http://localhost:8080/spring-rest/companyRest?callback=getCompanyData',
data: {
format: 'json'
},
type: 'GET',
jsonpCallback:'getCompanyData',
dataType: 'jsonp',
error: function() {
$('#infoREST').html('<p>An error has occurred</p>');
},
success: function(data) {
console.log("sucess");
}
});
});
});
function getCompanyData(data) {
document.write("<b>ID:</b> "+data.id+"<br/>");
document.write("<b>NAME:</b> "+data.name+"<br/>");
document.write("<br/>");
}
</script>
</head>
<body>
<!-- Using REST URL-->
<button id="REST-button">Test REST JSON-P!</button>
<div id="infoREST"></div>
</body>
</html>
@@ -0,0 +1,10 @@
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
>
<bean id="RedirectedUrl" class="org.springframework.web.servlet.view.RedirectView">
<property name="url" value="redirectedUrl" />
</bean>
</beans>
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
>
<display-name>Spring MVC Application</display-name>
<!-- Spring root -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.baeldung.sampleapp.config</param-value>
</context-param>
<!-- <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
-->
<!-- Spring child -->
<servlet>
<servlet-name>api</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>api</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file/>
</welcome-file-list>
</web-app>
@@ -0,0 +1,24 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.changeport.CustomApplication;
import com.baeldung.produceimage.ImageApplication;
import com.baeldung.propertyeditor.PropertyEditorApplication;
import com.baeldung.responseheaders.ResponseHeadersApplication;
import com.baeldung.sampleapp.config.MainApplication;
import com.baeldung.web.log.app.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { CustomApplication.class, ImageApplication.class, PropertyEditorApplication.class,
ResponseHeadersApplication.class, Application.class, com.baeldung.web.upload.app.UploadApplication.class,
MainApplication.class})
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,24 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.changeport.CustomApplication;
import com.baeldung.produceimage.ImageApplication;
import com.baeldung.propertyeditor.PropertyEditorApplication;
import com.baeldung.responseheaders.ResponseHeadersApplication;
import com.baeldung.sampleapp.config.MainApplication;
import com.baeldung.web.log.app.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { CustomApplication.class, ImageApplication.class, PropertyEditorApplication.class,
ResponseHeadersApplication.class, Application.class, com.baeldung.web.upload.app.UploadApplication.class,
MainApplication.class})
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,41 @@
package com.baeldung.pact;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringApplication;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import com.baeldung.sampleapp.config.MainApplication;
import au.com.dius.pact.provider.junit.PactRunner;
import au.com.dius.pact.provider.junit.Provider;
import au.com.dius.pact.provider.junit.State;
import au.com.dius.pact.provider.junit.loader.PactFolder;
import au.com.dius.pact.provider.junit.target.HttpTarget;
import au.com.dius.pact.provider.junit.target.Target;
import au.com.dius.pact.provider.junit.target.TestTarget;
@RunWith(PactRunner.class)
@Provider("test_provider")
@PactFolder("pacts")
public class PactProviderLiveTest {
@TestTarget
public final Target target = new HttpTarget("http", "localhost", 8082, "/spring-rest");
private static ConfigurableWebApplicationContext application;
@BeforeClass
public static void start() {
application = (ConfigurableWebApplicationContext) SpringApplication.run(MainApplication.class);
}
@State("test GET")
public void toGetState() {
}
@State("test POST")
public void toPostState() {
}
}
@@ -0,0 +1,41 @@
package com.baeldung.propertyeditor.creditcard;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class CreditCardEditorUnitTest {
private CreditCardEditor creditCardEditor;
@Before
public void setup() {
creditCardEditor = new CreditCardEditor();
}
@Test(expected=IllegalArgumentException.class)
public void whenInvalidCardNoWithLessDigits_thenThrowsException() {
creditCardEditor.setAsText("123-123-123-123");
}
@Test(expected=IllegalArgumentException.class)
public void whenInvalidCardNoWithNonDigits_thenThrowsException() {
creditCardEditor.setAsText("1234-1234-xxxx-yyyy");
}
@Test
public void whenCardNoWithNonDigits_parseCreditCard() {
creditCardEditor.setAsText("1234-5678-9123-4560");
CreditCard creditCard = (CreditCard) creditCardEditor.getValue();
Assert.assertNotNull(creditCard);
Assert.assertEquals(123456, creditCard.getBankIdNo().intValue());
Assert.assertEquals(789123456, creditCard.getAccountNo().intValue());
Assert.assertEquals(0, creditCard.getCheckCode().intValue());
}
}
@@ -0,0 +1,103 @@
package com.baeldung.responseheaders;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
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.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ResponseHeaderLiveTest {
private static final String BASE_URL = "http://localhost:8082/spring-rest";
private static final String SINGLE_BASE_URL = BASE_URL + "/single-response-header";
private static final String FILTER_BASE_URL = BASE_URL + "/filter-response-header";
private static final String SERVICE_SINGLE_RESPONSE_HEADER = "Baeldung-Example-Header";
private static final String SERVICE_FILTER_RESPONSE_HEADER = "Baeldung-Example-Filter-Header";
@Autowired
private TestRestTemplate template;
@Test
public void whenHttpServletResponseRequest_thenObtainResponseWithCorrectHeader() {
final String requestUrl = "/http-servlet-response";
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
HttpHeaders responseHeaders = response.getHeaders();
assertThat(responseHeaders).isNotEmpty();
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-HttpServletResponse"));
}
@Test
public void whenResponseEntityConstructorRequest_thenObtainResponseWithCorrectHeader() {
final String requestUrl = "/response-entity-constructor";
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
HttpHeaders responseHeaders = response.getHeaders();
assertThat(responseHeaders).isNotEmpty();
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityContructor"));
}
@Test
public void whenResponseEntityConstructorAndMultipleHeadersRequest_thenObtainResponseWithCorrectHeaders() {
final String requestUrl = "/response-entity-contructor-multiple-headers";
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
HttpHeaders responseHeaders = response.getHeaders();
assertThat(responseHeaders).isNotEmpty();
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityConstructorAndHeaders"));
assertThat(responseHeaders).containsEntry("Accept", Arrays.asList(MediaType.APPLICATION_JSON.toString()));
}
@Test
public void whenResponseEntityBuilderRequest_thenObtainResponseWithCorrectHeader() {
final String requestUrl = "/response-entity-builder";
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
HttpHeaders responseHeaders = response.getHeaders();
assertThat(responseHeaders).isNotEmpty();
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityBuilder"));
}
@Test
public void whenResponseEntityBuilderAndHttpHeadersRequest_thenObtainResponseWithCorrectHeader() {
final String requestUrl = "/response-entity-builder-with-http-headers";
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
HttpHeaders responseHeaders = response.getHeaders();
assertThat(responseHeaders).isNotEmpty();
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityBuilderWithHttpHeaders"));
}
@Test
public void whenFilterWithNoExtraHeaderRequest_thenObtainResponseWithCorrectHeader() {
final String requestUrl = "/no-extra-header";
ResponseEntity<String> response = template.getForEntity(FILTER_BASE_URL + requestUrl, String.class);
HttpHeaders responseHeaders = response.getHeaders();
assertThat(responseHeaders).isNotEmpty();
assertThat(responseHeaders).containsEntry(SERVICE_FILTER_RESPONSE_HEADER, Arrays.asList("Value-Filter"));
}
@Test
public void whenFilterWithExtraHeaderRequest_thenObtainResponseWithCorrectHeaders() {
final String requestUrl = "/extra-header";
ResponseEntity<String> response = template.getForEntity(FILTER_BASE_URL + requestUrl, String.class);
HttpHeaders responseHeaders = response.getHeaders();
assertThat(responseHeaders).isNotEmpty();
assertThat(responseHeaders).containsEntry(SERVICE_FILTER_RESPONSE_HEADER, Arrays.asList("Value-Filter"));
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ExtraHeader"));
}
}
@@ -0,0 +1,43 @@
package com.baeldung.resttemplate;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;
import com.baeldung.sampleapp.config.RestClientConfig;
import com.baeldung.transfer.LoginForm;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RestClientConfig.class)
public class RestTemplateLiveTest {
@Autowired
RestTemplate restTemplate;
@Test
public void givenRestTemplate_whenRequested_thenLogAndModifyResponse() {
LoginForm loginForm = new LoginForm("userName", "password");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<LoginForm> requestEntity = new HttpEntity<LoginForm>(loginForm, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://httpbin.org/post", requestEntity, String.class);
assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK)));
assertThat(responseEntity.getHeaders()
.get("Foo")
.get(0), is(equalTo("bar")));
}
}
@@ -0,0 +1,49 @@
package com.baeldung.uribuilder;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import org.junit.Test;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
public class SpringUriBuilderIntegrationTest {
@Test
public void constructUri() {
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/junit-5").build();
assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString());
}
@Test
public void constructUriEncoded() {
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/junit 5").build().encode();
assertEquals("http://www.baeldung.com/junit%205", uriComponents.toUriString());
}
@Test
public void constructUriFromTemplate() {
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/{article-name}").buildAndExpand("junit-5");
assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString());
}
@Test
public void constructUriWithQueryParameter() {
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.google.com").path("/").query("q={keyword}").buildAndExpand("baeldung");
assertEquals("http://www.google.com/?q=baeldung", uriComponents.toUriString());
}
@Test
public void expandWithRegexVar() {
String template = "/myurl/{name:[a-z]{1,5}}/show";
UriComponents uriComponents = UriComponentsBuilder.fromUriString(template).build();
uriComponents = uriComponents.expand(Collections.singletonMap("name", "test"));
assertEquals("/myurl/test/show", uriComponents.getPath());
}
}
@@ -0,0 +1,71 @@
package com.baeldung.web.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.HashMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.sampleapp.config.WebConfig;
import com.baeldung.sampleapp.web.dto.HeavyResource;
import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = WebConfig.class)
@WebAppConfiguration
public class HeavyResourceControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
private final ObjectMapper objectMapper = new ObjectMapper();
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void givenHeavyResource_whenSendPutRequest_thenCreateResource() throws Exception {
mockMvc.perform(put("/heavyresource/1")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(new HeavyResource(1, "Tom", "Jackson", 12, "heaven street")))
).andExpect(status().isOk());
}
@Test
public void givenNewAddressOfResource_whenExecutePatchRequest_thenUpdateResourcePartially() throws Exception {
mockMvc.perform(patch("/heavyresource/1")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(new HeavyResourceAddressOnly(1, "5th avenue")))
).andExpect(status().isOk());
}
@Test
public void givenNewAddressOfResource_whenExecutePatchGeneric_thenUpdateResourcePartially() throws Exception {
HashMap<String, Object> updates = new HashMap<>();
updates.put("address", "5th avenue");
mockMvc.perform(patch("/heavyresource/1")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(updates))
).andExpect(status().isOk());
}
}
@@ -0,0 +1,35 @@
package com.baeldung.web.controller;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.web.log.app.Application;
import com.baeldung.web.log.data.TaxiRide;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TaxiFareControllerIntegrationTest {
@LocalServerPort
private int port;
@Test
public void givenRequest_whenFetchTaxiFareRateCard_thanOK() {
String URL = "http://localhost:" + port + "/spring-rest";
TestRestTemplate testRestTemplate = new TestRestTemplate();
TaxiRide taxiRide = new TaxiRide(true, 10l);
String fare = testRestTemplate.postForObject(
URL + "/taxifare/calculate/",
taxiRide, String.class);
assertThat(fare, equalTo("200"));
}
}
@@ -0,0 +1,43 @@
package com.baeldung.web.controller.mediatypes;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.sampleapp.config.WebConfig;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = WebConfig.class)
@WebAppConfiguration
public class CustomMediaTypeControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void givenServiceUrl_whenGetWithProperAcceptHeaderFirstAPIVersion_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/items/1").accept("application/vnd.baeldung.api.v1+json")).andExpect(status().isOk());
}
@Test
public void givenServiceUrl_whenGetWithProperAcceptHeaderSecondVersion_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/items/2").accept("application/vnd.baeldung.api.v2+json")).andExpect(status().isOk());
}
}
@@ -0,0 +1,37 @@
package com.baeldung.web.controller.mediatypes;
import io.restassured.http.ContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static io.restassured.RestAssured.given;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class)
public class CustomMediaTypeControllerLiveTest {
private static final String URL_PREFIX = "http://localhost:8082/spring-rest";
@Test
public void givenServiceEndpoint_whenGetRequestFirstAPIVersion_thenShouldReturn200() {
given()
.accept("application/vnd.baeldung.api.v1+json")
.when()
.get(URL_PREFIX + "/public/api/items/1")
.then()
.contentType(ContentType.JSON).and().statusCode(200);
}
@Test
public void givenServiceEndpoint_whenGetRequestSecondAPIVersion_thenShouldReturn200() {
given()
.accept("application/vnd.baeldung.api.v2+json")
.when()
.get(URL_PREFIX + "/public/api/items/2")
.then()
.contentType(ContentType.JSON).and().statusCode(200);
}
}
@@ -0,0 +1,11 @@
package com.baeldung.web.controller.mediatypes;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan({ "com.baeldung.web" })
public class TestConfig {
}
@@ -0,0 +1,66 @@
package com.baeldung.web.controller.redirect;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/api-servlet.xml")
@WebAppConfiguration
public class RedirectControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
protected WebApplicationContext wac;
@Before
public void setup() {
mockMvc = webAppContextSetup(wac).build();
}
@Test
public void whenRedirectOnUrlWithUsingXMLConfig_thenStatusRedirectionAndRedirectedOnUrl() throws Exception {
mockMvc.perform(get("/redirectWithXMLConfig")).andExpect(status().is3xxRedirection()).andExpect(view().name("RedirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithXMLConfig")))
.andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithXMLConfig"));
}
@Test
public void whenRedirectOnUrlWithUsingRedirectPrefix_thenStatusRedirectionAndRedirectedOnUrl() throws Exception {
mockMvc.perform(get("/redirectWithRedirectPrefix")).andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectPrefix")))
.andExpect(redirectedUrl("/redirectedUrl?attribute=redirectWithRedirectPrefix"));
}
@Test
public void whenRedirectOnUrlWithUsingRedirectAttributes_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception {
mockMvc.perform(get("/redirectWithRedirectAttributes")).andExpect(status().is3xxRedirection()).andExpect(flash().attribute("flashAttribute", equalTo("redirectWithRedirectAttributes")))
.andExpect(model().attribute("attribute", equalTo("redirectWithRedirectAttributes"))).andExpect(model().attribute("flashAttribute", equalTo(null))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectAttributes"));
}
@Test
public void whenRedirectOnUrlWithUsingRedirectView_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception {
mockMvc.perform(get("/redirectWithRedirectView")).andExpect(status().is3xxRedirection()).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectView"))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectView"));
}
@Test
public void whenRedirectOnUrlWithUsingForwardPrefix_thenStatusOkAndForwardedOnUrl() throws Exception {
mockMvc.perform(get("/forwardWithForwardPrefix")).andExpect(status().isOk()).andExpect(view().name("forward:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithForwardPrefix"))).andExpect(forwardedUrl("/redirectedUrl"));
}
}
+13
View File
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
@@ -0,0 +1,24 @@
https://publicobject.com/helloworld.txt
GET
0
HTTP/1.1 200 OK
10
Content-Type: text/plain
Content-Length: 1759
Connection: keep-alive
Accept-Ranges: bytes
Server: nginx/1.10.0 (Ubuntu)
Date: Sat, 08 Dec 2018 13:02:07 GMT
Last-Modified: Tue, 27 May 2014 02:35:47 GMT
ETag: "5383fa03-6df"
OkHttp-Sent-Millis: 1489054646765
OkHttp-Received-Millis: 1489054646966
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
4
MIIFVTCCBD2gAwIBAgIRAKgHBM+t9Yx3v9G9tGZECWkwDQYJKoZIhvcNAQELBQAwgZAxCzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAOBgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9ETyBDQSBMaW1pdGVkMTYwNAYDVQQDEy1DT01PRE8gUlNBIERvbWFpbiBWYWxpZGF0aW9uIFNlY3VyZSBTZXJ2ZXIgQ0EwHhcNMTQxMDExMDAwMDAwWhcNMTkxMDEwMjM1OTU5WjBUMSEwHwYDVQQLExhEb21haW4gQ29udHJvbCBWYWxpZGF0ZWQxFDASBgNVBAsTC1Bvc2l0aXZlU1NMMRkwFwYDVQQDExBwdWJsaWNvYmplY3QuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjtgQtvL2kUr6ooHMOq7cxQLGycBW+ri9TGyQkO1lTb66RmcAujENxMh51wKodrveUdbqwpL4g1P49o/Y1fK5IHWAf3vpE8p3RyELY0NRlclRM24dgif/+dgRUUk+0kF3NH6MbB/kve07FMF2FyNDLxtbwJvmrn1MI5c52cpxI24vGcpOZ0VIW7+nS3V+QSrEinvrugAtu8b6Gpg+I8w6rAvmjpfCLmLP0zbjz5ExJzMC0TnR6JMgiqo2TUIyuDM2OuNJpyiluNvlUnzFrlRieg7xexoJxCbqqiOSm076fdT9qNzBp+4MzQ8w8Ofm8tsOnM4FNsz3ifX6KpJdIXfsAQIDAQABo4IB4zCCAd8wHwYDVR0jBBgwFoAUkK9qOpRaC9iQ6hJWc99DtDoo2ucwHQ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@@. '@@@@@' .@@:
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@
:@@ :@@@@@@@@@@@@@@@@@. @@:
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@@@@@@@@@@@@@@@
'@@@@@@@@@@@@@@@'
@@@@ @@@@
@@@@ @@@@
@@@@ @@@@
'@@' '@@'
:@@@.
.@@@@@@@: +@@ `@@ @@` @@ @@
.@@@@'@@@@: +@@ `@@ @@` @@ @@
@@@ @@@ +@@ `@@ @@` @@ @@
.@@ @@: +@@ @@@ `@@ @@` @@@@@@ @@@@@@ @@;@@@@@
@@@ @@@ +@@ @@@ `@@ @@` @@@@@@ @@@@@@ @@@@@@@@@
@@@ @@@ +@@ @@@ `@@@@@@@@@@` @@ @@ @@@ :@@
@@@ @@@ +@@@@@ `@@@@@@@@@@` @@ @@ @@# @@+
@@@ @@@ +@@@@@+ `@@ @@` @@ @@ @@: @@#
@@: .@@` +@@@+@@ `@@ @@` @@ @@ @@# @@+
@@@. .@@@ +@@ @@@ `@@ @@` @@ @@ @@@ ,@@
@@@@@@@@@ +@@ @@@ `@@ @@` @@@@ @@@@ @@@@#@@@@
@@@@@@@ +@@ #@@ `@@ @@` @@@@: @@@@: @@'@@@@@
@@:
@@:
@@:
@@ -0,0 +1,13 @@
http://publicobject.com/helloworld.txt
GET
0
HTTP/1.1 301 Moved Permanently
8
Server: nginx/1.10.0 (Ubuntu)
Date: Sat, 08 Dec 2018 13:02:04 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: https://publicobject.com/helloworld.txt
OkHttp-Sent-Millis: 1544274128028
OkHttp-Received-Millis: 1544274128386
@@ -0,0 +1,7 @@
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.10.0 (Ubuntu)</center>
</body>
</html>
+75
View File
@@ -0,0 +1,75 @@
libcore.io.DiskLruCache
1
201105
2
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
DIRTY 2d9345a30d2cc31bb3091d70a8ef6c18
CLEAN 2d9345a30d2cc31bb3091d70a8ef6c18 7618 1759
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 2d9345a30d2cc31bb3091d70a8ef6c18
DIRTY 2d9345a30d2cc31bb3091d70a8ef6c18
CLEAN 2d9345a30d2cc31bb3091d70a8ef6c18 7618 1759
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 2d9345a30d2cc31bb3091d70a8ef6c18
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 2d9345a30d2cc31bb3091d70a8ef6c18
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 2d9345a30d2cc31bb3091d70a8ef6c18
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 2d9345a30d2cc31bb3091d70a8ef6c18
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 2d9345a30d2cc31bb3091d70a8ef6c18
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 2d9345a30d2cc31bb3091d70a8ef6c18
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 2d9345a30d2cc31bb3091d70a8ef6c18
DIRTY 2d9345a30d2cc31bb3091d70a8ef6c18
CLEAN 2d9345a30d2cc31bb3091d70a8ef6c18 7618 1759
READ 4b217e04ba52215f3a6b64d28f6729c6
DIRTY 4b217e04ba52215f3a6b64d28f6729c6
CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194
READ 2d9345a30d2cc31bb3091d70a8ef6c18
DIRTY 2d9345a30d2cc31bb3091d70a8ef6c18
CLEAN 2d9345a30d2cc31bb3091d70a8ef6c18 7618 1759
+1
View File
@@ -0,0 +1 @@
hello world