Merge pull request #8038 from sjmillington/rest-move-1

[BAEL-18364] move spring-rest-*** articles - 1
This commit is contained in:
Josh Cummings 2019-11-05 21:37:55 -07:00 committed by GitHub
commit 6a6b58a280
83 changed files with 437 additions and 292 deletions

View File

@ -12,8 +12,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
- [Integration Testing with the Maven Cargo plugin](https://www.baeldung.com/integration-testing-with-the-maven-cargo-plugin)
- [Project Configuration with Spring](https://www.baeldung.com/project-configuration-with-spring)
- [Metrics for your Spring REST API](https://www.baeldung.com/spring-rest-api-metrics)
- [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic)
### Build the Project
```

View File

@ -10,16 +10,11 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Returning Custom Status Codes from Spring Controllers](https://www.baeldung.com/spring-mvc-controller-custom-http-status-code)
- [Binary Data Formats in a Spring REST API](https://www.baeldung.com/spring-rest-api-with-binary-data-formats)
- [Guide to UriComponentsBuilder in Spring](https://www.baeldung.com/spring-uricomponentsbuilder)
- [Introduction to FindBugs](https://www.baeldung.com/intro-to-findbugs)
- [A Custom Media Type for a Spring REST API](https://www.baeldung.com/spring-rest-custom-media-type)
- [HTTP PUT vs HTTP PATCH in a REST API](https://www.baeldung.com/http-put-patch-difference-spring)
- [Spring Log Incoming Requests](https://www.baeldung.com/spring-http-logging)
- [Introduction to CheckStyle](https://www.baeldung.com/checkstyle-java)
- [How to Change the Default Port in Spring Boot](https://www.baeldung.com/spring-boot-change-port)
- [Guide to DeferredResult in Spring](https://www.baeldung.com/spring-deferred-result)
- [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor)
- [Using the Spring RestTemplate Interceptor](https://www.baeldung.com/spring-rest-template-interceptor)
- [Get and Post Lists of Objects with RestTemplate](https://www.baeldung.com/spring-rest-template-list)
- [How to Set a Header on a Response with Spring 5](https://www.baeldung.com/spring-response-header)
- [Uploading MultipartFile with Spring RestTemplate](https://www.baeldung.com/spring-rest-template-multipart-upload)
- [Download an Image or a File with Spring MVC](https://www.baeldung.com/spring-controller-return-image-file)

View File

@ -20,10 +20,7 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
@ -141,11 +138,7 @@
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>au.com.dius</groupId>
<artifactId>pact-jvm-provider-junit_2.11</artifactId>
<version>${pact.version}</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
@ -176,21 +169,7 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle-maven-plugin.version}</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
@ -250,18 +229,7 @@
</profiles>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle-maven-plugin.version}</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
</configuration>
</plugin>
</plugins>
</reporting>
<properties>
<commons-fileupload.version>1.3.2</commons-fileupload.version>
@ -275,7 +243,7 @@
<!-- Maven plugins -->
<cargo-maven2-plugin.version>1.6.0</cargo-maven2-plugin.version>
<findbugs-maven-plugin.version>3.0.4</findbugs-maven-plugin.version>
<checkstyle-maven-plugin.version>3.0.0</checkstyle-maven-plugin.version>
<dependency.locations.enabled>false</dependency.locations.enabled>
<json.path.version>2.2.0</json.path.version>

View File

@ -13,4 +13,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Mocking a RestTemplate in Spring](https://www.baeldung.com/spring-mock-rest-template)
- [RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json)
- [Download a Large File Through a Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-download-large-file)
- [Using the Spring RestTemplate Interceptor](https://www.baeldung.com/spring-rest-template-interceptor)
- [Uploading MultipartFile with Spring RestTemplate](https://www.baeldung.com/spring-rest-template-multipart-upload)
- [Get and Post Lists of Objects with RestTemplate](https://www.baeldung.com/spring-rest-template-list)
- [Copy of RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json-test)

View File

@ -21,6 +21,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
@ -32,7 +36,13 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>au.com.dius</groupId>
<artifactId>pact-jvm-provider-junit_2.11</artifactId>
<version>${pact.version}</version>
</dependency>
<!-- Spring -->
@ -111,11 +121,13 @@
<!-- test scoped -->
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
@ -295,6 +307,7 @@
<!-- okhttp -->
<com.squareup.okhttp3.version>3.4.1</com.squareup.okhttp3.version>
<pact.version>3.5.11</pact.version>
</properties>
</project>

View File

@ -1,29 +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;
}
}
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;
}
}

View File

@ -1,18 +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;
}
}
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;
}
}

View File

@ -1,44 +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());
}
}
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());
}
}

View File

@ -1,20 +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;
}
}
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;
}
}

View File

@ -1,19 +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/**/");
}
}
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/**/");
}
}

View File

@ -1,31 +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;
}
}
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;
}
}

View File

@ -1,33 +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;
}
}
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;
}
}

View File

@ -1,14 +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));
}
}
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));
}
}

View File

@ -1,38 +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;
}
}
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;
}
}

View File

@ -15,3 +15,4 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
- [Servlet 3 Async Support with Spring MVC and Spring Security](https://www.baeldung.com/spring-mvc-async-security)
- [Intro to Spring Security Expressions](https://www.baeldung.com/spring-security-expressions)
- [Spring Security for a REST API](https://www.baeldung.com/securing-a-restful-web-service-with-spring-security)
- [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic)

View File

@ -6,5 +6,7 @@
- [Cucumber and Scenario Outline](http://www.baeldung.com/cucumber-scenario-outline)
- [Cucumber Java 8 Support](http://www.baeldung.com/cucumber-java-8-support)
- [Introduction to Lambda Behave](http://www.baeldung.com/lambda-behave)
- [Introduction to CheckStyle](https://www.baeldung.com/checkstyle-java)
- [Introduction to FindBugs](https://www.baeldung.com/intro-to-findbugs)

View File

@ -35,11 +35,60 @@
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>testing-libraries</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle-maven-plugin.version}</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle-maven-plugin.version}</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
</configuration>
</plugin>
</plugins>
</reporting>
<properties>
<lambda-behave.version>0.4</lambda-behave.version>
<cucumber.version>1.2.5</cucumber.version>
<checkstyle-maven-plugin.version>3.0.0</checkstyle-maven-plugin.version>
</properties>

View File

@ -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.";
}
}
}

View File

@ -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;
}
}