Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
f232ee72a9
4
guest/junit5-example/.gitignore
vendored
Normal file
4
guest/junit5-example/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
/target/
|
||||||
|
.settings/
|
||||||
|
.classpath
|
||||||
|
.project
|
68
guest/junit5-example/pom.xml
Normal file
68
guest/junit5-example/pom.xml
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
<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>junit5-example</groupId>
|
||||||
|
<artifactId>junit5-example</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-engine</artifactId>
|
||||||
|
<version>5.0.0-M4</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-params</artifactId>
|
||||||
|
<version>5.0.0-M4</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.vintage</groupId>
|
||||||
|
<artifactId>junit-vintage-engine</artifactId>
|
||||||
|
<version>4.12.0-M4</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>1.4.195</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
|
<artifactId>log4j-core</artifactId>
|
||||||
|
<version>2.8.2</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.5</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>2.19.1</version>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||||
|
<version>1.0.0-M4</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<configuration>
|
||||||
|
<properties>
|
||||||
|
<excludeTags>math</excludeTags>
|
||||||
|
</properties>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
@ -0,0 +1,141 @@
|
|||||||
|
package com.stackify.daos;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
|
||||||
|
import com.stackify.models.User;
|
||||||
|
import com.stackify.utils.ConnectionUtil;
|
||||||
|
|
||||||
|
public class UserDAO {
|
||||||
|
|
||||||
|
private Logger logger = LogManager.getLogger(UserDAO.class);
|
||||||
|
|
||||||
|
public void createTable() {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
String createQuery = "CREATE TABLE users(email varchar(50) primary key, name varchar(50))";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(createQuery);
|
||||||
|
|
||||||
|
pstmt.execute();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void add(User user) {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
|
||||||
|
String insertQuery = "INSERT INTO users(email,name) VALUES(?,?)";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(insertQuery);
|
||||||
|
pstmt.setString(1, user.getEmail());
|
||||||
|
pstmt.setString(2, user.getName());
|
||||||
|
|
||||||
|
pstmt.executeUpdate();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void update(User user) {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
|
||||||
|
String updateQuery = "UPDATE users SET name=? WHERE email=?";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(updateQuery);
|
||||||
|
pstmt.setString(1, user.getName());
|
||||||
|
pstmt.setString(2, user.getEmail());
|
||||||
|
|
||||||
|
pstmt.executeUpdate();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(User user) {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
|
||||||
|
String deleteQuery = "DELETE FROM users WHERE email=?";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
|
||||||
|
pstmt.setString(1, user.getEmail());
|
||||||
|
|
||||||
|
pstmt.executeUpdate();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(String email) {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
|
||||||
|
String deleteQuery = "DELETE FROM users WHERE email=?";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
|
||||||
|
pstmt.setString(1, email);
|
||||||
|
|
||||||
|
pstmt.executeUpdate();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public User findOne(String email) {
|
||||||
|
User user = null;
|
||||||
|
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
String query = "SELECT * FROM users WHERE email=?";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(query);
|
||||||
|
pstmt.setString(1, email);
|
||||||
|
|
||||||
|
ResultSet rs = pstmt.executeQuery();
|
||||||
|
while (rs.next()) {
|
||||||
|
user = new User();
|
||||||
|
user.setEmail(rs.getString("email"));
|
||||||
|
user.setName(rs.getString("name"));
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<User> findAll() {
|
||||||
|
List<User> users = new ArrayList<>();
|
||||||
|
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
String query = "SELECT * FROM users";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(query);
|
||||||
|
|
||||||
|
ResultSet rs = pstmt.executeQuery();
|
||||||
|
while (rs.next()) {
|
||||||
|
User user = new User();
|
||||||
|
user.setEmail(rs.getString("email"));
|
||||||
|
user.setName(rs.getString("name"));
|
||||||
|
users.add(user);
|
||||||
|
}
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return users;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteAll() {
|
||||||
|
try (Connection con = ConnectionUtil.getConnection()) {
|
||||||
|
|
||||||
|
String deleteQuery = "DELETE FROM users";
|
||||||
|
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
|
||||||
|
|
||||||
|
pstmt.executeUpdate();
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,63 @@
|
|||||||
|
package com.stackify.models;
|
||||||
|
|
||||||
|
public class User {
|
||||||
|
private String email;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public User() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public User(String email, String name) {
|
||||||
|
super();
|
||||||
|
this.email = email;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
result = prime * result + ((email == null) ? 0 : email.hashCode());
|
||||||
|
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
User other = (User) obj;
|
||||||
|
if (email == null) {
|
||||||
|
if (other.email != null)
|
||||||
|
return false;
|
||||||
|
} else if (!email.equals(other.email))
|
||||||
|
return false;
|
||||||
|
if (name == null) {
|
||||||
|
if (other.name != null)
|
||||||
|
return false;
|
||||||
|
} else if (!name.equals(other.name))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.stackify.test.conditions;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
|
||||||
|
@Target({ ElementType.METHOD })
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@ExtendWith(DisabledOnEnvironmentCondition.class)
|
||||||
|
public @interface DisabledOnEnvironment {
|
||||||
|
String[] value();
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.stackify.test.conditions;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
|
||||||
|
import org.junit.jupiter.api.extension.TestExecutionCondition;
|
||||||
|
import org.junit.jupiter.api.extension.TestExtensionContext;
|
||||||
|
import org.junit.platform.commons.support.AnnotationSupport;
|
||||||
|
|
||||||
|
import com.stackify.utils.ConnectionUtil;
|
||||||
|
|
||||||
|
public class DisabledOnEnvironmentCondition implements TestExecutionCondition {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ConditionEvaluationResult evaluate(TestExtensionContext context) {
|
||||||
|
Properties props = new Properties();
|
||||||
|
String env = "";
|
||||||
|
try {
|
||||||
|
props.load(ConnectionUtil.class.getResourceAsStream("/application.properties"));
|
||||||
|
env = props.getProperty("env");
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
Optional<DisabledOnEnvironment> disabled = AnnotationSupport.findAnnotation(context.getElement().get(), DisabledOnEnvironment.class);
|
||||||
|
if (disabled.isPresent()) {
|
||||||
|
String[] envs = disabled.get().value();
|
||||||
|
if (Arrays.asList(envs).contains(env)) {
|
||||||
|
return ConditionEvaluationResult.disabled("Disabled on environment " + env);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ConditionEvaluationResult.enabled("Enabled on environment "+env);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.stackify.utils;
|
||||||
|
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
|
||||||
|
public class ConnectionUtil {
|
||||||
|
|
||||||
|
private static Logger logger = LogManager.getLogger(ConnectionUtil.class);
|
||||||
|
|
||||||
|
public static Connection getConnection() {
|
||||||
|
try {
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.load(ConnectionUtil.class.getResourceAsStream("jdbc.properties"));
|
||||||
|
Class.forName(props.getProperty("jdbc.driver"));
|
||||||
|
Connection con = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.user"), props.getProperty("jdbc.password"));
|
||||||
|
return con;
|
||||||
|
}
|
||||||
|
|
||||||
|
catch (FileNotFoundException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
} catch (IOException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
} catch (ClassNotFoundException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
} catch (SQLException exc) {
|
||||||
|
logger.error(exc.getMessage());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1 @@
|
|||||||
|
env=dev
|
@ -0,0 +1,4 @@
|
|||||||
|
jdbc.driver=org.h2.Driver
|
||||||
|
jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
|
||||||
|
jdbc.user=
|
||||||
|
jdbc.password=
|
13
guest/junit5-example/src/main/resources/log4j2.xml
Normal file
13
guest/junit5-example/src/main/resources/log4j2.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="WARN">
|
||||||
|
<Appenders>
|
||||||
|
<Console name="Console" target="SYSTEM_OUT">
|
||||||
|
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
|
||||||
|
</Console>
|
||||||
|
</Appenders>
|
||||||
|
<Loggers>
|
||||||
|
<Root level="info">
|
||||||
|
<AppenderRef ref="Console"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.stackify.test;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.stackify.utils.ConnectionUtil;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public interface DatabaseConnectionTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
default void testDatabaseConnection() {
|
||||||
|
Connection con = ConnectionUtil.getConnection();
|
||||||
|
assertNotNull(con);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.stackify.test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import org.junit.jupiter.api.DynamicTest;
|
||||||
|
import org.junit.jupiter.api.TestFactory;
|
||||||
|
import org.junit.jupiter.api.function.ThrowingConsumer;
|
||||||
|
|
||||||
|
import com.stackify.daos.UserDAO;
|
||||||
|
import com.stackify.models.User;
|
||||||
|
|
||||||
|
public class DynamicTests {
|
||||||
|
|
||||||
|
@TestFactory
|
||||||
|
public Collection<DynamicTest> dynamicTestCollection() {
|
||||||
|
return Arrays.asList(DynamicTest.dynamicTest("Dynamic Test", () -> assertTrue(1 == 1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@TestFactory
|
||||||
|
public Stream<DynamicTest> dynamicUserTestCollection() {
|
||||||
|
List<User> inputList = Arrays.asList(new User("john@yahoo.com", "John"), new User("ana@yahoo.com", "Ana"));
|
||||||
|
|
||||||
|
Function<User, String> displayNameGenerator = (input) -> "Saving user: " + input;
|
||||||
|
|
||||||
|
UserDAO userDAO = new UserDAO();
|
||||||
|
ThrowingConsumer<User> testExecutor = (input) -> {
|
||||||
|
userDAO.add(input);
|
||||||
|
assertNotNull(userDAO.findOne(input.getEmail()));
|
||||||
|
};
|
||||||
|
|
||||||
|
return DynamicTest.stream(inputList.iterator(), displayNameGenerator, testExecutor);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.stackify.test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.RepeatedTest;
|
||||||
|
import org.junit.jupiter.api.RepetitionInfo;
|
||||||
|
|
||||||
|
public class IncrementTest {
|
||||||
|
|
||||||
|
private static Logger logger = LogManager.getLogger(IncrementTest.class);
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
public void increment() {
|
||||||
|
logger.info("Before Each Test");
|
||||||
|
}
|
||||||
|
|
||||||
|
@RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME)
|
||||||
|
public void test(RepetitionInfo info) {
|
||||||
|
assertTrue(1 == 1);
|
||||||
|
logger.info("Repetition #" + info.getCurrentRepetition());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.stackify.test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import org.junit.jupiter.api.Tag;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
@Tag("math")
|
||||||
|
public class TaggedTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Tag("arithmetic")
|
||||||
|
public void testEquals() {
|
||||||
|
assertTrue(1 == 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,155 @@
|
|||||||
|
package com.stackify.test;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Disabled;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Nested;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.TestInfo;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.ValueSource;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.junit.jupiter.api.Assumptions.*;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.stackify.daos.UserDAO;
|
||||||
|
import com.stackify.models.User;
|
||||||
|
|
||||||
|
import com.stackify.test.conditions.DisabledOnEnvironment;
|
||||||
|
|
||||||
|
public class UsersTest implements DatabaseConnectionTest {
|
||||||
|
|
||||||
|
private static UserDAO userDAO;
|
||||||
|
|
||||||
|
private static Logger logger = LogManager.getLogger(UsersTest.class);
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
public static void addData() {
|
||||||
|
userDAO = new UserDAO();
|
||||||
|
userDAO.createTable();
|
||||||
|
|
||||||
|
User user1 = new User("john@gmail.com", "John");
|
||||||
|
User user2 = new User("ana@gmail.com", "Ana");
|
||||||
|
userDAO.add(user1);
|
||||||
|
userDAO.add(user2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Test Get Users")
|
||||||
|
public void testGetUsersNumber() {
|
||||||
|
assertEquals(2, userDAO.findAll().size());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Test Get Users")
|
||||||
|
public void testGetUsersNumberWithInfo(TestInfo testInfo) {
|
||||||
|
assertEquals(2, userDAO.findAll().size());
|
||||||
|
assertEquals("Test Get Users", testInfo.getDisplayName());
|
||||||
|
assertEquals(UsersTest.class, testInfo.getTestClass().get());
|
||||||
|
logger.info("Running test method:" + testInfo.getTestMethod().get().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetUser() {
|
||||||
|
User user = userDAO.findOne("john@gmail.com");
|
||||||
|
assertEquals("John", user.getName(), "User name:" + user.getName() + " incorrect");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testClassicAssertions() {
|
||||||
|
User user1 = userDAO.findOne("john@gmail.com");
|
||||||
|
User user2 = userDAO.findOne("john@yahoo.com");
|
||||||
|
|
||||||
|
assertNotNull(user1);
|
||||||
|
assertNull(user2);
|
||||||
|
|
||||||
|
user2 = new User("john@yahoo.com", "John");
|
||||||
|
assertEquals(user1.getName(), user2.getName(), "Names are not equal");
|
||||||
|
assertFalse(user1.getEmail().equals(user2.getEmail()), "Emails are equal");
|
||||||
|
assertNotSame(user1, user2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Disabled
|
||||||
|
public void testGroupedAssertions() {
|
||||||
|
User user = userDAO.findOne("john@gmail.com");
|
||||||
|
assertAll("user", () -> assertEquals("Johnson", user.getName()), () -> assertEquals("johnson@gmail.com", user.getEmail()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testIterableEquals() {
|
||||||
|
User user1 = new User("john@gmail.com", "John");
|
||||||
|
User user2 = new User("ana@gmail.com", "Ana");
|
||||||
|
|
||||||
|
List<User> users = new ArrayList<>();
|
||||||
|
users.add(user1);
|
||||||
|
users.add(user2);
|
||||||
|
|
||||||
|
assertIterableEquals(users, userDAO.findAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testLinesMatch() {
|
||||||
|
List<String> expectedLines = Collections.singletonList("(.*)@(.*)");
|
||||||
|
List<String> emails = Arrays.asList("john@gmail.com");
|
||||||
|
assertLinesMatch(expectedLines, emails);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testThrows() {
|
||||||
|
User user = null;
|
||||||
|
Exception exception = assertThrows(NullPointerException.class, () -> user.getName());
|
||||||
|
logger.info(exception.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisabledOnEnvironment({ "dev", "prod")
|
||||||
|
void testFail() {
|
||||||
|
fail("this test fails");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testAssumptions() {
|
||||||
|
List<User> users = userDAO.findAll();
|
||||||
|
assumeFalse(users == null);
|
||||||
|
assumeTrue(users.size() > 0);
|
||||||
|
|
||||||
|
User user1 = new User("john@gmail.com", "John");
|
||||||
|
|
||||||
|
assumingThat(users.contains(user1), () -> assertTrue(users.size() > 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@ValueSource(strings = { "john@gmail.com", "ana@gmail.com" })
|
||||||
|
public void testParameterized(String email) {
|
||||||
|
assertNotNull(userDAO.findOne(email));
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
public static void removeData() {
|
||||||
|
userDAO.deleteAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class DeleteUsersTest {
|
||||||
|
@Test
|
||||||
|
public void addUser() {
|
||||||
|
User user = new User("bob@gmail.com", "Bob");
|
||||||
|
userDAO.add(user);
|
||||||
|
assertNotNull(userDAO.findOne("bob@gmail.com"));
|
||||||
|
|
||||||
|
userDAO.delete("bob@gmail.com");
|
||||||
|
assertNull(userDAO.findOne("bob@gmail.com"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -36,7 +36,7 @@ import opennlp.tools.util.TrainingParameters;
|
|||||||
public class OpenNLP {
|
public class OpenNLP {
|
||||||
|
|
||||||
private final static Logger LOGGER = Logger.getLogger(OpenNLP.class.getName());
|
private final static Logger LOGGER = Logger.getLogger(OpenNLP.class.getName());
|
||||||
private final static String text = "To get to the south: Go to the store. Buy a compass. Use the compass. Then walk to the south.";
|
private final static String text = buildString();
|
||||||
private final static String sentence[] = new String[] { "James", "Jordan", "live", "in", "Oklahoma", "city", "." };
|
private final static String sentence[] = new String[] { "James", "Jordan", "live", "in", "Oklahoma", "city", "." };
|
||||||
|
|
||||||
private DoccatModel docCatModel;
|
private DoccatModel docCatModel;
|
||||||
@ -45,6 +45,16 @@ public class OpenNLP {
|
|||||||
new OpenNLP();
|
new OpenNLP();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static String buildString(){
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
sb.append("To get to the south:");
|
||||||
|
sb.append(" Go to the store.");
|
||||||
|
sb.append(" Buy a compass.");
|
||||||
|
sb.append(" Use the compass.");
|
||||||
|
sb.append(" Then walk to the south.");
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
public OpenNLP() {
|
public OpenNLP() {
|
||||||
try {
|
try {
|
||||||
sentenceDetector();
|
sentenceDetector();
|
||||||
@ -68,7 +78,9 @@ public class OpenNLP {
|
|||||||
SentenceModel model = new SentenceModel(is);
|
SentenceModel model = new SentenceModel(is);
|
||||||
SentenceDetectorME sdetector = new SentenceDetectorME(model);
|
SentenceDetectorME sdetector = new SentenceDetectorME(model);
|
||||||
String sentences[] = sdetector.sentDetect(text);
|
String sentences[] = sdetector.sentDetect(text);
|
||||||
Arrays.stream(sentences).forEach(LOGGER::info);
|
for (String sentence : sentences) {
|
||||||
|
LOGGER.info(sentence);
|
||||||
|
}
|
||||||
is.close();
|
is.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -77,7 +89,9 @@ public class OpenNLP {
|
|||||||
TokenizerModel model = new TokenizerModel(is);
|
TokenizerModel model = new TokenizerModel(is);
|
||||||
Tokenizer tokenizer = new TokenizerME(model);
|
Tokenizer tokenizer = new TokenizerME(model);
|
||||||
String tokens[] = tokenizer.tokenize(text);
|
String tokens[] = tokenizer.tokenize(text);
|
||||||
Arrays.stream(tokens).forEach(LOGGER::info);
|
for (String token : tokens) {
|
||||||
|
LOGGER.info(token);
|
||||||
|
}
|
||||||
is.close();
|
is.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -89,6 +103,9 @@ public class OpenNLP {
|
|||||||
Span nameSpans[] = nameFinder.find(sentence);
|
Span nameSpans[] = nameFinder.find(sentence);
|
||||||
String[] names = Span.spansToStrings(nameSpans, sentence);
|
String[] names = Span.spansToStrings(nameSpans, sentence);
|
||||||
Arrays.stream(names).forEach(LOGGER::info);
|
Arrays.stream(names).forEach(LOGGER::info);
|
||||||
|
for (String name : names) {
|
||||||
|
LOGGER.info(name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void locationFinder() throws IOException {
|
public static void locationFinder() throws IOException {
|
||||||
@ -99,6 +116,9 @@ public class OpenNLP {
|
|||||||
Span locationSpans[] = nameFinder.find(sentence);
|
Span locationSpans[] = nameFinder.find(sentence);
|
||||||
String[] locations = Span.spansToStrings(locationSpans, sentence);
|
String[] locations = Span.spansToStrings(locationSpans, sentence);
|
||||||
Arrays.stream(locations).forEach(LOGGER::info);
|
Arrays.stream(locations).forEach(LOGGER::info);
|
||||||
|
for (String location : locations) {
|
||||||
|
LOGGER.info(location);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void trainDocumentCategorizer() {
|
public void trainDocumentCategorizer() {
|
||||||
@ -160,7 +180,9 @@ public class OpenNLP {
|
|||||||
String[] taggedSentence = new String[] {"Out", "of", "the", "night", "that", "covers", "me"};
|
String[] taggedSentence = new String[] {"Out", "of", "the", "night", "that", "covers", "me"};
|
||||||
String pos[] = new String[] { "IN", "IN", "DT", "NN", "WDT", "VBZ", "PRP"};
|
String pos[] = new String[] { "IN", "IN", "DT", "NN", "WDT", "VBZ", "PRP"};
|
||||||
String chunks[] = chunkerME.chunk(taggedSentence, pos);
|
String chunks[] = chunkerME.chunk(taggedSentence, pos);
|
||||||
Arrays.stream(chunks).forEach(LOGGER::info);
|
for (String chunk : chunks) {
|
||||||
|
LOGGER.info(chunk);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
24
spring-boot-bootstrap/.gitignore
vendored
Normal file
24
spring-boot-bootstrap/.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
target/
|
||||||
|
!.mvn/wrapper/maven-wrapper.jar
|
||||||
|
|
||||||
|
### STS ###
|
||||||
|
.apt_generated
|
||||||
|
.classpath
|
||||||
|
.factorypath
|
||||||
|
.project
|
||||||
|
.settings
|
||||||
|
.springBeans
|
||||||
|
|
||||||
|
### IntelliJ IDEA ###
|
||||||
|
.idea
|
||||||
|
*.iws
|
||||||
|
*.iml
|
||||||
|
*.ipr
|
||||||
|
|
||||||
|
### NetBeans ###
|
||||||
|
nbproject/private/
|
||||||
|
build/
|
||||||
|
nbbuild/
|
||||||
|
dist/
|
||||||
|
nbdist/
|
||||||
|
.nb-gradle/
|
75
spring-boot-bootstrap/pom.xml
Normal file
75
spring-boot-bootstrap/pom.xml
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<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>org.baeldung</groupId>
|
||||||
|
<artifactId>spring-boot-bootstrap</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<name>spring-boot-bootstrap</name>
|
||||||
|
<description>Demo project for Spring Boot</description>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>1.5.3.RELEASE</version>
|
||||||
|
<relativePath /> <!-- lookup parent from repository -->
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||||
|
<java.version>1.8</java.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.rest-assured</groupId>
|
||||||
|
<artifactId>rest-assured</artifactId>
|
||||||
|
<version>3.0.3</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,19 @@
|
|||||||
|
package org.baeldung;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@ComponentScan("org.baeldung")
|
||||||
|
@EnableJpaRepositories("org.baeldung.persistence.repo")
|
||||||
|
@EntityScan("org.baeldung.persistence.model")
|
||||||
|
public class Application {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(Application.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,96 @@
|
|||||||
|
package org.baeldung.persistence.model;
|
||||||
|
|
||||||
|
import javax.persistence.Column;
|
||||||
|
import javax.persistence.Entity;
|
||||||
|
import javax.persistence.GeneratedValue;
|
||||||
|
import javax.persistence.GenerationType;
|
||||||
|
import javax.persistence.Id;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Book {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
|
private long id;
|
||||||
|
|
||||||
|
@Column(nullable = false, unique = true)
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private String author;
|
||||||
|
|
||||||
|
//
|
||||||
|
|
||||||
|
public Book() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Book(String title, String author) {
|
||||||
|
super();
|
||||||
|
this.title = title;
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTitle() {
|
||||||
|
return title;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTitle(String title) {
|
||||||
|
this.title = title;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthor() {
|
||||||
|
return author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAuthor(String author) {
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
result = prime * result + ((author == null) ? 0 : author.hashCode());
|
||||||
|
result = prime * result + (int) (id ^ (id >>> 32));
|
||||||
|
result = prime * result + ((title == null) ? 0 : title.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
Book other = (Book) obj;
|
||||||
|
if (author == null) {
|
||||||
|
if (other.author != null)
|
||||||
|
return false;
|
||||||
|
} else if (!author.equals(other.author))
|
||||||
|
return false;
|
||||||
|
if (id != other.id)
|
||||||
|
return false;
|
||||||
|
if (title == null) {
|
||||||
|
if (other.title != null)
|
||||||
|
return false;
|
||||||
|
} else if (!title.equals(other.title))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Book [id=" + id + ", title=" + title + ", author=" + author + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package org.baeldung.persistence.repo;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.baeldung.persistence.model.Book;
|
||||||
|
import org.springframework.data.repository.CrudRepository;
|
||||||
|
|
||||||
|
public interface BookRepository extends CrudRepository<Book, Long> {
|
||||||
|
List<Book> findByTitle(String title);
|
||||||
|
}
|
@ -0,0 +1,74 @@
|
|||||||
|
package org.baeldung.web;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.baeldung.persistence.model.Book;
|
||||||
|
import org.baeldung.persistence.repo.BookRepository;
|
||||||
|
import org.baeldung.web.exception.BookIdMismatchException;
|
||||||
|
import org.baeldung.web.exception.BookNotFoundException;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/books")
|
||||||
|
public class BookController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private BookRepository bookRepository;
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public Iterable<Book> findAll() {
|
||||||
|
return bookRepository.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/title/{bookTitle}")
|
||||||
|
public List<Book> findByTitle(@PathVariable String bookTitle) {
|
||||||
|
return bookRepository.findByTitle(bookTitle);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public Book findOne(@PathVariable Long id) {
|
||||||
|
final Book book = bookRepository.findOne(id);
|
||||||
|
if (book == null) {
|
||||||
|
throw new BookNotFoundException();
|
||||||
|
}
|
||||||
|
return book;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
|
public Book create(@RequestBody Book book) {
|
||||||
|
return bookRepository.save(book);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public void delete(@PathVariable Long id) {
|
||||||
|
final Book book = bookRepository.findOne(id);
|
||||||
|
if (book == null) {
|
||||||
|
throw new BookNotFoundException();
|
||||||
|
}
|
||||||
|
bookRepository.delete(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public Book updateBook(@RequestBody Book book, @PathVariable Long id) {
|
||||||
|
if (book.getId() != id) {
|
||||||
|
throw new BookIdMismatchException();
|
||||||
|
}
|
||||||
|
final Book old = bookRepository.findOne(id);
|
||||||
|
if (old == null) {
|
||||||
|
throw new BookNotFoundException();
|
||||||
|
}
|
||||||
|
return bookRepository.save(book);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package org.baeldung.web;
|
||||||
|
|
||||||
|
import org.baeldung.web.exception.BookIdMismatchException;
|
||||||
|
import org.baeldung.web.exception.BookNotFoundException;
|
||||||
|
import org.hibernate.exception.ConstraintViolationException;
|
||||||
|
import org.springframework.dao.DataIntegrityViolationException;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
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 RestExceptionHandler extends ResponseEntityExceptionHandler {
|
||||||
|
|
||||||
|
public RestExceptionHandler() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler({ BookNotFoundException.class })
|
||||||
|
protected ResponseEntity<Object> handleNotFound(Exception ex, WebRequest request) {
|
||||||
|
return handleExceptionInternal(ex, "Book not found", new HttpHeaders(), HttpStatus.NOT_FOUND, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler({ BookIdMismatchException.class, ConstraintViolationException.class, DataIntegrityViolationException.class })
|
||||||
|
public ResponseEntity<Object> handleBadRequest(Exception ex, WebRequest request) {
|
||||||
|
return handleExceptionInternal(ex, ex.getLocalizedMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,19 @@
|
|||||||
|
package org.baeldung.web;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.ui.Model;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
public class SimpleController {
|
||||||
|
@Value("${spring.application.name}")
|
||||||
|
String appName;
|
||||||
|
|
||||||
|
@RequestMapping("/")
|
||||||
|
public String homePage(Model model) {
|
||||||
|
model.addAttribute("appName", appName);
|
||||||
|
return "home";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package org.baeldung.web.exception;
|
||||||
|
|
||||||
|
public class BookIdMismatchException extends RuntimeException {
|
||||||
|
|
||||||
|
public BookIdMismatchException() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public BookIdMismatchException(final String message, final Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BookIdMismatchException(final String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BookIdMismatchException(final Throwable cause) {
|
||||||
|
super(cause);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package org.baeldung.web.exception;
|
||||||
|
|
||||||
|
public class BookNotFoundException extends RuntimeException {
|
||||||
|
|
||||||
|
public BookNotFoundException() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public BookNotFoundException(final String message, final Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BookNotFoundException(final String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BookNotFoundException(final Throwable cause) {
|
||||||
|
super(cause);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
server.port = 8081
|
||||||
|
|
||||||
|
spring.application.name = Bootstrap Spring Boot
|
||||||
|
|
||||||
|
spring.thymeleaf.cache = false
|
||||||
|
spring.thymeleaf.enabled=true
|
||||||
|
spring.thymeleaf.prefix=classpath:/templates/
|
||||||
|
spring.thymeleaf.suffix=.html
|
||||||
|
|
||||||
|
security.basic.enabled=true
|
||||||
|
security.user.name=john
|
||||||
|
security.user.password=123
|
||||||
|
|
||||||
|
|
||||||
|
spring.datasource.driver-class-name=org.h2.Driver
|
||||||
|
spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
|
||||||
|
spring.datasource.username=sa
|
||||||
|
spring.datasource.password=
|
||||||
|
|
||||||
|
server.error.path=/error
|
||||||
|
server.error.whitelabel.enabled=false
|
@ -0,0 +1,19 @@
|
|||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<title>Error Occurred</title>
|
||||||
|
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<h1>Error Occurred!</h1>
|
||||||
|
<div class="alert alert-danger" role="alert">
|
||||||
|
<b>
|
||||||
|
[<span th:text="${status}">status</span>]
|
||||||
|
<span th:text="${error}">error</span>
|
||||||
|
</b>
|
||||||
|
<p th:text="${message}">message</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
@ -0,0 +1,7 @@
|
|||||||
|
<html>
|
||||||
|
<head><title>Home Page</title></head>
|
||||||
|
<body>
|
||||||
|
<h1>Hello !</h1>
|
||||||
|
<p>Welcome to <span th:text="${appName}">Our App</span></p>
|
||||||
|
</body>
|
||||||
|
</html>
|
142
spring-boot-bootstrap/src/test/java/org/baeldung/LiveTest.java
Normal file
142
spring-boot-bootstrap/src/test/java/org/baeldung/LiveTest.java
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
package org.baeldung;
|
||||||
|
|
||||||
|
import static io.restassured.RestAssured.preemptive;
|
||||||
|
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||||
|
import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import io.restassured.RestAssured;
|
||||||
|
import io.restassured.response.Response;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.baeldung.persistence.model.Book;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(classes = { Application.class }, webEnvironment = WebEnvironment.DEFINED_PORT)
|
||||||
|
public class LiveTest {
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
RestAssured.authentication = preemptive().basic("john", "123");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final String API_ROOT = "http://localhost:8081/api/books";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetAllBooks_thenOK() {
|
||||||
|
final Response response = RestAssured.get(API_ROOT);
|
||||||
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetBooksByTitle_thenOK() {
|
||||||
|
final Book book = createRandomBook();
|
||||||
|
createBookAsUri(book);
|
||||||
|
|
||||||
|
final Response response = RestAssured.get(API_ROOT + "/title/" + book.getTitle());
|
||||||
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
|
assertTrue(response.as(List.class)
|
||||||
|
.size() > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetCreatedBookById_thenOK() {
|
||||||
|
final Book book = createRandomBook();
|
||||||
|
final String location = createBookAsUri(book);
|
||||||
|
|
||||||
|
final Response response = RestAssured.get(location);
|
||||||
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
|
assertEquals(book.getTitle(), response.jsonPath()
|
||||||
|
.get("title"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetNotExistBookById_thenNotFound() {
|
||||||
|
final Response response = RestAssured.get(API_ROOT + "/" + randomNumeric(4));
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST
|
||||||
|
@Test
|
||||||
|
public void whenCreateNewBook_thenCreated() {
|
||||||
|
final Book book = createRandomBook();
|
||||||
|
|
||||||
|
final Response response = RestAssured.given()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
.body(book)
|
||||||
|
.post(API_ROOT);
|
||||||
|
assertEquals(HttpStatus.CREATED.value(), response.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInvalidBook_thenError() {
|
||||||
|
final Book book = createRandomBook();
|
||||||
|
book.setAuthor(null);
|
||||||
|
|
||||||
|
final Response response = RestAssured.given()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
.body(book)
|
||||||
|
.post(API_ROOT);
|
||||||
|
assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUpdateCreatedBook_thenUpdated() {
|
||||||
|
final Book book = createRandomBook();
|
||||||
|
final String location = createBookAsUri(book);
|
||||||
|
|
||||||
|
book.setId(Long.parseLong(location.split("api/books/")[1]));
|
||||||
|
book.setAuthor("newAuthor");
|
||||||
|
Response response = RestAssured.given()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
.body(book)
|
||||||
|
.put(location);
|
||||||
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
|
|
||||||
|
response = RestAssured.get(location);
|
||||||
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
|
assertEquals("newAuthor", response.jsonPath()
|
||||||
|
.get("author"));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDeleteCreatedBook_thenOk() {
|
||||||
|
final Book book = createRandomBook();
|
||||||
|
final String location = createBookAsUri(book);
|
||||||
|
|
||||||
|
Response response = RestAssured.delete(location);
|
||||||
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
|
|
||||||
|
response = RestAssured.get(location);
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===============================
|
||||||
|
|
||||||
|
private Book createRandomBook() {
|
||||||
|
final Book book = new Book();
|
||||||
|
book.setTitle(randomAlphabetic(10));
|
||||||
|
book.setAuthor(randomAlphabetic(15));
|
||||||
|
return book;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String createBookAsUri(Book book) {
|
||||||
|
final Response response = RestAssured.given()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
.body(book)
|
||||||
|
.post(API_ROOT);
|
||||||
|
return API_ROOT + "/" + response.jsonPath()
|
||||||
|
.get("id");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package org.baeldung;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest
|
||||||
|
public class SpringBootBootstrapApplicationTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void contextLoads() {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user