Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Christian Raedel 2016-09-05 18:37:27 +02:00
commit b755cd94dc
26 changed files with 351 additions and 471 deletions

View File

@ -18,10 +18,6 @@ public abstract class Animal implements Eating {
this.name = name;
}
public String makeSound() {
return getSound();
}
protected abstract String getSound();
}

View File

@ -8,9 +8,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import static org.junit.Assert.*;
public class ReflectionTest {
@ -24,7 +22,6 @@ public class ReflectionTest {
assertTrue(Arrays.asList("name", "age")
.containsAll(actualFieldNames));
}
@Test
@ -127,7 +124,7 @@ public class ReflectionTest {
assertEquals(4, actualMethods.size());
assertTrue(actualMethods.containsAll(Arrays.asList("getName",
"setName", "getSound", "makeSound")));
"setName", "getSound")));
}
@Test
@ -311,16 +308,19 @@ public class ReflectionTest {
}
private static List<String> getMethodNames(Method[] methods) {
return Stream.of(methods)
.map((Method::getName))
.collect(toList());
}
private static List<String> getFieldNames(Field[] fields) {
List<String> fieldNames = new ArrayList<>();
for (Field field : fields)
fieldNames.add(field.getName());
return fieldNames;
private static List<String> getFieldNames(Field[] fields) {
return Stream.of(fields)
.map(Field::getName)
.collect(toList());
}
}
private static List<String> getMethodNames(Method[] methods) {
List<String> methodNames = new ArrayList<>();
for (Method method : methods)
methodNames.add(method.getName());
return methodNames;
}
}

View File

@ -0,0 +1,43 @@
<?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>
<artifactId>front-controller-pattern</artifactId>
<packaging>war</packaging>
<parent>
<artifactId>enterprise-patterns-parent</artifactId>
<groupId>com.baeldung.enterprise.patterns</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.0.M1</version>
<configuration>
<webApp>
<contextPath>/front-controller</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,45 @@
package com.baeldung.enterprise.patterns.front.controller;
import com.baeldung.enterprise.patterns.front.controller.commands.FrontCommand;
import com.baeldung.enterprise.patterns.front.controller.commands.UnknownCommand;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class FrontControllerServlet extends HttpServlet {
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
FrontCommand command = getCommand(request);
command.init(getServletContext(), request, response);
command.process();
}
private FrontCommand getCommand(HttpServletRequest request) {
try {
return (FrontCommand) getCommandClass(request)
.asSubclass(FrontCommand.class)
.newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to get command!", e);
}
}
private Class getCommandClass(HttpServletRequest request) {
try {
return Class.forName(
String.format(
"com.baeldung.enterprise.patterns.front.controller.commands.%sCommand",
request.getParameter("command")
)
);
} catch (ClassNotFoundException e) {
return UnknownCommand.class;
}
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.enterprise.patterns.front.controller.commands;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public abstract class FrontCommand {
protected ServletContext context;
protected HttpServletRequest request;
protected HttpServletResponse response;
public void init(
ServletContext servletContext,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse
) {
this.context = servletContext;
this.request = servletRequest;
this.response = servletResponse;
}
public abstract void process() throws ServletException, IOException;
protected void forward(String target) throws ServletException, IOException {
target = String.format("/WEB-INF/jsp/%s.jsp", target);
RequestDispatcher dispatcher = context.getRequestDispatcher(target);
dispatcher.forward(request, response);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.enterprise.patterns.front.controller.commands;
import com.baeldung.enterprise.patterns.front.controller.data.Book;
import com.baeldung.enterprise.patterns.front.controller.data.BookshelfImpl;
import javax.servlet.ServletException;
import java.io.IOException;
public class SearchCommand extends FrontCommand {
@Override
public void process() throws ServletException, IOException {
Book book = new BookshelfImpl().getInstance()
.findByTitle(request.getParameter("title"));
if (book != null) {
request.setAttribute("book", book);
forward("book-found");
} else {
forward("book-notfound");
}
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.enterprise.patterns.front.controller.commands;
import javax.servlet.ServletException;
import java.io.IOException;
public class UnknownCommand extends FrontCommand {
@Override
public void process() throws ServletException, IOException {
forward("unknown");
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.enterprise.patterns.front.controller.data;
public class Book {
private String author;
private String title;
private Double price;
public Book() {
}
public Book(String author, String title, Double price) {
this.author = author;
this.title = title;
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.enterprise.patterns.front.controller.data;
public interface Bookshelf {
default void init() {
add(new Book("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99));
add(new Book("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88));
}
Bookshelf getInstance();
<E extends Book> boolean add(E book);
Book findByTitle(String title);
}

View File

@ -0,0 +1,24 @@
package com.baeldung.enterprise.patterns.front.controller.data;
import java.util.ArrayList;
public class BookshelfImpl extends ArrayList<Book> implements Bookshelf {
private static Bookshelf INSTANCE;
@Override
public Bookshelf getInstance() {
if (INSTANCE == null) {
INSTANCE = new BookshelfImpl();
INSTANCE.init();
}
return INSTANCE;
}
@Override
public Book findByTitle(String title) {
return this.stream()
.filter(book -> book.getTitle().toLowerCase().contains(title.toLowerCase()))
.findFirst()
.orElse(null);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

View File

@ -0,0 +1,22 @@
@startuml
class Handler {
doGet
doPost
}
abstract class AbstractCommand {
process
}
class ConcreteCommand1 {
process
}
class ConcreteCommand2 {
process
}
Handler .right.> AbstractCommand
AbstractCommand <|-- ConcreteCommand1
AbstractCommand <|-- ConcreteCommand2
@enduml

View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<title>Bookshelf: Title found</title>
</head>
<body>
<p>Our Bookshelf contains this title:</p>
<h2>${book.getTitle()}</h2>
<p>Author: ${book.getAuthor()}</p>
<input type="submit" value="Buy it: ${book.getPrice()}$">
</body>
</html>

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Bookshelf: Title not found</title>
</head>
<body>
<p>Our Bookshelf doesn't contains this title:</p>
<h2>${param.get("title")}</h2>
</body>
</html>

View File

@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<title>Bookshelf: Command unknown</title>
</head>
<body>
<p>Sorry, this command is not known!</p>
</body>
</html>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>front-controller</servlet-name>
<servlet-class>com.baeldung.enterprise.patterns.front.controller.FrontControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>front-controller</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

View File

@ -0,0 +1,35 @@
<?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>com.baeldung.enterprise.patterns</groupId>
<artifactId>enterprise-patterns-parent</artifactId>
<packaging>pom</packaging>
<modules>
<module>front-controller-pattern</module>
</modules>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -29,6 +29,8 @@
<module>dozer</module>
<module>dependency-injection</module>
<module>deltaspike</module>
<module>enterprise-patterns</module>
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
<module>gson</module>

View File

@ -1,30 +0,0 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>reflection</artifactId>
<version>1.0</version>
<name>reflection</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.3</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,23 +0,0 @@
package com.baeldung.reflection;
public abstract class Animal implements Eating {
public static final String CATEGORY = "domestic";
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
protected abstract String getSound();
}

View File

@ -1,36 +0,0 @@
package com.baeldung.reflection;
public class Bird extends Animal {
private boolean walks;
public Bird() {
super("bird");
}
public Bird(String name, boolean walks) {
super(name);
setWalks(walks);
}
public Bird(String name) {
super(name);
}
@Override
public String eats() {
return "grains";
}
@Override
protected String getSound() {
return "chaps";
}
public boolean walks() {
return walks;
}
public void setWalks(boolean walks) {
this.walks = walks;
}
}

View File

@ -1,5 +0,0 @@
package com.baeldung.reflection;
public interface Eating {
String eats();
}

View File

@ -1,24 +0,0 @@
package com.baeldung.reflection;
public class Goat extends Animal implements Locomotion {
public Goat(String name) {
super(name);
}
@Override
protected String getSound() {
return "bleat";
}
@Override
public String getLocomotion() {
return "walks";
}
@Override
public String eats() {
return "grass";
}
}

View File

@ -1,5 +0,0 @@
package com.baeldung.reflection;
public interface Locomotion {
String getLocomotion();
}

View File

@ -1,6 +0,0 @@
package com.baeldung.reflection;
public class Person {
private String name;
private int age;
}

View File

@ -1,323 +0,0 @@
package com.baeldung.reflection;
import org.junit.Test;
import java.lang.reflect.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.*;
public class ReflectionTest {
@Test
public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
Object person = new Person();
Field[] fields = person.getClass().getDeclaredFields();
List<String> actualFieldNames = getFieldNames(fields);
assertTrue(Arrays.asList("name", "age")
.containsAll(actualFieldNames));
}
@Test
public void givenObject_whenGetsClassName_thenCorrect() {
Object goat = new Goat("goat");
Class<?> clazz = goat.getClass();
assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
}
@Test
public void givenClassName_whenCreatesObject_thenCorrect()
throws ClassNotFoundException {
Class<?> clazz = Class.forName("com.baeldung.reflection.Goat");
assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
}
@Test
public void givenClass_whenRecognisesModifiers_thenCorrect()
throws ClassNotFoundException {
Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
int goatMods = goatClass.getModifiers();
int animalMods = animalClass.getModifiers();
assertTrue(Modifier.isPublic(goatMods));
assertTrue(Modifier.isAbstract(animalMods));
assertTrue(Modifier.isPublic(animalMods));
}
@Test
public void givenClass_whenGetsPackageInfo_thenCorrect() {
Goat goat = new Goat("goat");
Class<?> goatClass = goat.getClass();
Package pkg = goatClass.getPackage();
assertEquals("com.baeldung.reflection", pkg.getName());
}
@Test
public void givenClass_whenGetsSuperClass_thenCorrect() {
Goat goat = new Goat("goat");
String str = "any string";
Class<?> goatClass = goat.getClass();
Class<?> goatSuperClass = goatClass.getSuperclass();
assertEquals("Animal", goatSuperClass.getSimpleName());
assertEquals("Object", str.getClass().getSuperclass().getSimpleName());
}
@Test
public void givenClass_whenGetsImplementedInterfaces_thenCorrect()
throws ClassNotFoundException {
Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
Class<?>[] goatInterfaces = goatClass.getInterfaces();
Class<?>[] animalInterfaces = animalClass.getInterfaces();
assertEquals(1, goatInterfaces.length);
assertEquals(1, animalInterfaces.length);
assertEquals("Locomotion", goatInterfaces[0].getSimpleName());
assertEquals("Eating", animalInterfaces[0].getSimpleName());
}
@Test
public void givenClass_whenGetsConstructor_thenCorrect()
throws ClassNotFoundException {
Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
Constructor<?>[] constructors = goatClass.getConstructors();
assertEquals(1, constructors.length);
assertEquals("com.baeldung.reflection.Goat", constructors[0].getName());
}
@Test
public void givenClass_whenGetsFields_thenCorrect()
throws ClassNotFoundException {
Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
Field[] fields = animalClass.getDeclaredFields();
List<String> actualFields = getFieldNames(fields);
assertEquals(2, actualFields.size());
assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY")));
}
@Test
public void givenClass_whenGetsMethods_thenCorrect()
throws ClassNotFoundException {
Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
Method[] methods = animalClass.getDeclaredMethods();
List<String> actualMethods = getMethodNames(methods);
assertEquals(4, actualMethods.size());
assertTrue(actualMethods.containsAll(Arrays.asList("getName",
"setName", "getSound", "makeSound")));
}
@Test
public void givenClass_whenGetsAllConstructors_thenCorrect()
throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Constructor<?>[] constructors = birdClass.getConstructors();
assertEquals(3, constructors.length);
}
@Test
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect()
throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Constructor<?> cons1 = birdClass.getConstructor();
Constructor<?> cons2 = birdClass.getConstructor(String.class);
Constructor<?> cons3 = birdClass.getConstructor(String.class,
boolean.class);
}
@Test
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect()
throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Constructor<?> cons1 = birdClass.getConstructor();
Constructor<?> cons2 = birdClass.getConstructor(String.class);
Constructor<?> cons3 = birdClass.getConstructor(String.class,
boolean.class);
Bird bird1 = (Bird) cons1.newInstance();
Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
Bird bird3 = (Bird) cons3.newInstance("dove", true);
assertEquals("bird", bird1.getName());
assertEquals("Weaver bird", bird2.getName());
assertEquals("dove", bird3.getName());
assertFalse(bird1.walks());
assertTrue(bird3.walks());
}
@Test
public void givenClass_whenGetsPublicFields_thenCorrect()
throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Field[] fields = birdClass.getFields();
assertEquals(1, fields.length);
assertEquals("CATEGORY", fields[0].getName());
}
@Test
public void givenClass_whenGetsPublicFieldByName_thenCorrect()
throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Field field = birdClass.getField("CATEGORY");
assertEquals("CATEGORY", field.getName());
}
@Test
public void givenClass_whenGetsDeclaredFields_thenCorrect()
throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Field[] fields = birdClass.getDeclaredFields();
assertEquals(1, fields.length);
assertEquals("walks", fields[0].getName());
}
@Test
public void givenClass_whenGetsFieldsByName_thenCorrect()
throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Field field = birdClass.getDeclaredField("walks");
assertEquals("walks", field.getName());
}
@Test
public void givenClassField_whenGetsType_thenCorrect()
throws Exception {
Field field = Class.forName("com.baeldung.reflection.Bird")
.getDeclaredField("walks");
Class<?> fieldClass = field.getType();
assertEquals("boolean", fieldClass.getSimpleName());
}
@Test
public void givenClassField_whenSetsAndGetsValue_thenCorrect()
throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Bird bird = (Bird) birdClass.newInstance();
Field field = birdClass.getDeclaredField("walks");
field.setAccessible(true);
assertFalse(field.getBoolean(bird));
assertFalse(bird.walks());
field.set(bird, true);
assertTrue(field.getBoolean(bird));
assertTrue(bird.walks());
}
@Test
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect()
throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Field field = birdClass.getField("CATEGORY");
field.setAccessible(true);
assertEquals("domestic", field.get(null));
}
@Test
public void givenClass_whenGetsAllPublicMethods_thenCorrect()
throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Method[] methods = birdClass.getMethods();
List<String> methodNames = getMethodNames(methods);
assertTrue(methodNames.containsAll(Arrays
.asList("equals", "notifyAll", "hashCode",
"walks", "eats", "toString")));
}
@Test
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect()
throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
assertEquals(expectedMethodNames.size(), actualMethodNames.size());
assertTrue(expectedMethodNames.containsAll(actualMethodNames));
assertTrue(actualMethodNames.containsAll(expectedMethodNames));
}
@Test
public void givenMethodName_whenGetsMethod_thenCorrect()
throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Method walksMethod = birdClass.getDeclaredMethod("walks");
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks",
boolean.class);
assertFalse(walksMethod.isAccessible());
assertFalse(setWalksMethod.isAccessible());
walksMethod.setAccessible(true);
setWalksMethod.setAccessible(true);
assertTrue(walksMethod.isAccessible());
assertTrue(setWalksMethod.isAccessible());
}
@Test
public void givenMethod_whenInvokes_thenCorrect()
throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
Bird bird = (Bird) birdClass.newInstance();
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks",
boolean.class);
Method walksMethod = birdClass.getDeclaredMethod("walks");
boolean walks = (boolean) walksMethod.invoke(bird);
assertFalse(walks);
assertFalse(bird.walks());
setWalksMethod.invoke(bird, true);
boolean walks2 = (boolean) walksMethod.invoke(bird);
assertTrue(walks2);
assertTrue(bird.walks());
}
private static List<String> getMethodNames(Method[] methods) {
return Stream.of(methods)
.map((Method::getName))
.collect(toList());
}
private static List<String> getFieldNames(Field[] fields) {
return Stream.of(fields)
.map(Field::getName)
.collect(toList());
}
}