Merge branch 'master' into sla-pr/1423-jesus-custom-validator

This commit is contained in:
slavisa-baeldung
2017-03-18 09:01:34 +00:00
83 changed files with 1919 additions and 623 deletions
-1
View File
@@ -5,7 +5,6 @@ install: travis_wait 40 mvn -q clean install -Dgib.enabled=true
jdk:
- oraclejdk8
sudo: false
addons:
apt:
packages:
+1
View File
@@ -0,0 +1 @@
javac -d mods --module-source-path src/modules $(find src/modules -name "*.java")
+3
View File
@@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.client^
src/modules/com.baeldung.student.client/module-info.java^
src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java
+2
View File
@@ -0,0 +1,2 @@
javac -d mods/com.baeldung.student.model src/modules/com.baeldung.student.model/module-info.java^
src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java
@@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.service.dbimpl^
src/modules/com.baeldung.student.service.dbimpl/module-info.java^
src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java
+3
View File
@@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.service^
src/modules/com.baeldung.student.service/module-info.java^
src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java
+1
View File
@@ -0,0 +1 @@
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient
+1
View File
@@ -0,0 +1 @@
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient
@@ -0,0 +1,16 @@
package com.baeldung.student.client;
import com.baeldung.student.service.StudentService;
import com.baeldung.student.service.dbimpl.StudentDbService;
import com.baeldung.student.model.Student;
public class StudentClient {
public static void main(String[] args) {
StudentService service = new StudentDbService();
service.create(new Student());
service.read("17SS0001");
service.update(new Student());
service.delete("17SS0001");
}
}
@@ -0,0 +1,3 @@
module com.baeldung.student.client{
requires com.baeldung.student.service.dbimpl;
}
@@ -0,0 +1,15 @@
package com.baeldung.student.model;
import java.util.Date;
public class Student {
private String registrationId;
public String getRegistrationId() {
return registrationId;
}
public void setRegistrationId(String registrationId) {
this.registrationId = registrationId;
}
}
@@ -0,0 +1,3 @@
module com.baeldung.student.model{
exports com.baeldung.student.model;
}
@@ -0,0 +1,30 @@
package com.baeldung.student.service.dbimpl;
import com.baeldung.student.service.StudentService;
import com.baeldung.student.model.Student;
import java.util.logging.*;
public class StudentDbService implements StudentService {
private static Logger logger = Logger.getLogger("StudentDbService");
public String create(Student student) {
logger.log(Level.INFO, "Creating student in DB...");
return student.getRegistrationId();
}
public Student read(String registrationId) {
logger.log(Level.INFO, "Reading student from DB...");
return new Student();
}
public Student update(Student student) {
logger.log(Level.INFO, "Updating sutdent in DB...");
return student;
}
public String delete(String registrationId) {
logger.log(Level.INFO, "Deleteing sutdent in DB...");
return registrationId;
}
}
@@ -0,0 +1,5 @@
module com.baeldung.student.service.dbimpl{
requires transitive com.baeldung.student.service;
exports com.baeldung.student.service.dbimpl;
requires java.logging;
}
@@ -0,0 +1,14 @@
package com.baeldung.student.service;
import com.baeldung.student.model.Student;
public interface StudentService {
public String create(Student student);
public Student read(String registrationId);
public Student update(Student student);
public String delete(String registrationId);
}
@@ -0,0 +1,4 @@
module com.baeldung.student.service{
requires transitive com.baeldung.student.model;
exports com.baeldung.student.service;
}
@@ -1,17 +0,0 @@
package com.baeldung.list.flattennestedlist;
import java.util.ArrayList;
import java.util.List;
public class FlattenNestedList {
public List<String> flattenListOfLists(List<List<String>> lol) {
// flatten the list
List<String> ls = new ArrayList<>();
lol.forEach((k) -> ls.addAll(k));
return ls;
}
}
@@ -1,52 +1,64 @@
package com.baeldung.list.flattennestedlist;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FlattenNestedListTest {
private static final Logger LOGGER = LoggerFactory.getLogger(FlattenNestedListTest.class);
private FlattenNestedList flol;
@Before
public void setup() {
flol = new FlattenNestedList();
}
@Test
public void givenListOfListOfString_flattenNestedList() {
// create the list to flatten
public void givenListOfListOfString_flattenNestedList1() {
// given
List<String> ls1 = Arrays.asList("one:one", "one:two", "one:three");
List<String> ls2 = Arrays.asList("two:one", "two:two", "two:three");
List<String> ls3 = Arrays.asList("three:one", "three:two", "three:three");
List<List<String>> lol = new ArrayList<>();
lol.addAll(Arrays.asList(ls1, ls2, ls3));
// show nested list
LOGGER.debug("\nNested list: ");
lol.forEach((nl) -> LOGGER.debug(nl + ""));
List<List<String>> list = Arrays.asList(ls1, ls2, ls3);
// flatten it
List<String> ls = flol.flattenListOfLists(lol);
// when
List<String> ls = flattenListOfListsImperatively(list);
// then
assertNotNull(ls);
assertTrue(ls.size() == 9);
// show flattened list
LOGGER.debug("\nFlattened list:");
ls.forEach((l) -> LOGGER.debug(l));
//TODO content assertion
}
@Test
public void givenListOfListOfString_flattenNestedList2() {
// given
List<String> ls1 = Arrays.asList("one:one", "one:two", "one:three");
List<String> ls2 = Arrays.asList("two:one", "two:two", "two:three");
List<String> ls3 = Arrays.asList("three:one", "three:two", "three:three");
List<List<String>> list = Arrays.asList(ls1, ls2, ls3);
// when
List<String> ls = flattenListOfListsStream(list);
// then
assertNotNull(ls);
assertTrue(ls.size() == 9);
//TODO content assertion
}
public <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
List<T> ls = new ArrayList<>();
list.forEach(ls::addAll);
return ls;
}
public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
}
+4
View File
@@ -0,0 +1,4 @@
## Google Guice Tutorials Project
### Relevant Articles
- [Guide to Google Guice](http://www.baeldung.com/guice)
+7 -1
View File
@@ -23,7 +23,7 @@
</plugins>
</build>
<dependencies>
<dependencies>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
@@ -51,6 +51,11 @@
<artifactId>javatuples</artifactId>
<version>${javatuples.version}</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javaassist.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.assertj/assertj-core -->
<dependency>
<groupId>org.assertj</groupId>
@@ -65,6 +70,7 @@
<junit.version>4.12</junit.version>
<jasypt.version>1.9.2</jasypt.version>
<javatuples.version>1.2</javatuples.version>
<javaassist.version>3.21.0-GA</javaassist.version>
<assertj.version>3.6.2</assertj.version>
</properties>
@@ -0,0 +1,17 @@
package com.baeldung.javasisst;
public class Point {
public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void move(int x, int y) {
this.x = x;
this.y = y;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.javasisst;
public class ThreeDimensionalPoint {
public int x = 0;
public int y = 0;
public int z = 0;
public ThreeDimensionalPoint(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public void move(int x, int y) {
this.x = x;
this.y = y;
}
}
@@ -0,0 +1,119 @@
package com.baeldung.javassist;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.NotFoundException;
import javassist.bytecode.*;
import org.junit.Test;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class JavasisstTest {
@Test
public void givenJavasisstAPI_whenConstructClass_thenGenerateAClassFile() throws CannotCompileException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
//given
String classNameWithPackage = "com.baeldung.JavassistGeneratedClass";
ClassFile cf = new ClassFile(false, classNameWithPackage, null);
cf.setInterfaces(new String[]{"java.lang.Cloneable"});
FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I");
f.setAccessFlags(AccessFlag.PUBLIC);
cf.addField(f);
//when
String className = "JavassistGeneratedClass.class";
cf.write(new DataOutputStream(new FileOutputStream(className)));
//then
ClassPool classPool = ClassPool.getDefault();
Field[] fields = classPool.makeClass(cf).toClass().getFields();
assertEquals(fields[0].getName(), "id");
String classContent = new String(Files.readAllBytes(Paths.get(className)));
assertTrue(classContent.contains("java/lang/Cloneable"));
}
@Test
public void givenJavaClass_whenLoadAtByJavassist_thenTraversWholeClass() throws NotFoundException, CannotCompileException, BadBytecode {
//given
ClassPool cp = ClassPool.getDefault();
ClassFile cf = cp.get("com.baeldung.javasisst.Point").getClassFile();
MethodInfo minfo = cf.getMethod("move");
CodeAttribute ca = minfo.getCodeAttribute();
CodeIterator ci = ca.iterator();
//when
List<String> operations = new LinkedList<>();
while (ci.hasNext()) {
int index = ci.next();
int op = ci.byteAt(index);
operations.add(Mnemonic.OPCODE[op]);
}
//then
assertEquals(operations,
Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return"));
}
@Test
public void givenTableOfInstructions_whenAddNewInstruction_thenShouldConstructProperSequence() throws NotFoundException, BadBytecode, CannotCompileException, IllegalAccessException, InstantiationException {
//given
ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.ThreeDimensionalPoint").getClassFile();
//when
FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I");
f.setAccessFlags(AccessFlag.PUBLIC);
cf.addField(f);
ClassPool classPool = ClassPool.getDefault();
Field[] fields = classPool.makeClass(cf).toClass().getFields();
List<String> fieldsList = Stream.of(fields).map(Field::getName).collect(Collectors.toList());
assertTrue(fieldsList.contains("id"));
}
@Test
public void givenLoadedClass_whenAddConstructorToClass_shouldCreateClassWithConstructor() throws NotFoundException, CannotCompileException, BadBytecode {
//given
ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.Point").getClassFile();
Bytecode code = new Bytecode(cf.getConstPool());
code.addAload(0);
code.addInvokespecial("java/lang/Object", MethodInfo.nameInit, "()V");
code.addReturn(null);
//when
MethodInfo minfo = new MethodInfo(cf.getConstPool(), MethodInfo.nameInit, "()V");
minfo.setCodeAttribute(code.toCodeAttribute());
cf.addMethod(minfo);
//then
CodeIterator ci = code.toCodeAttribute().iterator();
List<String> operations = new LinkedList<>();
while (ci.hasNext()) {
int index = ci.next();
int op = ci.byteAt(index);
operations.add(Mnemonic.OPCODE[op]);
}
assertEquals(operations,
Arrays.asList("aload_0", "invokespecial", "return"));
}
}
+3
View File
@@ -4,6 +4,7 @@ buildscript {
}
dependencies {
classpath "io.ratpack:ratpack-gradle:1.4.5"
classpath "com.h2database:h2:1.4.193"
}
}
@@ -19,6 +20,8 @@ repositories {
}
dependencies {
compile ratpack.dependency('hikari')
compile 'com.h2database:h2:1.4.193'
testCompile 'junit:junit:4.11'
runtime "org.slf4j:slf4j-simple:1.7.21"
}
+35 -16
View File
@@ -15,22 +15,41 @@
</properties>
<dependencies>
<dependency>
<groupId>io.ratpack</groupId>
<artifactId>ratpack-core</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>io.ratpack</groupId>
<artifactId>ratpack-test</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.ratpack</groupId>
<artifactId>ratpack-core</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>io.ratpack</groupId>
<artifactId>ratpack-hikari</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>io.ratpack</groupId>
<artifactId>ratpack-test</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>
@@ -1,22 +1,48 @@
package com.baeldung;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.filter.RequestValidatorFilter;
import com.baeldung.model.Employee;
import ratpack.guice.Guice;
import ratpack.hikari.HikariModule;
import ratpack.http.MutableHeaders;
import ratpack.jackson.Jackson;
import ratpack.http.MutableHeaders;
import ratpack.server.RatpackServer;
public class Application {
public static void main(String... args) throws Exception {
RatpackServer.start(server -> server.handlers(chain -> chain.all(ctx -> {
MutableHeaders headers = ctx.getResponse().getHeaders();
headers.set("Access-Control-Allow-Origin", "*");
headers.set("Accept-Language", "en-us");
headers.set("Accept-Charset", "UTF-8");
ctx.next();
})
.get(ctx -> ctx.render("Welcome to baeldung ratpack!!!"))
.get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens().get("name") + "!!!"))
.post(":amount", ctx -> ctx.render(" Amount $" + ctx.getPathTokens().get("amount") + " added successfully !!!"))
));
public static void main(String[] args) throws Exception {
List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee(1L, "Mr", "John Doe"));
employees.add(new Employee(2L, "Mr", "White Snow"));
RatpackServer.start(
server -> server.registry(Guice.registry(bindings -> bindings.module(HikariModule.class, config -> {
config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
config.addDataSourceProperty("URL",
"jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'");
}))).handlers(chain -> chain
.all(
// ctx -> {
// MutableHeaders headers =
// ctx.getResponse().getHeaders();
// headers.set("Access-Control-Allow-Origin","*");
// headers.set("Accept-Language", "en-us");
// headers.set("Accept-Charset", "UTF-8");
// ctx.next();
// }
new RequestValidatorFilter())
.get(ctx -> ctx.render("Welcome to baeldung ratpack!!!"))
.get("data/employees", ctx -> ctx.render(Jackson.json(employees)))
.get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens().get("name") + "!!!"))
.post(":amount", ctx -> ctx
.render(" Amount $" + ctx.getPathTokens().get("amount") + " added successfully !!!"))));
}
}
@@ -0,0 +1,16 @@
package com.baeldung.filter;
import ratpack.handling.Context;
import ratpack.handling.Handler;
import ratpack.http.MutableHeaders;
public class RequestValidatorFilter implements Handler {
@Override
public void handle(Context ctx) throws Exception {
MutableHeaders headers = ctx.getResponse().getHeaders();
headers.set("Access-Control-Allow-Origin", "*");
ctx.next();
}
}
@@ -0,0 +1,44 @@
package com.baeldung.model;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 3077867088762010705L;
private Long id;
private String title;
private String name;
public Employee(Long id, String title, String name) {
super();
this.id = id;
this.title = title;
this.name = name;
}
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 getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
+6
View File
@@ -0,0 +1,6 @@
DROP TABLE IF EXISTS employee;
CREATE TABLE employee (
id bigint auto_increment primary key,
title varchar(255),
name varchar(255)
)
@@ -4,10 +4,17 @@ import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.baeldung.model.Employee;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ratpack.test.MainClassApplicationUnderTest;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
@RunWith(JUnit4.class)
public class ApplicationTest {
@@ -23,6 +30,16 @@ public class ApplicationTest {
assertEquals("Hello dummybot!!!", appUnderTest.getHttpClient().getText("/dummybot"));
}
@Test
public void givenUrl_getListOfEmployee() throws JsonProcessingException {
List<Employee> employees = new ArrayList<Employee>();
ObjectMapper mapper = new ObjectMapper();
employees.add(new Employee(1L, "Mr", "John Doe"));
employees.add(new Employee(2L, "Mr", "White Snow"));
assertEquals(mapper.writeValueAsString(employees), appUnderTest.getHttpClient().getText("/data/employees"));
}
@After
public void shutdown() {
appUnderTest.close();

Some files were not shown because too many files have changed in this diff Show More