move query language to new module (#2864)

* move security content from spring-security-rest-full

* swagger update

* move query language to new module

* rename spring-security-rest-full to spring-rest-full
This commit is contained in:
Doha2012
2017-10-25 19:39:04 +03:00
committed by Grzegorz Piwowarek
parent 864c2e2190
commit 1c9477390d
111 changed files with 1048 additions and 148 deletions

13
spring-rest-full/.gitignore vendored Normal file
View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@@ -0,0 +1,44 @@
=========
## REST Example Project with Spring
### Courses
The "REST With Spring" Classes: http://bit.ly/restwithspring
The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
### Relevant Articles:
- [REST Pagination in Spring](http://www.baeldung.com/2012/01/18/rest-pagination-in-spring/)
- [HATEOAS for a Spring REST Service](http://www.baeldung.com/2011/11/13/rest-service-discoverability-with-spring-part-5/)
- [REST API Discoverability and HATEOAS](http://www.baeldung.com/2011/11/06/restful-web-service-discoverability-part-4/)
- [ETags for REST with Spring](http://www.baeldung.com/2013/01/11/etags-for-rest-with-spring/)
- [Integration Testing with the Maven Cargo plugin](http://www.baeldung.com/2011/10/16/how-to-set-up-integration-testing-with-the-maven-cargo-plugin/)
- [Introduction to Spring Data JPA](http://www.baeldung.com/2011/12/22/the-persistence-layer-with-spring-data-jpa/)
- [Project Configuration with Spring](http://www.baeldung.com/2012/03/12/project-configuration-with-spring/)
- [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics)
- [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template)
- [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration)
### Build the Project
```
mvn clean install
```
### Set up MySQL
```
mysql -u root -p
> CREATE USER 'tutorialuser'@'localhost' IDENTIFIED BY 'tutorialmy5ql';
> GRANT ALL PRIVILEGES ON *.* TO 'tutorialuser'@'localhost';
> FLUSH PRIVILEGES;
```
### Use the REST Service
```
curl http://localhost:8080/spring-rest-full/foos
```

378
spring-rest-full/pom.xml Normal file
View File

@@ -0,0 +1,378 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-rest-full</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-rest-full</name>
<packaging>war</packaging>
<parent>
<artifactId>parent-boot-4</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-4</relativePath>
</parent>
<dependencies>
<!-- Spring Boot Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<!-- deployment -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- web -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>runtime</scope>
</dependency>
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>${xstream.version}</version>
</dependency>
<!-- util -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.hamcrest</groupId> -->
<!-- <artifactId>hamcrest-core</artifactId> -->
<!-- <scope>test</scope> -->
<!-- </dependency> -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-rest-full</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
<!-- Querydsl and Specifications -->
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>${apt-maven-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<configuration>
<wait>false</wait>
</configuration>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- various -->
<xstream.version>1.4.9</xstream.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<!-- Maven plugins -->
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
<apt-maven-plugin.version>1.1.3</apt-maven-plugin.version>
</properties>
</project>

View File

@@ -0,0 +1,30 @@
package org.baeldung.persistence;
import java.io.Serializable;
import java.util.List;
import org.springframework.data.domain.Page;
public interface IOperations<T extends Serializable> {
// read - one
T findOne(final long id);
// read - all
List<T> findAll();
Page<T> findPaginated(int page, int size);
// write
T create(final T entity);
T update(final T entity);
void delete(final T entity);
void deleteById(final long entityId);
}

View File

@@ -0,0 +1,11 @@
package org.baeldung.persistence.dao;
import org.baeldung.persistence.model.Foo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface IFooDao extends JpaRepository<Foo, Long> {
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
Foo retrieveByName(@Param("name") String name);
}

View File

@@ -0,0 +1,83 @@
package org.baeldung.persistence.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Foo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String name;
public Foo() {
super();
}
public Foo(final String name) {
super();
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;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
}

View File

@@ -0,0 +1,94 @@
package org.baeldung.persistence.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
private int age;
public User() {
super();
}
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(final String username) {
email = username;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final User user = (User) obj;
return email.equals(user.email);
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]");
return builder.toString();
}
}

View File

@@ -0,0 +1,14 @@
package org.baeldung.persistence.service;
import org.baeldung.persistence.IOperations;
import org.baeldung.persistence.model.Foo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface IFooService extends IOperations<Foo> {
Foo retrieveByName(String name);
Page<Foo> findPaginated(Pageable pageable);
}

View File

@@ -0,0 +1,62 @@
package org.baeldung.persistence.service.common;
import java.io.Serializable;
import java.util.List;
import org.baeldung.persistence.IOperations;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
@Transactional
public abstract class AbstractService<T extends Serializable> implements IOperations<T> {
// read - one
@Override
@Transactional(readOnly = true)
public T findOne(final long id) {
return getDao().findOne(id);
}
// read - all
@Override
@Transactional(readOnly = true)
public List<T> findAll() {
return Lists.newArrayList(getDao().findAll());
}
@Override
public Page<T> findPaginated(final int page, final int size) {
return getDao().findAll(new PageRequest(page, size));
}
// write
@Override
public T create(final T entity) {
return getDao().save(entity);
}
@Override
public T update(final T entity) {
return getDao().save(entity);
}
@Override
public void delete(final T entity) {
getDao().delete(entity);
}
@Override
public void deleteById(final long entityId) {
getDao().delete(entityId);
}
protected abstract PagingAndSortingRepository<T, Long> getDao();
}

View File

@@ -0,0 +1,56 @@
package org.baeldung.persistence.service.impl;
import java.util.List;
import org.baeldung.persistence.dao.IFooDao;
import org.baeldung.persistence.model.Foo;
import org.baeldung.persistence.service.IFooService;
import org.baeldung.persistence.service.common.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
@Service
@Transactional
public class FooService extends AbstractService<Foo> implements IFooService {
@Autowired
private IFooDao dao;
public FooService() {
super();
}
// API
@Override
protected PagingAndSortingRepository<Foo, Long> getDao() {
return dao;
}
// custom methods
@Override
public Foo retrieveByName(final String name) {
return dao.retrieveByName(name);
}
// overridden to be secured
@Override
@Transactional(readOnly = true)
public List<Foo> findAll() {
return Lists.newArrayList(getDao().findAll());
}
@Override
public Page<Foo> findPaginated(Pageable pageable) {
return dao.findAll(pageable);
}
}

View File

@@ -0,0 +1,47 @@
package org.baeldung.spring;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.filter.ShallowEtagHeaderFilter;
/**
* Main Application Class - uses Spring Boot. Just run this as a normal Java
* class to run up a Jetty Server (on http://localhost:8082/spring-rest-full)
*
*/
@EnableScheduling
@EnableAutoConfiguration
@ComponentScan("org.baeldung")
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
@Override
public void onStartup(ServletContext sc) throws ServletException {
// Manages the lifecycle of the root application context
sc.addListener(new RequestContextListener());
}
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public ShallowEtagHeaderFilter shallowEtagHeaderFilter() {
return new ShallowEtagHeaderFilter();
}
}

View File

@@ -0,0 +1,85 @@
package org.baeldung.spring;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" })
@ComponentScan({ "org.baeldung.persistence" })
// @ImportResource("classpath*:springDataPersistenceConfig.xml")
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
public class PersistenceConfig {
@Autowired
private Environment env;
public PersistenceConfig() {
super();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
// vendorAdapter.set
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
return hibernateProperties;
}
}

View File

@@ -0,0 +1,37 @@
package org.baeldung.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan("org.baeldung.web")
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
public WebConfig() {
super();
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
// API
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/graph.html");
registry.addViewController("/homepage.html");
}
}

View File

@@ -0,0 +1,135 @@
package org.baeldung.web.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.baeldung.persistence.model.Foo;
import org.baeldung.persistence.service.IFooService;
import org.baeldung.web.exception.MyResourceNotFoundException;
import org.baeldung.web.hateoas.event.PaginatedResultsRetrievedEvent;
import org.baeldung.web.hateoas.event.ResourceCreatedEvent;
import org.baeldung.web.hateoas.event.SingleResourceRetrievedEvent;
import org.baeldung.web.util.RestPreconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.util.UriComponentsBuilder;
import com.google.common.base.Preconditions;
@Controller
@RequestMapping(value = "/auth/foos")
public class FooController {
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private IFooService service;
public FooController() {
super();
}
// API
@RequestMapping(method = RequestMethod.GET, value = "/count")
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
public long count() {
return 2l;
}
// read - one
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
return resourceById;
}
// read - all
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public List<Foo> findAll() {
return service.findAll();
}
@RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
@ResponseBody
public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
final Page<Foo> resultPage = service.findPaginated(page, size);
if (page > resultPage.getTotalPages()) {
throw new MyResourceNotFoundException();
}
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));
return resultPage.getContent();
}
@GetMapping("/pageable")
@ResponseBody
public List<Foo> findPaginatedWithPageable(Pageable pageable, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
final Page<Foo> resultPage = service.findPaginated(pageable);
if (pageable.getPageNumber() > resultPage.getTotalPages()) {
throw new MyResourceNotFoundException();
}
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, pageable.getPageNumber(), resultPage.getTotalPages(), pageable.getPageSize()));
return resultPage.getContent();
}
// write
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
Preconditions.checkNotNull(resource);
final Foo foo = service.create(resource);
final Long idOfCreatedResource = foo.getId();
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
return foo;
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
Preconditions.checkNotNull(resource);
RestPreconditions.checkFound(service.findOne(resource.getId()));
service.update(resource);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable("id") final Long id) {
service.deleteById(id);
}
@RequestMapping(method = RequestMethod.HEAD)
@ResponseStatus(HttpStatus.OK)
public void head(final HttpServletResponse resp) {
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
resp.setHeader("bar", "baz");
}
}

View File

@@ -0,0 +1,14 @@
package org.baeldung.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/")
public class HomeController {
public String index() {
return "homepage";
}
}

View File

@@ -0,0 +1,72 @@
package org.baeldung.web.controller;
import java.net.URI;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.baeldung.web.metric.IActuatorMetricService;
import org.baeldung.web.metric.IMetricService;
import org.baeldung.web.util.LinkUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
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.util.UriTemplate;
@Controller
@RequestMapping(value = "/auth/")
public class RootController {
@Autowired
private IMetricService metricService;
@Autowired
private IActuatorMetricService actMetricService;
public RootController() {
super();
}
// API
// discover
@RequestMapping(value = "admin", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
final String rootUri = request.getRequestURL().toString();
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
response.addHeader("Link", linkToFoo);
}
@RequestMapping(value = "/metric", method = RequestMethod.GET)
@ResponseBody
public Map getMetric() {
return metricService.getFullMetric();
}
@RequestMapping(value = "/status-metric", method = RequestMethod.GET)
@ResponseBody
public Map getStatusMetric() {
return metricService.getStatusMetric();
}
@RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
@ResponseBody
public Object[][] drawMetric() {
final Object[][] result = metricService.getGraphData();
for (int i = 1; i < result[0].length; i++) {
result[0][i] = result[0][i].toString();
}
return result;
}
}

View File

@@ -0,0 +1,84 @@
package org.baeldung.web.error;
import javax.persistence.EntityNotFoundException;
import org.baeldung.web.exception.MyResourceNotFoundException;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
public RestResponseEntityExceptionHandler() {
super();
}
// API
// 400
@ExceptionHandler({ ConstraintViolationException.class })
public ResponseEntity<Object> handleBadRequest(final ConstraintViolationException ex, final WebRequest request) {
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
@ExceptionHandler({ DataIntegrityViolationException.class })
public ResponseEntity<Object> handleBadRequest(final DataIntegrityViolationException ex, final WebRequest request) {
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
final String bodyOfResponse = "This should be application specific";
// ex.getCause() instanceof JsonMappingException, JsonParseException // for additional information later on
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
// 404
@ExceptionHandler(value = { EntityNotFoundException.class, MyResourceNotFoundException.class })
protected ResponseEntity<Object> handleNotFound(final RuntimeException ex, final WebRequest request) {
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
// 409
@ExceptionHandler({ InvalidDataAccessApiUsageException.class, DataAccessException.class })
protected ResponseEntity<Object> handleConflict(final RuntimeException ex, final WebRequest request) {
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request);
}
// 412
// 500
@ExceptionHandler({ NullPointerException.class, IllegalArgumentException.class, IllegalStateException.class })
/*500*/public ResponseEntity<Object> handleInternal(final RuntimeException ex, final WebRequest request) {
logger.error("500 Status Code", ex);
final String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
}
}

View File

@@ -0,0 +1,21 @@
package org.baeldung.web.exception;
public final class MyResourceNotFoundException extends RuntimeException {
public MyResourceNotFoundException() {
super();
}
public MyResourceNotFoundException(final String message, final Throwable cause) {
super(message, cause);
}
public MyResourceNotFoundException(final String message) {
super(message);
}
public MyResourceNotFoundException(final Throwable cause) {
super(cause);
}
}

View File

@@ -0,0 +1,67 @@
package org.baeldung.web.hateoas.event;
import java.io.Serializable;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEvent;
import org.springframework.web.util.UriComponentsBuilder;
/**
* Event that is fired when a paginated search is performed.
* <p/>
* This event object contains all the information needed to create the URL for the paginated results
*
* @param <T>
* Type of the result that is being handled (commonly Entities).
*/
public final class PaginatedResultsRetrievedEvent<T extends Serializable> extends ApplicationEvent {
private final UriComponentsBuilder uriBuilder;
private final HttpServletResponse response;
private final int page;
private final int totalPages;
private final int pageSize;
public PaginatedResultsRetrievedEvent(final Class<T> clazz, final UriComponentsBuilder uriBuilderToSet, final HttpServletResponse responseToSet, final int pageToSet, final int totalPagesToSet, final int pageSizeToSet) {
super(clazz);
uriBuilder = uriBuilderToSet;
response = responseToSet;
page = pageToSet;
totalPages = totalPagesToSet;
pageSize = pageSizeToSet;
}
// API
public final UriComponentsBuilder getUriBuilder() {
return uriBuilder;
}
public final HttpServletResponse getResponse() {
return response;
}
public final int getPage() {
return page;
}
public final int getTotalPages() {
return totalPages;
}
public final int getPageSize() {
return pageSize;
}
/**
* The object on which the Event initially occurred.
*
* @return The object on which the Event initially occurred.
*/
@SuppressWarnings("unchecked")
public final Class<T> getClazz() {
return (Class<T>) getSource();
}
}

View File

@@ -0,0 +1,28 @@
package org.baeldung.web.hateoas.event;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEvent;
public class ResourceCreatedEvent extends ApplicationEvent {
private final HttpServletResponse response;
private final long idOfNewResource;
public ResourceCreatedEvent(final Object source, final HttpServletResponse response, final long idOfNewResource) {
super(source);
this.response = response;
this.idOfNewResource = idOfNewResource;
}
// API
public HttpServletResponse getResponse() {
return response;
}
public long getIdOfNewResource() {
return idOfNewResource;
}
}

View File

@@ -0,0 +1,22 @@
package org.baeldung.web.hateoas.event;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEvent;
public class SingleResourceRetrievedEvent extends ApplicationEvent {
private final HttpServletResponse response;
public SingleResourceRetrievedEvent(final Object source, final HttpServletResponse response) {
super(source);
this.response = response;
}
// API
public HttpServletResponse getResponse() {
return response;
}
}

View File

@@ -0,0 +1,108 @@
package org.baeldung.web.hateoas.listener;
import javax.servlet.http.HttpServletResponse;
import org.baeldung.web.hateoas.event.PaginatedResultsRetrievedEvent;
import org.baeldung.web.util.LinkUtil;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
@SuppressWarnings({ "rawtypes" })
@Component
class PaginatedResultsRetrievedDiscoverabilityListener implements ApplicationListener<PaginatedResultsRetrievedEvent> {
private static final String PAGE = "page";
public PaginatedResultsRetrievedDiscoverabilityListener() {
super();
}
// API
@Override
public final void onApplicationEvent(final PaginatedResultsRetrievedEvent ev) {
Preconditions.checkNotNull(ev);
addLinkHeaderOnPagedResourceRetrieval(ev.getUriBuilder(), ev.getResponse(), ev.getClazz(), ev.getPage(), ev.getTotalPages(), ev.getPageSize());
}
// - note: at this point, the URI is transformed into plural (added `s`) in a hardcoded way - this will change in the future
final void addLinkHeaderOnPagedResourceRetrieval(final UriComponentsBuilder uriBuilder, final HttpServletResponse response, final Class clazz, final int page, final int totalPages, final int pageSize) {
plural(uriBuilder, clazz);
final StringBuilder linkHeader = new StringBuilder();
if (hasNextPage(page, totalPages)) {
final String uriForNextPage = constructNextPageUri(uriBuilder, page, pageSize);
linkHeader.append(LinkUtil.createLinkHeader(uriForNextPage, LinkUtil.REL_NEXT));
}
if (hasPreviousPage(page)) {
final String uriForPrevPage = constructPrevPageUri(uriBuilder, page, pageSize);
appendCommaIfNecessary(linkHeader);
linkHeader.append(LinkUtil.createLinkHeader(uriForPrevPage, LinkUtil.REL_PREV));
}
if (hasFirstPage(page)) {
final String uriForFirstPage = constructFirstPageUri(uriBuilder, pageSize);
appendCommaIfNecessary(linkHeader);
linkHeader.append(LinkUtil.createLinkHeader(uriForFirstPage, LinkUtil.REL_FIRST));
}
if (hasLastPage(page, totalPages)) {
final String uriForLastPage = constructLastPageUri(uriBuilder, totalPages, pageSize);
appendCommaIfNecessary(linkHeader);
linkHeader.append(LinkUtil.createLinkHeader(uriForLastPage, LinkUtil.REL_LAST));
}
if (linkHeader.length() > 0) {
response.addHeader(HttpHeaders.LINK, linkHeader.toString());
}
}
final String constructNextPageUri(final UriComponentsBuilder uriBuilder, final int page, final int size) {
return uriBuilder.replaceQueryParam(PAGE, page + 1).replaceQueryParam("size", size).build().encode().toUriString();
}
final String constructPrevPageUri(final UriComponentsBuilder uriBuilder, final int page, final int size) {
return uriBuilder.replaceQueryParam(PAGE, page - 1).replaceQueryParam("size", size).build().encode().toUriString();
}
final String constructFirstPageUri(final UriComponentsBuilder uriBuilder, final int size) {
return uriBuilder.replaceQueryParam(PAGE, 0).replaceQueryParam("size", size).build().encode().toUriString();
}
final String constructLastPageUri(final UriComponentsBuilder uriBuilder, final int totalPages, final int size) {
return uriBuilder.replaceQueryParam(PAGE, totalPages).replaceQueryParam("size", size).build().encode().toUriString();
}
final boolean hasNextPage(final int page, final int totalPages) {
return page < (totalPages - 1);
}
final boolean hasPreviousPage(final int page) {
return page > 0;
}
final boolean hasFirstPage(final int page) {
return hasPreviousPage(page);
}
final boolean hasLastPage(final int page, final int totalPages) {
return (totalPages > 1) && hasNextPage(page, totalPages);
}
final void appendCommaIfNecessary(final StringBuilder linkHeader) {
if (linkHeader.length() > 0) {
linkHeader.append(", ");
}
}
// template
protected void plural(final UriComponentsBuilder uriBuilder, final Class clazz) {
final String resourceName = clazz.getSimpleName().toLowerCase() + "s";
uriBuilder.path("/auth/" + resourceName);
}
}

View File

@@ -0,0 +1,36 @@
package org.baeldung.web.hateoas.listener;
import java.net.URI;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpHeaders;
import org.baeldung.web.hateoas.event.ResourceCreatedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.google.common.base.Preconditions;
@Component
class ResourceCreatedDiscoverabilityListener implements ApplicationListener<ResourceCreatedEvent> {
@Override
public void onApplicationEvent(final ResourceCreatedEvent resourceCreatedEvent) {
Preconditions.checkNotNull(resourceCreatedEvent);
final HttpServletResponse response = resourceCreatedEvent.getResponse();
final long idOfNewResource = resourceCreatedEvent.getIdOfNewResource();
addLinkHeaderOnResourceCreation(response, idOfNewResource);
}
void addLinkHeaderOnResourceCreation(final HttpServletResponse response, final long idOfNewResource) {
// final String requestUrl = request.getRequestURL().toString();
// final URI uri = new UriTemplate("{requestUrl}/{idOfNewResource}").expand(requestUrl, idOfNewResource);
final URI uri = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/{idOfNewResource}").buildAndExpand(idOfNewResource).toUri();
response.setHeader(HttpHeaders.LOCATION, uri.toASCIIString());
}
}

View File

@@ -0,0 +1,34 @@
package org.baeldung.web.hateoas.listener;
import javax.servlet.http.HttpServletResponse;
import org.baeldung.web.hateoas.event.SingleResourceRetrievedEvent;
import org.baeldung.web.util.LinkUtil;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
@Component
class SingleResourceRetrievedDiscoverabilityListener implements ApplicationListener<SingleResourceRetrievedEvent> {
@Override
public void onApplicationEvent(final SingleResourceRetrievedEvent resourceRetrievedEvent) {
Preconditions.checkNotNull(resourceRetrievedEvent);
final HttpServletResponse response = resourceRetrievedEvent.getResponse();
addLinkHeaderOnSingleResourceRetrieval(response);
}
void addLinkHeaderOnSingleResourceRetrieval(final HttpServletResponse response) {
final String requestURL = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri().toASCIIString();
final int positionOfLastSlash = requestURL.lastIndexOf("/");
final String uriForResourceCreation = requestURL.substring(0, positionOfLastSlash);
final String linkHeaderValue = LinkUtil.createLinkHeader(uriForResourceCreation, "collection");
response.addHeader(HttpHeaders.LINK, linkHeaderValue);
}
}

View File

@@ -0,0 +1,108 @@
package org.baeldung.web.metric;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.MetricReaderPublicMetrics;
import org.springframework.boot.actuate.metrics.Metric;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ActuatorMetricService implements IActuatorMetricService {
@Autowired
private MetricReaderPublicMetrics publicMetrics;
private final List<ArrayList<Integer>> statusMetricsByMinute;
private final List<String> statusList;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public ActuatorMetricService() {
super();
statusMetricsByMinute = new ArrayList<ArrayList<Integer>>();
statusList = new ArrayList<String>();
}
@Override
public Object[][] getGraphData() {
final Date current = new Date();
final int colCount = statusList.size() + 1;
final int rowCount = statusMetricsByMinute.size() + 1;
final Object[][] result = new Object[rowCount][colCount];
result[0][0] = "Time";
int j = 1;
for (final String status : statusList) {
result[0][j] = status;
j++;
}
for (int i = 1; i < rowCount; i++) {
result[i][0] = dateFormat.format(new Date(current.getTime() - (60000 * (rowCount - i))));
}
List<Integer> minuteOfStatuses;
List<Integer> last = new ArrayList<Integer>();
for (int i = 1; i < rowCount; i++) {
minuteOfStatuses = statusMetricsByMinute.get(i - 1);
for (j = 1; j <= minuteOfStatuses.size(); j++) {
result[i][j] = minuteOfStatuses.get(j - 1) - (last.size() >= j ? last.get(j - 1) : 0);
}
while (j < colCount) {
result[i][j] = 0;
j++;
}
last = minuteOfStatuses;
}
return result;
}
// Non - API
@Scheduled(fixedDelay = 60000)
private void exportMetrics() {
final ArrayList<Integer> lastMinuteStatuses = initializeStatuses(statusList.size());
for (final Metric<?> counterMetric : publicMetrics.metrics()) {
updateMetrics(counterMetric, lastMinuteStatuses);
}
statusMetricsByMinute.add(lastMinuteStatuses);
}
private ArrayList<Integer> initializeStatuses(final int size) {
final ArrayList<Integer> counterList = new ArrayList<Integer>();
for (int i = 0; i < size; i++) {
counterList.add(0);
}
return counterList;
}
private void updateMetrics(final Metric<?> counterMetric, final ArrayList<Integer> statusCount) {
String status = "";
int index = -1;
int oldCount = 0;
if (counterMetric.getName().contains("counter.status.")) {
status = counterMetric.getName().substring(15, 18); // example 404, 200
appendStatusIfNotExist(status, statusCount);
index = statusList.indexOf(status);
oldCount = statusCount.get(index) == null ? 0 : statusCount.get(index);
statusCount.set(index, counterMetric.getValue().intValue() + oldCount);
}
}
private void appendStatusIfNotExist(final String status, final ArrayList<Integer> statusCount) {
if (!statusList.contains(status)) {
statusList.add(status);
statusCount.add(0);
}
}
//
}

View File

@@ -0,0 +1,95 @@
package org.baeldung.web.metric;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.Metric;
import org.springframework.boot.actuate.metrics.repository.InMemoryMetricRepository;
import org.springframework.boot.actuate.metrics.repository.MetricRepository;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class CustomActuatorMetricService implements ICustomActuatorMetricService {
private MetricRepository repo;
@Autowired
private CounterService counter;
private final List<ArrayList<Integer>> statusMetricsByMinute;
private final List<String> statusList;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public CustomActuatorMetricService() {
super();
repo = new InMemoryMetricRepository();
statusMetricsByMinute = new ArrayList<ArrayList<Integer>>();
statusList = new ArrayList<String>();
}
// API
@Override
public void increaseCount(final int status) {
counter.increment("status." + status);
if (!statusList.contains("counter.status." + status)) {
statusList.add("counter.status." + status);
}
}
@Override
public Object[][] getGraphData() {
final Date current = new Date();
final int colCount = statusList.size() + 1;
final int rowCount = statusMetricsByMinute.size() + 1;
final Object[][] result = new Object[rowCount][colCount];
result[0][0] = "Time";
int j = 1;
for (final String status : statusList) {
result[0][j] = status;
j++;
}
for (int i = 1; i < rowCount; i++) {
result[i][0] = dateFormat.format(new Date(current.getTime() - (60000 * (rowCount - i))));
}
List<Integer> minuteOfStatuses;
for (int i = 1; i < rowCount; i++) {
minuteOfStatuses = statusMetricsByMinute.get(i - 1);
for (j = 1; j <= minuteOfStatuses.size(); j++) {
result[i][j] = minuteOfStatuses.get(j - 1);
}
while (j < colCount) {
result[i][j] = 0;
j++;
}
}
return result;
}
// Non - API
@Scheduled(fixedDelay = 60000)
private void exportMetrics() {
Metric<?> metric;
final ArrayList<Integer> statusCount = new ArrayList<Integer>();
for (final String status : statusList) {
metric = repo.findOne(status);
if (metric != null) {
statusCount.add(metric.getValue().intValue());
repo.reset(status);
} else {
statusCount.add(0);
}
}
statusMetricsByMinute.add(statusCount);
}
}

View File

@@ -0,0 +1,5 @@
package org.baeldung.web.metric;
public interface IActuatorMetricService {
Object[][] getGraphData();
}

View File

@@ -0,0 +1,8 @@
package org.baeldung.web.metric;
public interface ICustomActuatorMetricService {
void increaseCount(final int status);
Object[][] getGraphData();
}

View File

@@ -0,0 +1,14 @@
package org.baeldung.web.metric;
import java.util.Map;
public interface IMetricService {
void increaseCount(final String request, final int status);
Map getFullMetric();
Map getStatusMetric();
Object[][] getGraphData();
}

View File

@@ -0,0 +1,49 @@
package org.baeldung.web.metric;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
@Component
public class MetricFilter implements Filter {
@Autowired
private IMetricService metricService;
@Autowired
private ICustomActuatorMetricService actMetricService;
@Override
public void init(final FilterConfig config) throws ServletException {
if (metricService == null || actMetricService == null) {
metricService = (IMetricService) WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean("metricService");
actMetricService = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean(CustomActuatorMetricService.class);
}
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws java.io.IOException, ServletException {
final HttpServletRequest httpRequest = ((HttpServletRequest) request);
final String req = httpRequest.getMethod() + " " + httpRequest.getRequestURI();
chain.doFilter(request, response);
final int status = ((HttpServletResponse) response).getStatus();
metricService.increaseCount(req, status);
actMetricService.increaseCount(status);
}
@Override
public void destroy() {
}
}

View File

@@ -0,0 +1,122 @@
package org.baeldung.web.metric;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.stereotype.Service;
@Service
public class MetricService implements IMetricService {
private ConcurrentMap<String, ConcurrentHashMap<Integer, Integer>> metricMap;
private ConcurrentMap<Integer, Integer> statusMetric;
private ConcurrentMap<String, ConcurrentHashMap<Integer, Integer>> timeMap;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public MetricService() {
super();
metricMap = new ConcurrentHashMap<String, ConcurrentHashMap<Integer, Integer>>();
statusMetric = new ConcurrentHashMap<Integer, Integer>();
timeMap = new ConcurrentHashMap<String, ConcurrentHashMap<Integer, Integer>>();
}
// API
@Override
public void increaseCount(final String request, final int status) {
increaseMainMetric(request, status);
increaseStatusMetric(status);
updateTimeMap(status);
}
@Override
public Map getFullMetric() {
return metricMap;
}
@Override
public Map getStatusMetric() {
return statusMetric;
}
@Override
public Object[][] getGraphData() {
final int colCount = statusMetric.keySet().size() + 1;
final Set<Integer> allStatus = statusMetric.keySet();
final int rowCount = timeMap.keySet().size() + 1;
final Object[][] result = new Object[rowCount][colCount];
result[0][0] = "Time";
int j = 1;
for (final int status : allStatus) {
result[0][j] = status;
j++;
}
int i = 1;
ConcurrentMap<Integer, Integer> tempMap;
for (final Entry<String, ConcurrentHashMap<Integer, Integer>> entry : timeMap.entrySet()) {
result[i][0] = entry.getKey();
tempMap = entry.getValue();
for (j = 1; j < colCount; j++) {
result[i][j] = tempMap.get(result[0][j]);
if (result[i][j] == null) {
result[i][j] = 0;
}
}
i++;
}
return result;
}
// NON-API
private void increaseMainMetric(final String request, final int status) {
ConcurrentHashMap<Integer, Integer> statusMap = metricMap.get(request);
if (statusMap == null) {
statusMap = new ConcurrentHashMap<Integer, Integer>();
}
Integer count = statusMap.get(status);
if (count == null) {
count = 1;
} else {
count++;
}
statusMap.put(status, count);
metricMap.put(request, statusMap);
}
private void increaseStatusMetric(final int status) {
final Integer statusCount = statusMetric.get(status);
if (statusCount == null) {
statusMetric.put(status, 1);
} else {
statusMetric.put(status, statusCount + 1);
}
}
private void updateTimeMap(final int status) {
final String time = dateFormat.format(new Date());
ConcurrentHashMap<Integer, Integer> statusMap = timeMap.get(time);
if (statusMap == null) {
statusMap = new ConcurrentHashMap<Integer, Integer>();
}
Integer count = statusMap.get(status);
if (count == null) {
count = 1;
} else {
count++;
}
statusMap.put(status, count);
timeMap.put(time, statusMap);
}
}

View File

@@ -0,0 +1,36 @@
package org.baeldung.web.util;
import javax.servlet.http.HttpServletResponse;
/**
* Provides some constants and utility methods to build a Link Header to be stored in the {@link HttpServletResponse} object
*/
public final class LinkUtil {
public static final String REL_COLLECTION = "collection";
public static final String REL_NEXT = "next";
public static final String REL_PREV = "prev";
public static final String REL_FIRST = "first";
public static final String REL_LAST = "last";
private LinkUtil() {
throw new AssertionError();
}
//
/**
* Creates a Link Header to be stored in the {@link HttpServletResponse} to provide Discoverability features to the user
*
* @param uri
* the base uri
* @param rel
* the relative path
*
* @return the complete url
*/
public static String createLinkHeader(final String uri, final String rel) {
return "<" + uri + ">; rel=\"" + rel + "\"";
}
}

View File

@@ -0,0 +1,47 @@
package org.baeldung.web.util;
import org.baeldung.web.exception.MyResourceNotFoundException;
import org.springframework.http.HttpStatus;
/**
* Simple static methods to be called at the start of your own methods to verify correct arguments and state. If the Precondition fails, an {@link HttpStatus} code is thrown
*/
public final class RestPreconditions {
private RestPreconditions() {
throw new AssertionError();
}
// API
/**
* Check if some value was found, otherwise throw exception.
*
* @param expression
* has value true if found, otherwise false
* @throws MyResourceNotFoundException
* if expression is false, means value not found.
*/
public static void checkFound(final boolean expression) {
if (!expression) {
throw new MyResourceNotFoundException();
}
}
/**
* Check if some value was found, otherwise throw exception.
*
* @param expression
* has value true if found, otherwise false
* @throws MyResourceNotFoundException
* if expression is false, means value not found.
*/
public static <T> T checkFound(final T resource) {
if (resource == null) {
throw new MyResourceNotFoundException();
}
return resource;
}
}

View File

@@ -0,0 +1,3 @@
server.port=8082
server.context-path=/spring-rest-full
endpoints.metrics.enabled=true

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<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>

View File

@@ -0,0 +1,22 @@
## jdbc.X
#jdbc.driverClassName=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true
#jdbc.user=tutorialuser
#jdbc.pass=tutorialmy5ql
#
## hibernate.X
#hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
#hibernate.show_sql=false
#hibernate.hbm2ddl.auto=create-drop
# jdbc.X
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
jdbc.user=sa
jdbc.pass=
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop

View File

@@ -0,0 +1,10 @@
# jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true
jdbc.user=tutorialuser
jdbc.pass=tutorialmy5ql
# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
>
<jpa:repositories base-package="org.baeldung.persistence.dao"/>
</beans>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<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-4.2.xsd" >
</beans>

View File

@@ -0,0 +1,43 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Metric Graph</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {
packages : [ "corechart" ]
});
function drawChart() {
$.get("<c:url value="/metric-graph-data"/>",
function(mydata) {
var data = google.visualization.arrayToDataTable(mydata);
var options = {
title : 'Website Metric',
hAxis : {
title : 'Time',
titleTextStyle : {
color : '#333'
}
},
vAxis : {
minValue : 0
}
};
var chart = new google.visualization.AreaChart(document
.getElementById('chart_div'));
chart.draw(data, options);
});
}
</script>
</head>
<body onload="drawChart()">
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>

View File

@@ -0,0 +1,7 @@
<html>
<head></head>
<body>
<h1>This is the body of the sample view</h1>
</body>
</html>

View File

@@ -0,0 +1,61 @@
<?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 REST 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>org.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>etagFilter</filter-name>
<filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>etagFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 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>
<!-- Metric filter -->
<filter>
<filter-name>metricFilter</filter-name>
<filter-class>org.baeldung.web.metric.MetricFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>metricFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

View File

@@ -0,0 +1,5 @@
package org.baeldung;
public interface Consts {
int APPLICATION_PORT = 8082;
}

View File

@@ -0,0 +1,16 @@
package org.baeldung;
import org.baeldung.persistence.PersistenceTestSuite;
import org.baeldung.web.LiveTestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
// @formatter:off
PersistenceTestSuite.class
,LiveTestSuite.class
}) //
public class TestSuite {
}

View File

@@ -0,0 +1,174 @@
package org.baeldung.common.web;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
import static org.baeldung.web.util.HTTPLinkHeaderUtil.extractURIByRel;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import java.io.Serializable;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.net.HttpHeaders;
public abstract class AbstractBasicLiveTest<T extends Serializable> extends AbstractLiveTest<T> {
public AbstractBasicLiveTest(final Class<T> clazzToSet) {
super(clazzToSet);
}
// tests
@Test
public void givenResourceExists_whenRetrievingResource_thenEtagIsAlsoReturned() {
// Given
final String uriOfResource = createAsUri();
// When
final Response findOneResponse = RestAssured.given()
.header("Accept", "application/json")
.get(uriOfResource);
// Then
assertNotNull(findOneResponse.getHeader(HttpHeaders.ETAG));
}
@Test
public void givenResourceWasRetrieved_whenRetrievingAgainWithEtag_thenNotModifiedReturned() {
// Given
final String uriOfResource = createAsUri();
final Response findOneResponse = RestAssured.given()
.header("Accept", "application/json")
.get(uriOfResource);
final String etagValue = findOneResponse.getHeader(HttpHeaders.ETAG);
// When
final Response secondFindOneResponse = RestAssured.given()
.header("Accept", "application/json")
.headers("If-None-Match", etagValue)
.get(uriOfResource);
// Then
assertTrue(secondFindOneResponse.getStatusCode() == 304);
}
@Test
@Ignore("No Update operation yet")
public void givenResourceWasRetrievedThenModified_whenRetrievingAgainWithEtag_thenResourceIsReturned() {
// Given
final String uriOfResource = createAsUri();
final Response findOneResponse = RestAssured.given()
.header("Accept", "application/json")
.get(uriOfResource);
final String etagValue = findOneResponse.getHeader(HttpHeaders.ETAG);
// existingResource.setName(randomAlphabetic(6));
// getApi().update(existingResource.setName("randomString"));
// When
final Response secondFindOneResponse = RestAssured.given()
.header("Accept", "application/json")
.headers("If-None-Match", etagValue)
.get(uriOfResource);
// Then
assertTrue(secondFindOneResponse.getStatusCode() == 200);
}
@Test
@Ignore("Not Yet Implemented By Spring - https://jira.springsource.org/browse/SPR-10164")
public void givenResourceExists_whenRetrievedWithIfMatchIncorrectEtag_then412IsReceived() {
// Given
final String uriOfResource = createAsUri();
// When
final Response findOneResponse = RestAssured.given()
.header("Accept", "application/json")
.headers("If-Match", randomAlphabetic(8))
.get(uriOfResource);
// Then
assertTrue(findOneResponse.getStatusCode() == 412);
}
// find - one
// find - all
// find - all - paginated
@Test
public void whenResourcesAreRetrievedPaged_then200IsReceived() {
final Response response = RestAssured.get(getURL() + "?page=0&size=10");
assertThat(response.getStatusCode(), is(200));
}
@Test
public void whenPageOfResourcesAreRetrievedOutOfBounds_then404IsReceived() {
final String url = getURL() + "?page=" + randomNumeric(5) + "&size=10";
final Response response = RestAssured.get(url);
assertThat(response.getStatusCode(), is(404));
}
@Test
public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() {
create();
final Response response = RestAssured.get(getURL() + "?page=0&size=10");
assertFalse(response.body().as(List.class).isEmpty());
}
@Test
public void whenFirstPageOfResourcesAreRetrieved_thenSecondPageIsNext() {
final Response response = RestAssured.get(getURL() + "?page=0&size=2");
final String uriToNextPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "next");
assertEquals(getURL() + "?page=1&size=2", uriToNextPage);
}
@Test
public void whenFirstPageOfResourcesAreRetrieved_thenNoPreviousPage() {
final Response response = RestAssured.get(getURL() + "?page=0&size=2");
final String uriToPrevPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "prev");
assertNull(uriToPrevPage);
}
@Test
public void whenSecondPageOfResourcesAreRetrieved_thenFirstPageIsPrevious() {
create();
create();
final Response response = RestAssured.get(getURL() + "?page=1&size=2");
final String uriToPrevPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "prev");
assertEquals(getURL() + "?page=0&size=2", uriToPrevPage);
}
@Test
public void whenLastPageOfResourcesIsRetrieved_thenNoNextPageIsDiscoverable() {
final Response first = RestAssured.get(getURL() + "?page=0&size=2");
final String uriToLastPage = extractURIByRel(first.getHeader(HttpHeaders.LINK), "last");
final Response response = RestAssured.get(uriToLastPage);
final String uriToNextPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "next");
assertNull(uriToNextPage);
}
// count
}

View File

@@ -0,0 +1,80 @@
package org.baeldung.common.web;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import java.io.Serializable;
import org.baeldung.persistence.model.Foo;
import org.baeldung.web.util.HTTPLinkHeaderUtil;
import org.hamcrest.core.AnyOf;
import org.junit.Test;
import org.springframework.http.MediaType;
import com.google.common.net.HttpHeaders;
public abstract class AbstractDiscoverabilityLiveTest<T extends Serializable> extends AbstractLiveTest<T> {
public AbstractDiscoverabilityLiveTest(final Class<T> clazzToSet) {
super(clazzToSet);
}
// tests
// discoverability
@Test
public void whenInvalidPOSTIsSentToValidURIOfResource_thenAllowHeaderListsTheAllowedActions() {
// Given
final String uriOfExistingResource = createAsUri();
// When
final Response res = RestAssured.post(uriOfExistingResource);
// Then
final String allowHeader = res.getHeader(HttpHeaders.ALLOW);
assertThat(allowHeader, AnyOf.anyOf(containsString("GET"), containsString("PUT"), containsString("DELETE")));
}
@Test
public void whenResourceIsCreated_thenUriOfTheNewlyCreatedResourceIsDiscoverable() {
// When
final Foo newResource = new Foo(randomAlphabetic(6));
final Response createResp = RestAssured.given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(newResource)
.post(getURL());
final String uriOfNewResource = createResp.getHeader(HttpHeaders.LOCATION);
// Then
final Response response = RestAssured.given()
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.get(uriOfNewResource);
final Foo resourceFromServer = response.body().as(Foo.class);
assertThat(newResource, equalTo(resourceFromServer));
}
@Test
public void whenResourceIsRetrieved_thenUriToGetAllResourcesIsDiscoverable() {
// Given
final String uriOfExistingResource = createAsUri();
// When
final Response getResponse = RestAssured.get(uriOfExistingResource);
// Then
final String uriToAllResources = HTTPLinkHeaderUtil.extractURIByRel(getResponse.getHeader("Link"), "collection");
final Response getAllResponse = RestAssured.get(uriToAllResources);
assertThat(getAllResponse.getStatusCode(), is(200));
}
// template method
}

View File

@@ -0,0 +1,64 @@
package org.baeldung.common.web;
import static org.baeldung.Consts.APPLICATION_PORT;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import java.io.Serializable;
import org.baeldung.test.IMarshaller;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
public abstract class AbstractLiveTest<T extends Serializable> {
protected final Class<T> clazz;
@Autowired
protected IMarshaller marshaller;
public AbstractLiveTest(final Class<T> clazzToSet) {
super();
Preconditions.checkNotNull(clazzToSet);
clazz = clazzToSet;
}
// template method
public abstract void create();
public abstract String createAsUri();
protected final void create(final T resource) {
createAsUri(resource);
}
protected final String createAsUri(final T resource) {
final Response response = createAsResponse(resource);
Preconditions.checkState(response.getStatusCode() == 201, "create operation: " + response.getStatusCode());
final String locationOfCreatedResource = response.getHeader(HttpHeaders.LOCATION);
Preconditions.checkNotNull(locationOfCreatedResource);
return locationOfCreatedResource;
}
final Response createAsResponse(final T resource) {
Preconditions.checkNotNull(resource);
final String resourceAsString = marshaller.encode(resource);
return RestAssured.given()
.contentType(marshaller.getMime())
.body(resourceAsString)
.post(getURL());
}
//
protected String getURL() {
return "http://localhost:" + APPLICATION_PORT + "/spring-rest-full/auth/foos";
}
}

View File

@@ -0,0 +1,16 @@
package org.baeldung.persistence;
import org.baeldung.persistence.service.FooServicePersistenceIntegrationTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
// @formatter:off
FooServicePersistenceIntegrationTest.class
}) //
public class PersistenceTestSuite {
}

View File

@@ -0,0 +1,255 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import java.io.Serializable;
import java.util.List;
import org.baeldung.persistence.IOperations;
import org.baeldung.persistence.model.Foo;
import org.baeldung.util.IDUtil;
import org.hamcrest.Matchers;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.dao.DataAccessException;
public abstract class AbstractServicePersistenceIntegrationTest<T extends Serializable> {
// tests
// find - one
@Test
/**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() {
// When
final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong());
// Then
assertNull(createdResource);
}
@Test
public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() {
final Foo existingResource = persistNewEntity();
getApi().findOne(existingResource.getId());
}
@Test
public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() {
getApi().findOne(IDUtil.randomPositiveLong());
}
@Test
public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() {
final Foo existingResource = persistNewEntity();
final Foo retrievedResource = getApi().findOne(existingResource.getId());
assertNotNull(retrievedResource);
}
@Test
public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() {
final Foo existingResource = persistNewEntity();
final Foo retrievedResource = getApi().findOne(existingResource.getId());
assertEquals(existingResource, retrievedResource);
}
// find - one - by name
// find - all
@Test
/**/public void whenAllResourcesAreRetrieved_thenNoExceptions() {
getApi().findAll();
}
@Test
/**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() {
final List<Foo> resources = getApi().findAll();
assertNotNull(resources);
}
@Test
/**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() {
persistNewEntity();
// When
final List<Foo> allResources = getApi().findAll();
// Then
assertThat(allResources, not(Matchers.<Foo> empty()));
}
@Test
/**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() {
final Foo existingResource = persistNewEntity();
final List<Foo> resources = getApi().findAll();
assertThat(resources, hasItem(existingResource));
}
@Test
/**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() {
persistNewEntity();
// When
final List<Foo> allResources = getApi().findAll();
// Then
for (final Foo resource : allResources) {
assertNotNull(resource.getId());
}
}
// create
@Test(expected = RuntimeException.class)
/**/public void whenNullResourceIsCreated_thenException() {
getApi().create(null);
}
@Test
/**/public void whenResourceIsCreated_thenNoExceptions() {
persistNewEntity();
}
@Test
/**/public void whenResourceIsCreated_thenResourceIsRetrievable() {
final Foo existingResource = persistNewEntity();
assertNotNull(getApi().findOne(existingResource.getId()));
}
@Test
/**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() {
final Foo originalResource = createNewEntity();
final Foo savedResource = getApi().create(originalResource);
assertEquals(originalResource, savedResource);
}
@Test(expected = RuntimeException.class)
public void whenResourceWithFailedConstraintsIsCreated_thenException() {
final Foo invalidResource = createNewEntity();
invalidate(invalidResource);
getApi().create(invalidResource);
}
/**
* -- specific to the persistence engine
*/
@Test(expected = DataAccessException.class)
@Ignore("Hibernate simply ignores the id silently and still saved (tracking this)")
public void whenResourceWithIdIsCreated_thenDataAccessException() {
final Foo resourceWithId = createNewEntity();
resourceWithId.setId(IDUtil.randomPositiveLong());
getApi().create(resourceWithId);
}
// update
@Test(expected = RuntimeException.class)
/**/public void whenNullResourceIsUpdated_thenException() {
getApi().update(null);
}
@Test
/**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() {
// Given
final Foo existingResource = persistNewEntity();
// When
getApi().update(existingResource);
}
/**
* - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException
*/
@Test(expected = RuntimeException.class)
public void whenResourceIsUpdatedWithFailedConstraints_thenException() {
final Foo existingResource = persistNewEntity();
invalidate(existingResource);
getApi().update(existingResource);
}
@Test
/**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() {
// Given
final Foo existingResource = persistNewEntity();
// When
change(existingResource);
getApi().update(existingResource);
final Foo updatedResource = getApi().findOne(existingResource.getId());
// Then
assertEquals(existingResource, updatedResource);
}
// delete
// @Test(expected = RuntimeException.class)
// public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() {
// // When
// getApi().delete(IDUtil.randomPositiveLong());
// }
//
// @Test(expected = RuntimeException.class)
// public void whenResourceIsDeletedByNegativeId_thenException() {
// // When
// getApi().delete(IDUtil.randomNegativeLong());
// }
//
// @Test
// public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() {
// // Given
// final Foo existingResource = persistNewEntity();
//
// // When
// getApi().delete(existingResource.getId());
// }
//
// @Test
// /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() {
// // Given
// final Foo existingResource = persistNewEntity();
//
// // When
// getApi().delete(existingResource.getId());
//
// // Then
// assertNull(getApi().findOne(existingResource.getId()));
// }
// template method
protected Foo createNewEntity() {
return new Foo(randomAlphabetic(6));
}
protected abstract IOperations<Foo> getApi();
private final void invalidate(final Foo entity) {
entity.setName(null);
}
private final void change(final Foo entity) {
entity.setName(randomAlphabetic(6));
}
protected Foo persistNewEntity() {
return getApi().create(createNewEntity());
}
}

View File

@@ -0,0 +1,76 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertNotNull;
import org.baeldung.persistence.IOperations;
import org.baeldung.persistence.model.Foo;
import org.baeldung.spring.PersistenceConfig;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest<Foo> {
@Autowired
private IFooService service;
// tests
@Test
public final void whenContextIsBootstrapped_thenNoExceptions() {
//
}
@Test
public final void whenEntityIsCreated_thenNoExceptions() {
service.create(new Foo(randomAlphabetic(6)));
}
@Test(expected = DataIntegrityViolationException.class)
public final void whenInvalidEntityIsCreated_thenDataException() {
service.create(new Foo());
}
@Test(expected = DataIntegrityViolationException.class)
public final void whenEntityWithLongNameIsCreated_thenDataException() {
service.create(new Foo(randomAlphabetic(2048)));
}
// custom Query method
@Test
public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() {
final String name = randomAlphabetic(6);
service.create(new Foo(name));
final Foo retrievedByName = service.retrieveByName(name);
assertNotNull(retrievedByName);
}
// work in progress
@Test(expected = InvalidDataAccessApiUsageException.class)
@Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail")
public final void whenSameEntityIsCreatedTwice_thenDataException() {
final Foo entity = new Foo(randomAlphabetic(8));
service.create(entity);
service.create(entity);
}
// API
@Override
protected final IOperations<Foo> getApi() {
return service;
}
}

View File

@@ -0,0 +1,17 @@
package org.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@ComponentScan("org.baeldung.test")
public class ConfigTest extends WebMvcConfigurerAdapter {
public ConfigTest() {
super();
}
// API
}

View File

@@ -0,0 +1,15 @@
package org.baeldung.test;
import java.util.List;
public interface IMarshaller {
<T> String encode(final T entity);
<T> T decode(final String entityAsString, final Class<T> clazz);
<T> List<T> decodeList(final String entitiesAsString, final Class<T> clazz);
String getMime();
}

View File

@@ -0,0 +1,83 @@
package org.baeldung.test;
import java.io.IOException;
import java.util.List;
import org.baeldung.persistence.model.Foo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
public final class JacksonMarshaller implements IMarshaller {
private final Logger logger = LoggerFactory.getLogger(JacksonMarshaller.class);
private final ObjectMapper objectMapper;
public JacksonMarshaller() {
super();
objectMapper = new ObjectMapper();
}
// API
@Override
public final <T> String encode(final T resource) {
Preconditions.checkNotNull(resource);
String entityAsJSON = null;
try {
entityAsJSON = objectMapper.writeValueAsString(resource);
} catch (final IOException ioEx) {
logger.error("", ioEx);
}
return entityAsJSON;
}
@Override
public final <T> T decode(final String resourceAsString, final Class<T> clazz) {
Preconditions.checkNotNull(resourceAsString);
T entity = null;
try {
entity = objectMapper.readValue(resourceAsString, clazz);
} catch (final IOException ioEx) {
logger.error("", ioEx);
}
return entity;
}
@SuppressWarnings("unchecked")
@Override
public final <T> List<T> decodeList(final String resourcesAsString, final Class<T> clazz) {
Preconditions.checkNotNull(resourcesAsString);
List<T> entities = null;
try {
if (clazz.equals(Foo.class)) {
entities = objectMapper.readValue(resourcesAsString, new TypeReference<List<Foo>>() {
// ...
});
} else {
entities = objectMapper.readValue(resourcesAsString, List.class);
}
} catch (final IOException ioEx) {
logger.error("", ioEx);
}
return entities;
}
@Override
public final String getMime() {
return MediaType.APPLICATION_JSON.toString();
}
}

View File

@@ -0,0 +1,48 @@
package org.baeldung.test;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@Profile("test")
public class TestMarshallerFactory implements FactoryBean<IMarshaller> {
@Autowired
private Environment env;
public TestMarshallerFactory() {
super();
}
// API
@Override
public IMarshaller getObject() {
final String testMime = env.getProperty("test.mime");
if (testMime != null) {
switch (testMime) {
case "json":
return new JacksonMarshaller();
case "xml":
return new XStreamMarshaller();
default:
throw new IllegalStateException();
}
}
return new JacksonMarshaller();
}
@Override
public Class<IMarshaller> getObjectType() {
return IMarshaller.class;
}
@Override
public boolean isSingleton() {
return true;
}
}

View File

@@ -0,0 +1,49 @@
package org.baeldung.test;
import java.util.List;
import org.baeldung.persistence.model.Foo;
import org.springframework.http.MediaType;
import com.google.common.base.Preconditions;
import com.thoughtworks.xstream.XStream;
public final class XStreamMarshaller implements IMarshaller {
private XStream xstream;
public XStreamMarshaller() {
super();
xstream = new XStream();
xstream.autodetectAnnotations(true);
xstream.processAnnotations(Foo.class);
}
// API
@Override
public final <T> String encode(final T resource) {
Preconditions.checkNotNull(resource);
return xstream.toXML(resource);
}
@SuppressWarnings("unchecked")
@Override
public final <T> T decode(final String resourceAsString, final Class<T> clazz) {
Preconditions.checkNotNull(resourceAsString);
return (T) xstream.fromXML(resourceAsString);
}
@SuppressWarnings("unchecked")
@Override
public <T> List<T> decodeList(final String resourcesAsString, final Class<T> clazz) {
return this.decode(resourcesAsString, List.class);
}
@Override
public final String getMime() {
return MediaType.APPLICATION_XML.toString();
}
}

View File

@@ -0,0 +1,33 @@
package org.baeldung.util;
import java.util.Random;
public final class IDUtil {
private IDUtil() {
throw new AssertionError();
}
// API
public static String randomPositiveLongAsString() {
return Long.toString(randomPositiveLong());
}
public static String randomNegativeLongAsString() {
return Long.toString(randomNegativeLong());
}
public static long randomPositiveLong() {
long id = new Random().nextLong() * 10000;
id = (id < 0) ? (-1 * id) : id;
return id;
}
private static long randomNegativeLong() {
long id = new Random().nextLong() * 10000;
id = (id > 0) ? (-1 * id) : id;
return id;
}
}

View File

@@ -0,0 +1,35 @@
package org.baeldung.web;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.baeldung.common.web.AbstractDiscoverabilityLiveTest;
import org.baeldung.persistence.model.Foo;
import org.baeldung.spring.ConfigTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("test")
public class FooDiscoverabilityLiveTest extends AbstractDiscoverabilityLiveTest<Foo> {
public FooDiscoverabilityLiveTest() {
super(Foo.class);
}
// API
@Override
public final void create() {
create(new Foo(randomAlphabetic(6)));
}
@Override
public final String createAsUri() {
return createAsUri(new Foo(randomAlphabetic(6)));
}
}

View File

@@ -0,0 +1,35 @@
package org.baeldung.web;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.baeldung.common.web.AbstractBasicLiveTest;
import org.baeldung.persistence.model.Foo;
import org.baeldung.spring.ConfigTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("test")
public class FooLiveTest extends AbstractBasicLiveTest<Foo> {
public FooLiveTest() {
super(Foo.class);
}
// API
@Override
public final void create() {
create(new Foo(randomAlphabetic(6)));
}
@Override
public final String createAsUri() {
return createAsUri(new Foo(randomAlphabetic(6)));
}
}

View File

@@ -0,0 +1,76 @@
package org.baeldung.web;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
import static org.baeldung.Consts.APPLICATION_PORT;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import java.util.List;
import org.baeldung.common.web.AbstractBasicLiveTest;
import org.baeldung.persistence.model.Foo;
import org.baeldung.spring.ConfigTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("test")
public class FooPageableLiveTest extends AbstractBasicLiveTest<Foo> {
public FooPageableLiveTest() {
super(Foo.class);
}
// API
@Override
public final void create() {
create(new Foo(randomAlphabetic(6)));
}
@Override
public final String createAsUri() {
return createAsUri(new Foo(randomAlphabetic(6)));
}
@Override
@Test
public void whenResourcesAreRetrievedPaged_then200IsReceived() {
final Response response = RestAssured.get(getPageableURL() + "?page=0&size=10");
assertThat(response.getStatusCode(), is(200));
}
@Override
@Test
public void whenPageOfResourcesAreRetrievedOutOfBounds_then404IsReceived() {
final String url = getPageableURL() + "?page=" + randomNumeric(5) + "&size=10";
final Response response = RestAssured.get(url);
assertThat(response.getStatusCode(), is(404));
}
@Override
@Test
public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() {
create();
final Response response = RestAssured.get(getPageableURL() + "?page=0&size=10");
assertFalse(response.body().as(List.class).isEmpty());
}
protected String getPageableURL() {
return "http://localhost:" + APPLICATION_PORT + "/spring-rest-full/auth/foos/pageable";
}
}

View File

@@ -0,0 +1,15 @@
package org.baeldung.web;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
// @formatter:off
FooDiscoverabilityLiveTest.class
,FooLiveTest.class
,FooPageableLiveTest.class
}) //
public class LiveTestSuite {
}

View File

@@ -0,0 +1,36 @@
package org.baeldung.web.util;
public final class HTTPLinkHeaderUtil {
private HTTPLinkHeaderUtil() {
throw new AssertionError();
}
//
public static String extractURIByRel(final String linkHeader, final String rel) {
if (linkHeader == null) {
return null;
}
String uriWithSpecifiedRel = null;
final String[] links = linkHeader.split(", ");
String linkRelation;
for (final String link : links) {
final int positionOfSeparator = link.indexOf(';');
linkRelation = link.substring(positionOfSeparator + 1, link.length()).trim();
if (extractTypeOfRelation(linkRelation).equals(rel)) {
uriWithSpecifiedRel = link.substring(1, positionOfSeparator - 1);
break;
}
}
return uriWithSpecifiedRel;
}
private static Object extractTypeOfRelation(final String linkRelation) {
final int positionOfEquals = linkRelation.indexOf('=');
return linkRelation.substring(positionOfEquals + 2, linkRelation.length() - 1).trim();
}
}

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear