From 2435e66439c95c2dd36baf0ad89e2bcc07671b92 Mon Sep 17 00:00:00 2001 From: sghosh Date: Mon, 4 Jan 2016 00:15:43 +0530 Subject: [PATCH 001/121] Source code for Intro to QueryDSL article. --- querydsl/pom.xml | 187 ++++++++++++++++++ .../main/java/org/baeldung/dao/PersonDao.java | 12 ++ .../java/org/baeldung/dao/PersonDaoImpl.java | 30 +++ .../main/java/org/baeldung/entity/Person.java | 50 +++++ .../main/resources/META-INF/persistence.xml | 19 ++ querydsl/src/main/resources/log4j.xml | 42 ++++ .../java/org/baeldung/dao/PersonDaoTest.java | 33 ++++ querydsl/src/test/resources/db.properties | 6 + querydsl/src/test/resources/test-context.xml | 20 ++ querydsl/src/test/resources/test-db.xml | 49 +++++ 10 files changed, 448 insertions(+) create mode 100644 querydsl/pom.xml create mode 100644 querydsl/src/main/java/org/baeldung/dao/PersonDao.java create mode 100644 querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java create mode 100644 querydsl/src/main/java/org/baeldung/entity/Person.java create mode 100644 querydsl/src/main/resources/META-INF/persistence.xml create mode 100644 querydsl/src/main/resources/log4j.xml create mode 100644 querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java create mode 100644 querydsl/src/test/resources/db.properties create mode 100644 querydsl/src/test/resources/test-context.xml create mode 100644 querydsl/src/test/resources/test-db.xml diff --git a/querydsl/pom.xml b/querydsl/pom.xml new file mode 100644 index 0000000000..4efb5dcb8b --- /dev/null +++ b/querydsl/pom.xml @@ -0,0 +1,187 @@ + + + 4.0.0 + + org.baeldung + querydsl + 0.1-SNAPSHOT + jar + + querydsl + http://maven.apache.org + + + UTF-8 + 1.6 + 4.10 + 3.1.0.RELEASE + 4.1.1.Final + 2.5.0 + 1.5.10 + + + + + + com.mysema.querydsl + querydsl-core + ${querydsl.version} + + + + com.mysema.querydsl + querydsl-jpa + ${querydsl.version} + + + + com.mysema.querydsl + querydsl-apt + ${querydsl.version} + provided + + + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + compile + + + + org.hibernate.javax.persistence + hibernate-jpa-2.0-api + 1.0.0.Final + compile + + + + commons-dbcp + commons-dbcp + 1.4 + jar + compile + + + + commons-pool + commons-pool + 1.5.5 + jar + compile + + + + + org.hsqldb + hsqldb-j5 + 2.2.4 + + + + + org.springframework + spring-context + ${spring.version} + + + + org.springframework + spring-webmvc + ${spring.version} + + + + org.springframework + spring-orm + ${spring.version} + jar + compile + + + + org.springframework + spring-aop + ${spring.version} + + + + org.springframework + spring-test + ${spring.version} + jar + test + + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + jcl-over-slf4j + ${slf4j.version} + runtime + + + org.slf4j + slf4j-log4j12 + ${slf4j.version} + runtime + + + log4j + log4j + 1.2.16 + + + + + junit + junit + ${junit.version} + test + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + ${java.version} + ${java.version} + -proc:none + + + + + + com.mysema.maven + maven-apt-plugin + 1.0.3 + + + + process + + + target/metamodel + com.mysema.query.apt.jpa.JPAAnnotationProcessor + + + + + + + \ No newline at end of file diff --git a/querydsl/src/main/java/org/baeldung/dao/PersonDao.java b/querydsl/src/main/java/org/baeldung/dao/PersonDao.java new file mode 100644 index 0000000000..cc193de44b --- /dev/null +++ b/querydsl/src/main/java/org/baeldung/dao/PersonDao.java @@ -0,0 +1,12 @@ +package org.baeldung.dao; + +import org.baeldung.entity.Person; + +import java.util.List; + +public interface PersonDao { + + public Person save(Person person); + + public List findPersonsByFirstnameQueryDSL(String firstname); +} \ No newline at end of file diff --git a/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java b/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java new file mode 100644 index 0000000000..82ee4c16cd --- /dev/null +++ b/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java @@ -0,0 +1,30 @@ +package org.baeldung.dao; + +import com.mysema.query.jpa.impl.JPAQuery; +import org.baeldung.entity.Person; +import org.baeldung.entity.QPerson; +import org.springframework.stereotype.Repository; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import java.util.List; + +@Repository +public class PersonDaoImpl implements PersonDao { + + @PersistenceContext + private EntityManager em; + + public Person save(Person person) { + em.persist(person); + return person; + } + + public List findPersonsByFirstnameQueryDSL(String firstname) { + JPAQuery query = new JPAQuery(em); + QPerson person = QPerson.person; + + return query.from(person).where(person.firstname.eq(firstname)).list(person); + } + +} \ No newline at end of file diff --git a/querydsl/src/main/java/org/baeldung/entity/Person.java b/querydsl/src/main/java/org/baeldung/entity/Person.java new file mode 100644 index 0000000000..d9b0a5a97d --- /dev/null +++ b/querydsl/src/main/java/org/baeldung/entity/Person.java @@ -0,0 +1,50 @@ +package org.baeldung.entity; + +import javax.persistence.*; + +@Entity +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column + private String firstname; + + @Column + private String surname; + + Person() { + } + + public Person(String firstname, String surname) { + this.firstname = firstname; + this.surname = surname; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } + +} \ No newline at end of file diff --git a/querydsl/src/main/resources/META-INF/persistence.xml b/querydsl/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..111d7933c3 --- /dev/null +++ b/querydsl/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/querydsl/src/main/resources/log4j.xml b/querydsl/src/main/resources/log4j.xml new file mode 100644 index 0000000000..a7f96b38a4 --- /dev/null +++ b/querydsl/src/main/resources/log4j.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java b/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java new file mode 100644 index 0000000000..29d4dd98e9 --- /dev/null +++ b/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java @@ -0,0 +1,33 @@ +package org.baeldung.dao; + +import junit.framework.Assert; +import org.baeldung.entity.Person; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.transaction.TransactionConfiguration; +import org.springframework.transaction.annotation.Transactional; + + +@ContextConfiguration("/test-context.xml") +@RunWith(SpringJUnit4ClassRunner.class) +@Transactional +@TransactionConfiguration(defaultRollback=true) +public class PersonDaoTest { + + @Autowired + private PersonDao personDao; + + @Test + public void testCreation() { + personDao.save(new Person("Erich", "Gamma")); + Person person = new Person("Kent", "Beck"); + personDao.save(person); + personDao.save(new Person("Ralph", "Johnson")); + + Person personFromDb = personDao.findPersonsByFirstnameQueryDSL("Kent").get(0); + Assert.assertEquals(person.getId(), personFromDb.getId()); + } +} \ No newline at end of file diff --git a/querydsl/src/test/resources/db.properties b/querydsl/src/test/resources/db.properties new file mode 100644 index 0000000000..efee3669ce --- /dev/null +++ b/querydsl/src/test/resources/db.properties @@ -0,0 +1,6 @@ +#In memory db +db.username=sa +db.password= +db.driver=org.hsqldb.jdbcDriver +db.url=jdbc:hsqldb:mem:app-db +db.dialect=org.hibernate.dialect.HSQLDialect \ No newline at end of file diff --git a/querydsl/src/test/resources/test-context.xml b/querydsl/src/test/resources/test-context.xml new file mode 100644 index 0000000000..13d823a857 --- /dev/null +++ b/querydsl/src/test/resources/test-context.xml @@ -0,0 +1,20 @@ + + + + + + + + + \ No newline at end of file diff --git a/querydsl/src/test/resources/test-db.xml b/querydsl/src/test/resources/test-db.xml new file mode 100644 index 0000000000..7f85630b6b --- /dev/null +++ b/querydsl/src/test/resources/test-db.xml @@ -0,0 +1,49 @@ + + + + + + + classpath:db.properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From e14be27fcc4e43cc597ddb79bce2ce7aab8e0288 Mon Sep 17 00:00:00 2001 From: ypatil Date: Thu, 4 Feb 2016 14:10:46 +0530 Subject: [PATCH 002/121] Spring with Apache Camel for file processing --- spring-apache-camel/data/file1.txt | 1 + .../data/input/.camel/file1.txt | 1 + .../data/outputLowerCase/file1.txt | 1 + .../data/outputUppperCase/file1.txt | 1 + spring-apache-camel/pom.xml | 43 +++++++++++++++++++ .../main/java/org/apache/camel/main/App.java | 12 ++++++ .../apache/camel/processor/FileProcessor.java | 19 ++++++++ .../src/main/resources/camel-context.xml | 41 ++++++++++++++++++ 8 files changed, 119 insertions(+) create mode 100644 spring-apache-camel/data/file1.txt create mode 100644 spring-apache-camel/data/input/.camel/file1.txt create mode 100644 spring-apache-camel/data/outputLowerCase/file1.txt create mode 100644 spring-apache-camel/data/outputUppperCase/file1.txt create mode 100644 spring-apache-camel/pom.xml create mode 100644 spring-apache-camel/src/main/java/org/apache/camel/main/App.java create mode 100644 spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java create mode 100644 spring-apache-camel/src/main/resources/camel-context.xml diff --git a/spring-apache-camel/data/file1.txt b/spring-apache-camel/data/file1.txt new file mode 100644 index 0000000000..c8436b654b --- /dev/null +++ b/spring-apache-camel/data/file1.txt @@ -0,0 +1 @@ +THIS IS UPPERCASE CONTENT. this is lowecase content. \ No newline at end of file diff --git a/spring-apache-camel/data/input/.camel/file1.txt b/spring-apache-camel/data/input/.camel/file1.txt new file mode 100644 index 0000000000..c8436b654b --- /dev/null +++ b/spring-apache-camel/data/input/.camel/file1.txt @@ -0,0 +1 @@ +THIS IS UPPERCASE CONTENT. this is lowecase content. \ No newline at end of file diff --git a/spring-apache-camel/data/outputLowerCase/file1.txt b/spring-apache-camel/data/outputLowerCase/file1.txt new file mode 100644 index 0000000000..06a9866342 --- /dev/null +++ b/spring-apache-camel/data/outputLowerCase/file1.txt @@ -0,0 +1 @@ +this is uppercase content. this is lowecase content. \ No newline at end of file diff --git a/spring-apache-camel/data/outputUppperCase/file1.txt b/spring-apache-camel/data/outputUppperCase/file1.txt new file mode 100644 index 0000000000..ce07e477bc --- /dev/null +++ b/spring-apache-camel/data/outputUppperCase/file1.txt @@ -0,0 +1 @@ +THIS IS UPPERCASE CONTENT. THIS IS LOWECASE CONTENT. \ No newline at end of file diff --git a/spring-apache-camel/pom.xml b/spring-apache-camel/pom.xml new file mode 100644 index 0000000000..5b143fedb4 --- /dev/null +++ b/spring-apache-camel/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + org.apache.camel + spring-apache-camel + jar + 1.0-SNAPSHOT + spring-apache-camel + http://maven.apache.org + + + 2.16.1 + 4.2.4.RELEASE + + + + + + org.apache.camel + camel-core + ${env.camel.version} + + + + org.apache.camel + camel-spring + ${env.camel.version} + + + + org.apache.camel + camel-stream + ${env.camel.version} + + + + org.springframework + spring-context + ${env.spring.version} + + + + diff --git a/spring-apache-camel/src/main/java/org/apache/camel/main/App.java b/spring-apache-camel/src/main/java/org/apache/camel/main/App.java new file mode 100644 index 0000000000..4d0793903e --- /dev/null +++ b/spring-apache-camel/src/main/java/org/apache/camel/main/App.java @@ -0,0 +1,12 @@ +package org.apache.camel.main; + +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class App { + public static void main(final String[] args) throws Exception { + //Load application context + ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context.xml"); + Thread.sleep(5000); + applicationContext.close(); + } +} \ No newline at end of file diff --git a/spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java b/spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java new file mode 100644 index 0000000000..961f877806 --- /dev/null +++ b/spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java @@ -0,0 +1,19 @@ +package org.apache.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +public class FileProcessor implements Processor { + + public void process(Exchange exchange) throws Exception { + //Read file content + String originalFileContent = (String)exchange.getIn().getBody(String.class); + + //Convert file content to upper case. + String upperCaseFileContent = originalFileContent.toUpperCase(); + + //Update file content. + exchange.getIn().setBody(upperCaseFileContent); + } + +} diff --git a/spring-apache-camel/src/main/resources/camel-context.xml b/spring-apache-camel/src/main/resources/camel-context.xml new file mode 100644 index 0000000000..d304ceb857 --- /dev/null +++ b/spring-apache-camel/src/main/resources/camel-context.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + ${body.toLowerCase()} + + + + + + + + .......... File content conversion completed .......... + + + + + + + + + \ No newline at end of file From c385d23cd53543d6bb0a0f6f7ec8c97a8679c31d Mon Sep 17 00:00:00 2001 From: ypatil Date: Thu, 4 Feb 2016 14:13:39 +0530 Subject: [PATCH 003/121] Readme file added --- spring-apache-camel/README.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 spring-apache-camel/README.md diff --git a/spring-apache-camel/README.md b/spring-apache-camel/README.md new file mode 100644 index 0000000000..28b95bdf89 --- /dev/null +++ b/spring-apache-camel/README.md @@ -0,0 +1,28 @@ + +

Configure and Use Apache Camel with Spring

+ +This article will demonstrate how to configure and use Apache Camel with Spring Framework. + +

Relevant Article

+ + + +

Framework Versions:

+ +
    +
  • Spring 4.2.4
  • +
  • Apache Camel 2.16.1
  • +
+ +

Build and Run Application

+ +To build this application execute following maven command in ApacheCamelFileProcessor directory. + +mvn clean install + +To run this application you can either run our main class org.apache.camel.main.App from your IDE or you can execute following maven command: + +mvn exec:java -Dexec.mainClass="org.apache.camel.main.App" \ No newline at end of file From 596486aea00f488010c79ff1931c418c1b5ffa12 Mon Sep 17 00:00:00 2001 From: Thai Nguyen Date: Fri, 5 Feb 2016 14:11:39 +0700 Subject: [PATCH 004/121] initial commit for json-path --- json-path/.classpath | 32 +++++++ json-path/.gitignore | 13 +++ json-path/.project | 23 +++++ json-path/pom.xml | 61 +++++++++++++ json-path/src/main/resources/intro_api.json | 57 +++++++++++++ json-path/src/main/resources/intro_user.json | 46 ++++++++++ .../introduction/ChangingPasswordTest.java | 85 +++++++++++++++++++ .../jsonpath/introduction/LoggingInTest.java | 50 +++++++++++ .../jsonpath/introduction/OperationTest.java | 71 ++++++++++++++++ .../introduction/RegisteringAccountTest.java | 46 ++++++++++ 10 files changed, 484 insertions(+) create mode 100644 json-path/.classpath create mode 100644 json-path/.gitignore create mode 100644 json-path/.project create mode 100644 json-path/pom.xml create mode 100644 json-path/src/main/resources/intro_api.json create mode 100644 json-path/src/main/resources/intro_user.json create mode 100644 json-path/src/test/java/org/baeldung/jsonpath/introduction/ChangingPasswordTest.java create mode 100644 json-path/src/test/java/org/baeldung/jsonpath/introduction/LoggingInTest.java create mode 100644 json-path/src/test/java/org/baeldung/jsonpath/introduction/OperationTest.java create mode 100644 json-path/src/test/java/org/baeldung/jsonpath/introduction/RegisteringAccountTest.java diff --git a/json-path/.classpath b/json-path/.classpath new file mode 100644 index 0000000000..2244ed1e21 --- /dev/null +++ b/json-path/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/json-path/.gitignore b/json-path/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/json-path/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/json-path/.project b/json-path/.project new file mode 100644 index 0000000000..caa2c41711 --- /dev/null +++ b/json-path/.project @@ -0,0 +1,23 @@ + + + json-path + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/json-path/pom.xml b/json-path/pom.xml new file mode 100644 index 0000000000..b51f59c411 --- /dev/null +++ b/json-path/pom.xml @@ -0,0 +1,61 @@ + + 4.0.0 + org.baeldung + json-path + 0.0.1-SNAPSHOT + json-path + + + + + com.jayway.jsonpath + json-path + ${json-path.version} + + + + + joda-time + joda-time + ${joda-time.version} + + + + + junit + junit + ${junit.version} + test + + + + + org.slf4j + slf4j-api + ${slf4j.version} + runtime + + + ch.qos.logback + logback-classic + ${logback.version} + runtime + + + + + + 2.1.0 + + + 2.9.2 + + + 4.12 + + + 1.7.14 + 1.1.3 + + \ No newline at end of file diff --git a/json-path/src/main/resources/intro_api.json b/json-path/src/main/resources/intro_api.json new file mode 100644 index 0000000000..8a252f2971 --- /dev/null +++ b/json-path/src/main/resources/intro_api.json @@ -0,0 +1,57 @@ +{ + "tool": + { + "jsonpath": + { + "creator": + { + "name": "Jayway Inc.", + "location": + [ + "Malmo", + "Stockholm", + "Copenhagen", + "San Francisco", + "Karlskrona", + "Halmstad", + "Helsingborg" + ] + }, + + "current release": "2.1" + } + }, + + "book": + [ + { + "title": "Beginning JSON", + "author": "Ben Smith", + "price": 49.99 + }, + + { + "title": "JSON at Work", + "author": "Tom Marrs", + "price": 29.99 + }, + + { + "title": "Learn JSON in a DAY", + "author": "Acodemy", + "price": 8.99 + }, + + { + "title": "JSON: Questions and Answers", + "author": "George Duckett", + "price": 6.00 + } + ], + + "price range": + { + "cheap": 10.00, + "medium": 20.00 + } +} \ No newline at end of file diff --git a/json-path/src/main/resources/intro_user.json b/json-path/src/main/resources/intro_user.json new file mode 100644 index 0000000000..c35914c6c4 --- /dev/null +++ b/json-path/src/main/resources/intro_user.json @@ -0,0 +1,46 @@ +[ + { + "username": "oracle", + "password": + { + "current": + { + "value": "Java_SE_8", + "created": 1397754000000 + }, + + "old": + [ + { + "value": "Java_SE_7", + "created": 1312650000000 + } + ] + } + }, + + { + "username": "sun", + "password": + { + "current": + { + "value": "Java_SE_6", + "created": 1168448400000 + }, + + "old": + [ + { + "value": "J2SE_5.0", + "created": 1099069200000 + }, + + { + "value": "J2SE_1.4", + "created": 1025542800000 + } + ] + } + } +] \ No newline at end of file diff --git a/json-path/src/test/java/org/baeldung/jsonpath/introduction/ChangingPasswordTest.java b/json-path/src/test/java/org/baeldung/jsonpath/introduction/ChangingPasswordTest.java new file mode 100644 index 0000000000..24f8500d3d --- /dev/null +++ b/json-path/src/test/java/org/baeldung/jsonpath/introduction/ChangingPasswordTest.java @@ -0,0 +1,85 @@ +package org.baeldung.jsonpath.introduction; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; +import java.util.Scanner; + +import org.joda.time.DateTime; +import org.joda.time.Years; + +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.JsonPath; +import com.jayway.jsonpath.Option; + +public class ChangingPasswordTest { + + enum Result { + SUCCESS, FAILURE + } + + InputStream jsonValueInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_user.json"); + String jsonDataSourceString = new Scanner(jsonValueInputStream, "UTF-8").useDelimiter("\\Z").next(); + + @Test + public void givenUseCase_whenChangingPasswordOfNonExistentUser_thenFail() { + String failedRequestBody = "{\"username\":\"jayway\", \"new_password\":\"JsonPath\"}"; + Result result = changingPasswordHelper(failedRequestBody); + + assertEquals(Result.FAILURE, result); + } + + @Test + public void givenUseCase_whenChangingToUnusedPassword_thenSucceed() { + String successfulRequestBody = "{\"username\":\"oracle\", \"new_password\":\"Java_SE_9\"}"; + Result result = changingPasswordHelper(successfulRequestBody); + + assertEquals(Result.SUCCESS, result); + } + + @Test + public void givenUseCase_whenChangingToRecentlyUsedPassword_thenFail() { + String failedRequestBody = "{\"username\":\"oracle\", \"new_password\":\"Java_SE_7\"}"; + Result result = changingPasswordHelper(failedRequestBody); + + assertEquals(Result.FAILURE, result); + } + + @Test + public void givenUseCase_whenChangingToLongTimeAgoPassword_thenSucceed() { + String successfulRequestBody = "{\"username\":\"sun\", \"new_password\":\"J2SE_5.0\"}"; + Result result = changingPasswordHelper(successfulRequestBody); + + assertEquals(Result.SUCCESS, result); + } + + private Result changingPasswordHelper(String requestBody) { + DocumentContext requestContext = JsonPath.parse(requestBody); + String extractedUsername = requestContext.read("$['username']"); + String extractedPassword = requestContext.read("$['new_password']"); + + DocumentContext jsonContext = JsonPath.parse(jsonDataSourceString); + List dataSourceUsername = jsonContext.read("$[?(@.username == '" + extractedUsername + "')]"); + if (dataSourceUsername.size() == 0) + return Result.FAILURE; + + Configuration pathConfiguration = Configuration.builder().options(Option.AS_PATH_LIST).build(); + List pathToCurrentUser = JsonPath.using(pathConfiguration).parse(jsonDataSourceString).read("$[?(@.username == '" + extractedUsername + "')]"); + List passwordCreatedTimeList = jsonContext.read(pathToCurrentUser.get(0) + "['password']['old'][?(@.value == '" + extractedPassword + "')]['created']"); + if (passwordCreatedTimeList.size() == 0) + return Result.SUCCESS; + + Long[] passwordCreatedTimeArray = (passwordCreatedTimeList.toArray(new Long[passwordCreatedTimeList.size()])); + Arrays.sort(passwordCreatedTimeArray); + DateTime oldDate = new DateTime(passwordCreatedTimeArray[passwordCreatedTimeArray.length - 1]); + if (Years.yearsBetween(oldDate, new DateTime()).getYears() <= 10) + return Result.FAILURE; + + return Result.SUCCESS; + } +} diff --git a/json-path/src/test/java/org/baeldung/jsonpath/introduction/LoggingInTest.java b/json-path/src/test/java/org/baeldung/jsonpath/introduction/LoggingInTest.java new file mode 100644 index 0000000000..1ab7dad88e --- /dev/null +++ b/json-path/src/test/java/org/baeldung/jsonpath/introduction/LoggingInTest.java @@ -0,0 +1,50 @@ +package org.baeldung.jsonpath.introduction; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import java.io.InputStream; +import java.util.List; +import java.util.Scanner; + +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.JsonPath; + +public class LoggingInTest { + + enum Result { + SUCCESS, FAILURE + } + + InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_user.json"); + String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); + + @Test + public void givenUseCase_whenLoggingInWithCorrectUserData_thenSucceed() { + String correctRequestBody = "{\"username\":\"sun\", \"password\":\"Java_SE_6\"}"; + Result result = loggingInHelper(correctRequestBody); + + assertEquals(Result.SUCCESS, result); + } + + @Test + public void givenUseCase_whenLoggingInWithIncorrectUserData_thenFail() { + String incorrectRequestBody = "{\"username\":\"oracle\", \"password\":\"Java_SE_9\"}"; + Result result = loggingInHelper(incorrectRequestBody); + + assertEquals(Result.FAILURE, result); + } + + private Result loggingInHelper(String requestBody) { + DocumentContext requestContext = JsonPath.parse(requestBody); + String extractedUsername = requestContext.read("$['username']"); + String extractedPassword = requestContext.read("$['password']"); + List list = JsonPath.parse(jsonDataSourceString).read("$[?(@.username == '" + extractedUsername + "' && @.password.current.value == '" + extractedPassword + "')]"); + + if (list.size() == 0) + return Result.FAILURE; + return Result.SUCCESS; + } + +} diff --git a/json-path/src/test/java/org/baeldung/jsonpath/introduction/OperationTest.java b/json-path/src/test/java/org/baeldung/jsonpath/introduction/OperationTest.java new file mode 100644 index 0000000000..9347a7f754 --- /dev/null +++ b/json-path/src/test/java/org/baeldung/jsonpath/introduction/OperationTest.java @@ -0,0 +1,71 @@ +package org.baeldung.jsonpath.introduction; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.not; + +import org.junit.Test; + +import java.io.InputStream; +import java.util.List; +import java.util.Map; +import java.util.Scanner; + +import com.jayway.jsonpath.Criteria; +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.Filter; +import com.jayway.jsonpath.JsonPath; +import com.jayway.jsonpath.Predicate; + +public class OperationTest { + InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json"); + String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); + + @Test + public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() { + String jsonpathCreatorNamePath = "$['tool']['jsonpath']['creator']['name']"; + String jsonpathCreatorLocationPath = "$['tool']['jsonpath']['creator']['location'][*]"; + + DocumentContext jsonContext = JsonPath.parse(jsonDataSourceString); + String jsonpathCreatorName = jsonContext.read(jsonpathCreatorNamePath); + List jsonpathCreatorLocation = jsonContext.read(jsonpathCreatorLocationPath); + + assertEquals("Jayway Inc.", jsonpathCreatorName); + assertThat(jsonpathCreatorLocation.toString(), containsString("Malmo")); + assertThat(jsonpathCreatorLocation.toString(), containsString("San Francisco")); + assertThat(jsonpathCreatorLocation.toString(), containsString("Helsingborg")); + } + + @Test + public void givenJsonPathWithFilterPredicate_whenReading_thenCorrect() { + Filter expensiveFilter = Filter.filter(Criteria.where("price").gt(20.00)); + List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensiveFilter); + predicateUsageAssertionHelper(expensive); + } + + @Test + public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() { + Predicate expensivePredicate = new Predicate() { + public boolean apply(PredicateContext context) { + String value = context.item(Map.class).get("price").toString(); + return Float.valueOf(value) > 20.00; + } + }; + List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate); + predicateUsageAssertionHelper(expensive); + } + + @Test + public void givenJsonPathWithInlinePredicate_whenReading_thenCorrect() { + List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?(@['price'] > $['price range']['medium'])]"); + predicateUsageAssertionHelper(expensive); + } + + private void predicateUsageAssertionHelper(List predicate) { + assertThat(predicate.toString(), containsString("Beginning JSON")); + assertThat(predicate.toString(), containsString("JSON at Work")); + assertThat(predicate.toString(), not(containsString("Learn JSON in a DAY"))); + assertThat(predicate.toString(), not(containsString("JSON: Questions and Answers"))); + } +} diff --git a/json-path/src/test/java/org/baeldung/jsonpath/introduction/RegisteringAccountTest.java b/json-path/src/test/java/org/baeldung/jsonpath/introduction/RegisteringAccountTest.java new file mode 100644 index 0000000000..6e5cba63b0 --- /dev/null +++ b/json-path/src/test/java/org/baeldung/jsonpath/introduction/RegisteringAccountTest.java @@ -0,0 +1,46 @@ +package org.baeldung.jsonpath.introduction; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import java.io.InputStream; +import java.util.List; +import java.util.Scanner; + +import com.jayway.jsonpath.JsonPath; + +public class RegisteringAccountTest { + + enum Result { + SUCCESS, FAILURE + } + + InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_user.json"); + String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); + + @Test + public void givenUseCase_whenRegisteringUnusedAccount_thenSucceed() { + String unusedRequestBody = "{\"username\":\"jayway\", \"password\":\"JsonPath\"}"; + Result result = registeringNewAccountHelper(unusedRequestBody); + + assertEquals(Result.SUCCESS, result); + } + + @Test + public void givenUseCase_whenRegisteringUsedAccount_thenFail() { + String usedRequestBody = "{\"username\":\"oracle\", \"password\":\"Java_SE_9\"}"; + Result result = registeringNewAccountHelper(usedRequestBody); + + assertEquals(Result.FAILURE, result); + } + + private Result registeringNewAccountHelper(String requestBody) { + List userDataSource = JsonPath.parse(jsonDataSourceString).read("$[*]['username']"); + String extractedUsername = JsonPath.parse(requestBody).read("$['username']"); + + if (userDataSource.toString().contains(extractedUsername)) + return Result.FAILURE; + return Result.SUCCESS; + } +} From 0fdbd513bcfdc936228c4485caf0b7e5ff15d294 Mon Sep 17 00:00:00 2001 From: ivan Date: Fri, 12 Feb 2016 00:09:58 +0100 Subject: [PATCH 005/121] Add form tag example --- .../spring/controller/PersonController.java | 86 +++++++++++++ .../java/org/baeldung/spring/form/Person.java | 120 ++++++++++++++++++ .../main/webapp/WEB-INF/view/personForm.jsp | 88 +++++++++++++ .../main/webapp/WEB-INF/view/personResume.jsp | 61 +++++++++ 4 files changed, 355 insertions(+) create mode 100644 spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java create mode 100644 spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java create mode 100644 spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp create mode 100644 spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java new file mode 100644 index 0000000000..688e52e51b --- /dev/null +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java @@ -0,0 +1,86 @@ +package org.baeldung.spring.controller; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.validation.Valid; + +import org.baeldung.spring.form.Person; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class PersonController { + + @RequestMapping(value = "/person", method = RequestMethod.GET) + public ModelAndView initForm(final Model model) { + + final List favouriteLanguage = new ArrayList(); + favouriteLanguage.add("Java"); + favouriteLanguage.add("C++"); + favouriteLanguage.add("Perl"); + model.addAttribute("favouriteLanguage", favouriteLanguage); + + final List job = new ArrayList(); + job.add("Full time"); + job.add("Part time"); + model.addAttribute("job", job); + + final Map country = new LinkedHashMap(); + country.put("US", "United Stated"); + country.put("IT", "Italy"); + country.put("UK", "United Kingdom"); + country.put("FR", "Grance"); + model.addAttribute("country", country); + + final List fruit = new ArrayList(); + fruit.add("Banana"); + fruit.add("Mango"); + fruit.add("Apple"); + model.addAttribute("fruit", fruit); + + final List books = new ArrayList(); + books.add("The Great Gatsby"); + books.add("Nineteen Eighty-Four"); + books.add("The Lord of the Rings"); + model.addAttribute("books", books); + + return new ModelAndView("personForm", "person", new Person()); + } + + @RequestMapping(value = "/addPerson", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, + final ModelMap model) { + + if (result.hasErrors()) { + return "error"; + } + + model.addAttribute("person", person); + + return "personResume"; + } + // + // protected Map> referenceData(final + // HttpServletRequest request) throws Exception { + // + // final Map> referenceData = new HashMap<>(); + // + // final List favouriteLanguageList = new ArrayList(); + // favouriteLanguageList.add("Java"); + // favouriteLanguageList.add("C++"); + // favouriteLanguageList.add("Perl"); + // referenceData.put("favouriteLanguageList", favouriteLanguageList); + // + // return referenceData; + // + // } +} diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java new file mode 100644 index 0000000000..1b77ab5771 --- /dev/null +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java @@ -0,0 +1,120 @@ +package org.baeldung.spring.form; + +import java.util.List; + +public class Person { + + private long id; + private String name; + private String password; + private String sex; + private String country; + private String book; + private String job; + boolean receiveNewsletter; + private String[] hobbies; + private List favouriteLanguage; + private List fruit; + private String notes; + + public Person() { + super(); + } + + 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; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } + + public String getSex() { + return sex; + } + + public void setSex(final String sex) { + this.sex = sex; + } + + public String getCountry() { + return country; + } + + public void setCountry(final String country) { + this.country = country; + } + + public String getJob() { + return job; + } + + public void setJob(final String job) { + this.job = job; + } + + public boolean isReceiveNewsletter() { + return receiveNewsletter; + } + + public void setReceiveNewsletter(final boolean receiveNewsletter) { + this.receiveNewsletter = receiveNewsletter; + } + + public String[] getHobbies() { + return hobbies; + } + + public void setHobbies(final String[] hobbies) { + this.hobbies = hobbies; + } + + public List getFavouriteLanguage() { + return favouriteLanguage; + } + + public void setFavouriteLanguage(final List favouriteLanguage) { + this.favouriteLanguage = favouriteLanguage; + } + + public String getNotes() { + return notes; + } + + public void setNotes(final String notes) { + this.notes = notes; + } + + public List getFruit() { + return fruit; + } + + public void setFruit(final List fruit) { + this.fruit = fruit; + } + + public String getBook() { + return book; + } + + public void setBook(final String book) { + this.book = book; + } + +} diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp new file mode 100644 index 0000000000..f6cf0bf460 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp @@ -0,0 +1,88 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +Form Example - Register a Person + + +

Welcome, Enter The Person Details

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name
Password
Sex + Male:
+ Female: +
Job + +
Country + +
Book + + + + +
Fruit + +
Receive newsletter
Hobbies + Bird watching: + Astronomy: + Snowboarding: +
Favourite languages + +
Notes
+
+ + + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp new file mode 100644 index 0000000000..81f7fd3411 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp @@ -0,0 +1,61 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + + + +Spring MVC Form Handling + + + +

Submitted Person Information

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Id :${person.id}
Name :${person.name}
Password :${person.password}
Sex :${person.sex}
Job :${person.job}
Country :${person.country}
Fruit :[]
Book :${person.book}
Receive Newsletter :${person.receiveNewsletter}
Hobbies :[]
Favourite Languages :[]
Notes :${person.notes}
+ + \ No newline at end of file From c1f4c574a86d33f216564990870fb6b14ebdcc82 Mon Sep 17 00:00:00 2001 From: Ivan Date: Fri, 12 Feb 2016 14:38:01 +0100 Subject: [PATCH 006/121] Add form tag example --- .../spring/controller/PersonController.java | 53 +++-- .../java/org/baeldung/spring/form/Person.java | 16 ++ .../src/main/resources/messages.properties | 2 + .../src/main/resources/webMvcConfig.xml | 13 ++ .../main/webapp/WEB-INF/view/personForm.jsp | 187 ++++++++++-------- .../main/webapp/WEB-INF/view/personResume.jsp | 4 + .../src/main/webapp/WEB-INF/web.xml | 3 + 7 files changed, 164 insertions(+), 114 deletions(-) create mode 100644 spring-mvc-xml/src/main/resources/messages.properties diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java index 688e52e51b..d5b68c7516 100644 --- a/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java @@ -21,7 +21,28 @@ import org.springframework.web.servlet.ModelAndView; public class PersonController { @RequestMapping(value = "/person", method = RequestMethod.GET) - public ModelAndView initForm(final Model model) { + public ModelAndView showForm(final Model model) { + + initData(model); + return new ModelAndView("personForm", "person", new Person()); + } + + @RequestMapping(value = "/addPerson", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, + final ModelMap modelMap, final Model model) { + + if (result.hasErrors()) { + + initData(model); + return "personForm"; + } + + modelMap.addAttribute("person", person); + + return "personResume"; + } + + private void initData(final Model model) { final List favouriteLanguage = new ArrayList(); favouriteLanguage.add("Java"); @@ -52,35 +73,5 @@ public class PersonController { books.add("Nineteen Eighty-Four"); books.add("The Lord of the Rings"); model.addAttribute("books", books); - - return new ModelAndView("personForm", "person", new Person()); } - - @RequestMapping(value = "/addPerson", method = RequestMethod.POST) - public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, - final ModelMap model) { - - if (result.hasErrors()) { - return "error"; - } - - model.addAttribute("person", person); - - return "personResume"; - } - // - // protected Map> referenceData(final - // HttpServletRequest request) throws Exception { - // - // final Map> referenceData = new HashMap<>(); - // - // final List favouriteLanguageList = new ArrayList(); - // favouriteLanguageList.add("Java"); - // favouriteLanguageList.add("C++"); - // favouriteLanguageList.add("Perl"); - // referenceData.put("favouriteLanguageList", favouriteLanguageList); - // - // return referenceData; - // - // } } diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java index 1b77ab5771..3db8cc4377 100644 --- a/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java @@ -2,10 +2,17 @@ package org.baeldung.spring.form; import java.util.List; +import org.hibernate.validator.constraints.NotEmpty; +import org.springframework.web.multipart.MultipartFile; + public class Person { private long id; + + @NotEmpty private String name; + + @NotEmpty private String password; private String sex; private String country; @@ -16,6 +23,7 @@ public class Person { private List favouriteLanguage; private List fruit; private String notes; + private MultipartFile file; public Person() { super(); @@ -117,4 +125,12 @@ public class Person { this.book = book; } + public MultipartFile getFile() { + return file; + } + + public void setFile(final MultipartFile file) { + this.file = file; + } + } diff --git a/spring-mvc-xml/src/main/resources/messages.properties b/spring-mvc-xml/src/main/resources/messages.properties new file mode 100644 index 0000000000..2a187731ae --- /dev/null +++ b/spring-mvc-xml/src/main/resources/messages.properties @@ -0,0 +1,2 @@ +NotEmpty.person.name = Name is required! +NotEmpty.person.password = Password is required! \ No newline at end of file diff --git a/spring-mvc-xml/src/main/resources/webMvcConfig.xml b/spring-mvc-xml/src/main/resources/webMvcConfig.xml index a7aa252c08..f3297fdbf6 100644 --- a/spring-mvc-xml/src/main/resources/webMvcConfig.xml +++ b/spring-mvc-xml/src/main/resources/webMvcConfig.xml @@ -11,7 +11,9 @@ > + + @@ -19,4 +21,15 @@ + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp index f6cf0bf460..9ef02efbae 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp @@ -1,88 +1,109 @@ <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> - - -Form Example - Register a Person - - -

Welcome, Enter The Person Details

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Name
Password
Sex - Male:
- Female: -
Job - -
Country - -
Book - - - - -
Fruit - -
Receive newsletter
Hobbies - Bird watching: - Astronomy: - Snowboarding: -
Favourite languages - -
Notes
-
- - + + + Form Example - Register a Person + + + + + + +

Welcome, Enter The Person Details

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name
Password
Sex + Male:
+ Female: +
Job + +
Country + +
Book + + + + +
Fruit + +
Receive newsletter
Hobbies + Bird watching: + Astronomy: + Snowboarding: +
Favourite languages + +
Notes
Select a file to upload
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp index 81f7fd3411..857738c545 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp @@ -56,6 +56,10 @@ Notes : ${person.notes} + + File : + ${person.file.originalFilename} + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml index 5275efdf24..4e38b2fae6 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml @@ -28,6 +28,9 @@ mvc org.springframework.web.servlet.DispatcherServlet 1 + + C:/Users/ivan/Desktop/tmp + mvc From aedffc1d139ce5c54fec86d1e0d411ee09a8c590 Mon Sep 17 00:00:00 2001 From: ypatil Date: Mon, 15 Feb 2016 15:29:13 +0530 Subject: [PATCH 007/121] data folder moved under test/data. Test cases added. Code & POM updated. --- spring-apache-camel/data/file1.txt | 1 - .../data/input/.camel/file1.txt | 1 - .../data/outputLowerCase/file1.txt | 1 - .../data/outputUppperCase/file1.txt | 1 - spring-apache-camel/pom.xml | 26 +++- .../main/java/org/apache/camel/main/App.java | 4 +- .../apache/camel/processor/FileProcessor.java | 7 +- .../src/main/resources/camel-context.xml | 35 +++--- .../src/test/data/sampleInputFile/file.txt | 1 + .../java/org/apache/camel/main/AppTest.java | 117 ++++++++++++++++++ 10 files changed, 163 insertions(+), 31 deletions(-) delete mode 100644 spring-apache-camel/data/file1.txt delete mode 100644 spring-apache-camel/data/input/.camel/file1.txt delete mode 100644 spring-apache-camel/data/outputLowerCase/file1.txt delete mode 100644 spring-apache-camel/data/outputUppperCase/file1.txt create mode 100644 spring-apache-camel/src/test/data/sampleInputFile/file.txt create mode 100644 spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java diff --git a/spring-apache-camel/data/file1.txt b/spring-apache-camel/data/file1.txt deleted file mode 100644 index c8436b654b..0000000000 --- a/spring-apache-camel/data/file1.txt +++ /dev/null @@ -1 +0,0 @@ -THIS IS UPPERCASE CONTENT. this is lowecase content. \ No newline at end of file diff --git a/spring-apache-camel/data/input/.camel/file1.txt b/spring-apache-camel/data/input/.camel/file1.txt deleted file mode 100644 index c8436b654b..0000000000 --- a/spring-apache-camel/data/input/.camel/file1.txt +++ /dev/null @@ -1 +0,0 @@ -THIS IS UPPERCASE CONTENT. this is lowecase content. \ No newline at end of file diff --git a/spring-apache-camel/data/outputLowerCase/file1.txt b/spring-apache-camel/data/outputLowerCase/file1.txt deleted file mode 100644 index 06a9866342..0000000000 --- a/spring-apache-camel/data/outputLowerCase/file1.txt +++ /dev/null @@ -1 +0,0 @@ -this is uppercase content. this is lowecase content. \ No newline at end of file diff --git a/spring-apache-camel/data/outputUppperCase/file1.txt b/spring-apache-camel/data/outputUppperCase/file1.txt deleted file mode 100644 index ce07e477bc..0000000000 --- a/spring-apache-camel/data/outputUppperCase/file1.txt +++ /dev/null @@ -1 +0,0 @@ -THIS IS UPPERCASE CONTENT. THIS IS LOWECASE CONTENT. \ No newline at end of file diff --git a/spring-apache-camel/pom.xml b/spring-apache-camel/pom.xml index 5b143fedb4..fbea9b779d 100644 --- a/spring-apache-camel/pom.xml +++ b/spring-apache-camel/pom.xml @@ -11,10 +11,19 @@ 2.16.1 4.2.4.RELEASE + 1.7 + 4.1 - + + + junit + junit + ${junit.version} + test + + org.apache.camel camel-core @@ -40,4 +49,19 @@ + + + + + maven-compiler-plugin + + true + true + ${java.version} + ${java.version} + ${java.version} + + + + diff --git a/spring-apache-camel/src/main/java/org/apache/camel/main/App.java b/spring-apache-camel/src/main/java/org/apache/camel/main/App.java index 4d0793903e..8674caefca 100644 --- a/spring-apache-camel/src/main/java/org/apache/camel/main/App.java +++ b/spring-apache-camel/src/main/java/org/apache/camel/main/App.java @@ -4,9 +4,9 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(final String[] args) throws Exception { - //Load application context ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context.xml"); - Thread.sleep(5000); + // Keep main thread alive for some time to let application finish processing the input files. + Thread.sleep(5000); applicationContext.close(); } } \ No newline at end of file diff --git a/spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java b/spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java index 961f877806..a98c77feb8 100644 --- a/spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java +++ b/spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java @@ -6,13 +6,8 @@ import org.apache.camel.Processor; public class FileProcessor implements Processor { public void process(Exchange exchange) throws Exception { - //Read file content - String originalFileContent = (String)exchange.getIn().getBody(String.class); - - //Convert file content to upper case. + String originalFileContent = exchange.getIn().getBody(String.class); String upperCaseFileContent = originalFileContent.toUpperCase(); - - //Update file content. exchange.getIn().setBody(upperCaseFileContent); } diff --git a/spring-apache-camel/src/main/resources/camel-context.xml b/spring-apache-camel/src/main/resources/camel-context.xml index d304ceb857..75e2a61711 100644 --- a/spring-apache-camel/src/main/resources/camel-context.xml +++ b/spring-apache-camel/src/main/resources/camel-context.xml @@ -1,40 +1,39 @@ + http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - - - + + + - - + + - + - - + + ${body.toLowerCase()} - + - - + + - .......... File content conversion completed .......... + .......... File content conversion completed .......... + - + - + diff --git a/spring-apache-camel/src/test/data/sampleInputFile/file.txt b/spring-apache-camel/src/test/data/sampleInputFile/file.txt new file mode 100644 index 0000000000..c1df3791c9 --- /dev/null +++ b/spring-apache-camel/src/test/data/sampleInputFile/file.txt @@ -0,0 +1 @@ +THIS IS UPPERCASE CONTENT. this is lowercase content. \ No newline at end of file diff --git a/spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java b/spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java new file mode 100644 index 0000000000..75a161d8cc --- /dev/null +++ b/spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java @@ -0,0 +1,117 @@ +package org.apache.camel.main; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Paths; + +import junit.framework.TestCase; + +import org.apache.camel.util.FileUtil; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class AppTest extends TestCase { + + private static final String FILE_NAME = "file.txt"; + private static final String SAMPLE_INPUT_DIR = "src/test/data/sampleInputFile/"; + private static final String TEST_INPUT_DIR = "src/test/data/input/"; + private static final String UPPERCARE_OUTPUT_DIR = "src/test/data/outputUpperCase/"; + private static final String LOWERCASE_OUTPUT_DIR = "src/test/data/outputLowerCase/"; + + @Before + public void setUp() throws Exception { + // Prepare input file for test + copySampleFileToInputDirectory(); + } + + @After + public void tearDown() throws Exception { + System.out.println("Deleting the test input and output files..."); + deleteFile(TEST_INPUT_DIR); + deleteFile(LOWERCASE_OUTPUT_DIR); + deleteFile(UPPERCARE_OUTPUT_DIR); + } + + @Test + public final void testMain() throws Exception { + App.main(null); + + String inputFileContent = readFileContent(SAMPLE_INPUT_DIR+FILE_NAME); + String outputUpperCase = readFileContent(UPPERCARE_OUTPUT_DIR+FILE_NAME); + String outputLowerCase = readFileContent(LOWERCASE_OUTPUT_DIR+FILE_NAME); + + System.out.println("Input File content = ["+inputFileContent+"]"); + System.out.println("UpperCaseOutput file content = ["+outputUpperCase+"]"); + System.out.println("LowerCaseOtput file content = ["+outputLowerCase+"]"); + + assertEquals(inputFileContent.toUpperCase(), outputUpperCase); + assertEquals(inputFileContent.toLowerCase(), outputLowerCase); + } + + private String readFileContent(String path) throws IOException { + byte[] encoded = Files.readAllBytes(Paths.get(path)); + return new String(encoded); + } + + private void deleteFile(String path) { + try { + FileUtil.removeDir(new File(path)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Copy sample input file to input directory. + */ + private void copySampleFileToInputDirectory() { + File sourceFile = new File(SAMPLE_INPUT_DIR + FILE_NAME); + File destFile = new File(TEST_INPUT_DIR + FILE_NAME); + + if (!sourceFile.exists()) { + System.out.println("Sample input file not found at location = [" + SAMPLE_INPUT_DIR + FILE_NAME + "]. Please provide this file."); + } + + if (!destFile.exists()) { + try { + System.out.println("Creating input file = [" + TEST_INPUT_DIR + FILE_NAME + "]"); + + File destDir = new File(TEST_INPUT_DIR); + if(!destDir.exists()) { + destDir.mkdir(); + } + destFile.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + FileChannel source = null; + FileChannel destination = null; + + try { + source = new FileInputStream(sourceFile).getChannel(); + destination = new FileOutputStream(destFile).getChannel(); + if (destination != null && source != null) { + destination.transferFrom(source, 0, source.size()); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + source.close(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + destination.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } +} From 7fb50bfaed8280acf7c4dbdf486087dac7d2b7b0 Mon Sep 17 00:00:00 2001 From: Kevin Gilmore Date: Wed, 17 Feb 2016 11:38:29 -0600 Subject: [PATCH 008/121] Added files for RAML annotations article --- raml/annotations/api.raml | 126 ++++++++++++++++++ raml/annotations/examples/Bar.json | 6 + raml/annotations/examples/Bars.json | 19 +++ raml/annotations/examples/Error.json | 4 + raml/annotations/examples/Foo.json | 4 + raml/annotations/examples/Foos.json | 16 +++ .../extensions/en_US/additionalResources.raml | 13 ++ raml/annotations/libraries/dataTypes.raml | 19 +++ raml/annotations/libraries/resourceTypes.raml | 38 ++++++ .../libraries/securitySchemes.raml | 20 +++ raml/annotations/libraries/traits.raml | 32 +++++ .../overlays/es_ES/additionalResources.raml | 11 ++ .../overlays/es_ES/documentationItems.raml | 22 +++ 13 files changed, 330 insertions(+) create mode 100644 raml/annotations/api.raml create mode 100644 raml/annotations/examples/Bar.json create mode 100644 raml/annotations/examples/Bars.json create mode 100644 raml/annotations/examples/Error.json create mode 100644 raml/annotations/examples/Foo.json create mode 100644 raml/annotations/examples/Foos.json create mode 100644 raml/annotations/extensions/en_US/additionalResources.raml create mode 100644 raml/annotations/libraries/dataTypes.raml create mode 100644 raml/annotations/libraries/resourceTypes.raml create mode 100644 raml/annotations/libraries/securitySchemes.raml create mode 100644 raml/annotations/libraries/traits.raml create mode 100644 raml/annotations/overlays/es_ES/additionalResources.raml create mode 100644 raml/annotations/overlays/es_ES/documentationItems.raml diff --git a/raml/annotations/api.raml b/raml/annotations/api.raml new file mode 100644 index 0000000000..e0123536eb --- /dev/null +++ b/raml/annotations/api.raml @@ -0,0 +1,126 @@ +#%RAML 1.0 +title: API for REST Services used in the RAML tutorials on Baeldung.com +documentation: + - title: Overview + content: | + This document defines the interface for the REST services + used in the popular RAML Tutorial series at Baeldung.com. + - title: Disclaimer + content: | + All names used in this definition are purely fictional. + Any similarities between the names used in this tutorial and those of real persons, whether living or dead, are merely coincidental. + - title: Copyright + content: Copyright 2016 by Baeldung.com. All rights reserved. +uses: + mySecuritySchemes: !include libraries/securitySchemes.raml + myDataTypes: !include libraries/dataTypes.raml + myTraits: !include libraries/traits.raml + myResourceTypes: !include libraries/resourceTypes.raml +version: v1 +protocols: [ HTTPS ] +baseUri: http://rest-api.baeldung.com/api/{version} +mediaType: application/json +securedBy: [ mySecuritySchemes.basicAuth ] +annotationTypes: + testCase: + allowedTargets: [ Method ] + allowMultiple: true + usage: | + Use this annotation to declare a test case + within a testSuite declaration. + You may apply this annotation multiple times + within the target testSuite. + properties: + scenario: string + setupScript?: string[] + testScript: string[] + expectedOutput?: string + cleanupScript?: string[] +/foos: + type: myResourceTypes.collection + get: + queryParameters: + name?: string + ownerName?: string + responses: + 200: + body: + example: !include examples/Foos.json + (testCase): + scenario: No Foos + setupScript: deleteAllFoosIfAny + testScript: getAllFoos + expectedOutput: "" + (testCase): + scenario: One Foo + setupScript: [ deleteAllFoosIfAny, addInputFoos ] + testScript: getAllFoos + expectedOutput: '[ { "id": 999, "name": Joe } ]' + cleanupScript: deleteInputFoos + (testCase): + scenario: Multiple Foos + setupScript: [ deleteAllFoosIfAny, addInputFoos ] + testScript: getAllFoos + expectedOutput: '[ { "id": 998, "name": "Bob" }, { "id": 999, "name": "Joe", "ownerName": "Bob" } ]' + cleanupScript: deleteInputFoos + post: + responses: + 200: + body: + example: !include examples/Foo.json + /{fooId}: + type: myResourceTypes.item + get: + responses: + 200: + body: + example: !include examples/Foo.json + put: + responses: + 200: + body: + example: !include examples/Foo.json +/foos/name/{name}: + get: + description: Get all Foos with the name {name} + responses: + 200: + body: + type: myDataTypes.Foo + 404: + body: + type: myDataTypes.Error +/foos/bar/{barId}: + get: + description: Get the Foo for the Bar with barId = {barId} + responses: + 200: + body: + example: !include examples/Foo.json +/bars: + type: myResourceTypes.collection + get: + queryParameters: + name?: string + ownerName?: string + responses: + 200: + body: + example: !include examples/Bars.json + post: + responses: + 200: + body: + example: !include examples/Bar.json + /{barId}: + type: myResourceTypes.item + get: + responses: + 200: + body: + example: !include examples/Bar.json + put: + responses: + 200: + body: + example: !include examples/Bars.json diff --git a/raml/annotations/examples/Bar.json b/raml/annotations/examples/Bar.json new file mode 100644 index 0000000000..0ee1b34edb --- /dev/null +++ b/raml/annotations/examples/Bar.json @@ -0,0 +1,6 @@ +{ + "id" : 1, + "name" : "First Bar", + "city" : "Austin", + "fooId" : 2 +} \ No newline at end of file diff --git a/raml/annotations/examples/Bars.json b/raml/annotations/examples/Bars.json new file mode 100644 index 0000000000..89ea875432 --- /dev/null +++ b/raml/annotations/examples/Bars.json @@ -0,0 +1,19 @@ +[ + { + "id" : 1, + "name" : "First Bar", + "city" : "Austin", + "fooId" : 2 + }, + { + "id" : 2, + "name" : "Second Bar", + "city" : "Dallas", + "fooId" : 1 + }, + { + "id" : 3, + "name" : "Third Bar", + "fooId" : 2 + } +] \ No newline at end of file diff --git a/raml/annotations/examples/Error.json b/raml/annotations/examples/Error.json new file mode 100644 index 0000000000..dca56da7c2 --- /dev/null +++ b/raml/annotations/examples/Error.json @@ -0,0 +1,4 @@ +{ + "message" : "Not found", + "code" : 1001 +} \ No newline at end of file diff --git a/raml/annotations/examples/Foo.json b/raml/annotations/examples/Foo.json new file mode 100644 index 0000000000..1b1b8c891e --- /dev/null +++ b/raml/annotations/examples/Foo.json @@ -0,0 +1,4 @@ +{ + "id" : 1, + "name" : "First Foo" +} \ No newline at end of file diff --git a/raml/annotations/examples/Foos.json b/raml/annotations/examples/Foos.json new file mode 100644 index 0000000000..74f64689f0 --- /dev/null +++ b/raml/annotations/examples/Foos.json @@ -0,0 +1,16 @@ +[ + { + "id" : 1, + "name" : "First Foo", + "ownerName" : "Jack Robinson" + }, + { + "id" : 2, + "name" : "Second Foo" + }, + { + "id" : 3, + "name" : "Third Foo", + "ownerName" : "Chuck Norris" + } +] \ No newline at end of file diff --git a/raml/annotations/extensions/en_US/additionalResources.raml b/raml/annotations/extensions/en_US/additionalResources.raml new file mode 100644 index 0000000000..9ab0d0a243 --- /dev/null +++ b/raml/annotations/extensions/en_US/additionalResources.raml @@ -0,0 +1,13 @@ +#%RAML 1.0 Extension +# File located at: +# /extensions/en_US/additionalResources.raml +masterRef: ../../api.raml +usage: This extension defines additional resources for version 2 of the API. +version: v2 +/foos: + /bar/{barId}: + get: + description: | + Get the foo that is related to the bar having barId = {barId} + queryParameters: + barId?: integer diff --git a/raml/annotations/libraries/dataTypes.raml b/raml/annotations/libraries/dataTypes.raml new file mode 100644 index 0000000000..8a240e62dc --- /dev/null +++ b/raml/annotations/libraries/dataTypes.raml @@ -0,0 +1,19 @@ +#%RAML 1.0 Library +# This is the file /libraries/dataTypes.raml +usage: This library defines the data types for the API +types: + Foo: + properties: + id: integer + name: string + ownerName?: string + Bar: + properties: + id: integer + name: string + city?: string + fooId: integer + Error: + properties: + code: integer + message: string diff --git a/raml/annotations/libraries/resourceTypes.raml b/raml/annotations/libraries/resourceTypes.raml new file mode 100644 index 0000000000..fb054f1a36 --- /dev/null +++ b/raml/annotations/libraries/resourceTypes.raml @@ -0,0 +1,38 @@ +#%RAML 1.0 Library +# This is the file /libraries/resourceTypes.raml +usage: This library defines the resource types for the API +uses: + myTraits: !include traits.raml +resourceTypes: + collection: + usage: Use this resourceType to represent a collection of items + description: A collection of <> + get: + description: | + Get all <>, + optionally filtered + is: [ myTraits.hasResponseCollection ] + post: + description: | + Create a new <> + is: [ myTraits.hasRequestItem ] + item: + usage: Use this resourceType to represent any single item + description: A single <> + get: + description: | + Get a <> + by <>Id + is: [ myTraits.hasResponseItem, myTraits.hasNotFound ] + put: + description: | + Update a <> + by <>Id + is: [ myTraits.hasRequestItem, myTraits.hasResponseItem, myTraits.hasNotFound ] + delete: + description: | + Delete a <> + by <>Id + is: [ myTraits.hasNotFound ] + responses: + 204: diff --git a/raml/annotations/libraries/securitySchemes.raml b/raml/annotations/libraries/securitySchemes.raml new file mode 100644 index 0000000000..621c6ac975 --- /dev/null +++ b/raml/annotations/libraries/securitySchemes.raml @@ -0,0 +1,20 @@ +#%RAML 1.0 Library +# This is the file /libraries/securitySchemes.raml +securitySchemes: + - basicAuth: + description: Each request must contain the headers necessary for + basic authentication + type: Basic Authentication + describedBy: + headers: + Authorization: + description: | + Used to send the Base64 encoded "username:password" + credentials + type: string + responses: + 401: + description: | + Unauthorized. Either the provided username and password + combination is invalid, or the user is not allowed to + access the content provided by the requested URL. diff --git a/raml/annotations/libraries/traits.raml b/raml/annotations/libraries/traits.raml new file mode 100644 index 0000000000..610747e79f --- /dev/null +++ b/raml/annotations/libraries/traits.raml @@ -0,0 +1,32 @@ +#%RAML 1.0 Library +# This is the file /libraries/traits.raml +usage: This library defines some basic traits +uses: + myDataTypes: !include dataTypes.raml +traits: + hasRequestItem: + usage: Use this trait for resources whose request body is a single item + body: + application/json: + type: <> + hasResponseItem: + usage: Use this trait for resources whose response body is a single item + responses: + 200: + body: + application/json: + type: <> + hasResponseCollection: + usage: Use this trait for resources whose response body is a collection of items + responses: + 200: + body: + application/json: + type: <>[] + hasNotFound: + usage: Use this trait for resources that could respond with a 404 status + responses: + 404: + body: + application/json: + type: myDataTypes.Error diff --git a/raml/annotations/overlays/es_ES/additionalResources.raml b/raml/annotations/overlays/es_ES/additionalResources.raml new file mode 100644 index 0000000000..0edd6a9231 --- /dev/null +++ b/raml/annotations/overlays/es_ES/additionalResources.raml @@ -0,0 +1,11 @@ +#%RAML 1.0 Overlay +# Archivo situado en: +# /overlays/es_ES/additionalResources.raml +masterRef: ../../api.raml +usage: | + Se trata de un español demasiado que describe los recursos adicionales + para la versión 1 del API. +/foos/bar/{barId}: + get: + description: | + Obtener el foo que se relaciona con el bar tomando barId = {barId} diff --git a/raml/annotations/overlays/es_ES/documentationItems.raml b/raml/annotations/overlays/es_ES/documentationItems.raml new file mode 100644 index 0000000000..49dd46fb59 --- /dev/null +++ b/raml/annotations/overlays/es_ES/documentationItems.raml @@ -0,0 +1,22 @@ +#%RAML 1.0 Overlay +# File located at (archivo situado en): +# /overlays/es_ES/documentationItems.raml +masterRef: ../../api.raml +usage: | + To provide user documentation and other descriptive text in Spanish + (Para proporcionar la documentación del usuario y otro texto descriptivo en español) +title: API para servicios REST utilizados en los tutoriales RAML en Baeldung.com +documentation: + - title: Descripción general + content: | + Este documento define la interfaz para los servicios REST + utilizados en la popular serie de RAML Tutorial en Baeldung.com + - title: Renuncia + content: | + Todos los nombres usados ​​en esta definición son pura ficción. + Cualquier similitud entre los nombres utilizados en este tutorial + y los de las personas reales, ya sea vivo o muerto, + no son más que coincidenta. + - title: Derechos de autor + content: | + Derechos de autor 2016 por Baeldung.com. Todos los derechos reservados. From 90d7b0236b928daa11787d543a33878946e60d2f Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Wed, 17 Feb 2016 23:37:16 +0100 Subject: [PATCH 009/121] Folder renamed e client code reverted --- {RestEasy Example => resteasy}/pom.xml | 0 .../baeldung/client/ServicesInterface.java | 0 .../main/java/com/baeldung/model/Movie.java | 0 .../com/baeldung/server/MovieCrudService.java | 0 .../com/baeldung/server/RestEasyServices.java | 0 .../main/webapp/WEB-INF/classes/logback.xml | 0 .../WEB-INF/jboss-deployment-structure.xml | 0 .../src/main/webapp/WEB-INF/jboss-web.xml | 0 .../src/main/webapp/WEB-INF/web.xml | 0 .../baeldung/server/RestEasyClientTest.java | 144 ++++++++++++++++++ .../com/baeldung/server/movies/batman.json | 4 + .../baeldung/server/movies/transformer.json | 4 + 12 files changed, 152 insertions(+) rename {RestEasy Example => resteasy}/pom.xml (100%) rename {RestEasy Example => resteasy}/src/main/java/com/baeldung/client/ServicesInterface.java (100%) rename {RestEasy Example => resteasy}/src/main/java/com/baeldung/model/Movie.java (100%) rename {RestEasy Example => resteasy}/src/main/java/com/baeldung/server/MovieCrudService.java (100%) rename {RestEasy Example => resteasy}/src/main/java/com/baeldung/server/RestEasyServices.java (100%) rename {RestEasy Example => resteasy}/src/main/webapp/WEB-INF/classes/logback.xml (100%) rename {RestEasy Example => resteasy}/src/main/webapp/WEB-INF/jboss-deployment-structure.xml (100%) rename {RestEasy Example => resteasy}/src/main/webapp/WEB-INF/jboss-web.xml (100%) rename {RestEasy Example => resteasy}/src/main/webapp/WEB-INF/web.xml (100%) create mode 100644 resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java create mode 100644 resteasy/src/test/resources/com/baeldung/server/movies/batman.json create mode 100644 resteasy/src/test/resources/com/baeldung/server/movies/transformer.json diff --git a/RestEasy Example/pom.xml b/resteasy/pom.xml similarity index 100% rename from RestEasy Example/pom.xml rename to resteasy/pom.xml diff --git a/RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java b/resteasy/src/main/java/com/baeldung/client/ServicesInterface.java similarity index 100% rename from RestEasy Example/src/main/java/com/baeldung/client/ServicesInterface.java rename to resteasy/src/main/java/com/baeldung/client/ServicesInterface.java diff --git a/RestEasy Example/src/main/java/com/baeldung/model/Movie.java b/resteasy/src/main/java/com/baeldung/model/Movie.java similarity index 100% rename from RestEasy Example/src/main/java/com/baeldung/model/Movie.java rename to resteasy/src/main/java/com/baeldung/model/Movie.java diff --git a/RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java b/resteasy/src/main/java/com/baeldung/server/MovieCrudService.java similarity index 100% rename from RestEasy Example/src/main/java/com/baeldung/server/MovieCrudService.java rename to resteasy/src/main/java/com/baeldung/server/MovieCrudService.java diff --git a/RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java b/resteasy/src/main/java/com/baeldung/server/RestEasyServices.java similarity index 100% rename from RestEasy Example/src/main/java/com/baeldung/server/RestEasyServices.java rename to resteasy/src/main/java/com/baeldung/server/RestEasyServices.java diff --git a/RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml b/resteasy/src/main/webapp/WEB-INF/classes/logback.xml similarity index 100% rename from RestEasy Example/src/main/webapp/WEB-INF/classes/logback.xml rename to resteasy/src/main/webapp/WEB-INF/classes/logback.xml diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/resteasy/src/main/webapp/WEB-INF/jboss-deployment-structure.xml similarity index 100% rename from RestEasy Example/src/main/webapp/WEB-INF/jboss-deployment-structure.xml rename to resteasy/src/main/webapp/WEB-INF/jboss-deployment-structure.xml diff --git a/RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml b/resteasy/src/main/webapp/WEB-INF/jboss-web.xml similarity index 100% rename from RestEasy Example/src/main/webapp/WEB-INF/jboss-web.xml rename to resteasy/src/main/webapp/WEB-INF/jboss-web.xml diff --git a/RestEasy Example/src/main/webapp/WEB-INF/web.xml b/resteasy/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from RestEasy Example/src/main/webapp/WEB-INF/web.xml rename to resteasy/src/main/webapp/WEB-INF/web.xml diff --git a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java b/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java new file mode 100644 index 0000000000..2a13465ebc --- /dev/null +++ b/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -0,0 +1,144 @@ +package com.baeldung.server; + +import com.baeldung.client.ServicesInterface; +import com.baeldung.model.Movie; +import org.apache.commons.io.IOUtils; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.ObjectMapper; +import org.jboss.resteasy.client.jaxrs.ResteasyClient; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.junit.Before; +import org.junit.Test; +import javax.naming.NamingException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Locale; + +public class RestEasyClientTest { + + Movie transformerMovie = null; + Movie batmanMovie = null; + ObjectMapper jsonMapper = null; + + @Before + public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { + + jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + jsonMapper.setDateFormat(sdf); + + try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/transformer.json")) { + String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Test is going to die ...", e); + } + + try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/batman.json")) { + String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); + + } catch (Exception e) { + throw new RuntimeException("Test is going to die ...", e); + } + } + + @Test + public void testListAllMovies() { + + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + + List movies = simple.listMovies(); + System.out.println(movies); + } + + @Test + public void testMovieByImdbId() { + + String transformerImdbId = "tt0418279"; + + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(transformerMovie); + moviesResponse.close(); + + Movie movies = simple.movieByImdbId(transformerImdbId); + System.out.println(movies); + } + + @Test + public void testAddMovie() { + + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.addMovie(transformerMovie); + + if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + + moviesResponse.close(); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); + } + + @Test + public void testDeleteMovi1e() { + + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + moviesResponse = simple.deleteMovie(batmanMovie.getImdbId()); + + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println(moviesResponse.readEntity(String.class)); + throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + + moviesResponse.close(); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); + } + + @Test + public void testUpdateMovie() { + + ResteasyClient client = new ResteasyClientBuilder().build(); + ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response moviesResponse = simple.addMovie(batmanMovie); + moviesResponse.close(); + batmanMovie.setTitle("Batman Begins"); + moviesResponse = simple.updateMovie(batmanMovie); + + if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { + System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); + } + + moviesResponse.close(); + System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); + } + +} \ No newline at end of file diff --git a/resteasy/src/test/resources/com/baeldung/server/movies/batman.json b/resteasy/src/test/resources/com/baeldung/server/movies/batman.json new file mode 100644 index 0000000000..82aaaa8f40 --- /dev/null +++ b/resteasy/src/test/resources/com/baeldung/server/movies/batman.json @@ -0,0 +1,4 @@ +{ + "title": "Batman", + "imdbId": "tt0096895" +} \ No newline at end of file diff --git a/resteasy/src/test/resources/com/baeldung/server/movies/transformer.json b/resteasy/src/test/resources/com/baeldung/server/movies/transformer.json new file mode 100644 index 0000000000..634cefc73c --- /dev/null +++ b/resteasy/src/test/resources/com/baeldung/server/movies/transformer.json @@ -0,0 +1,4 @@ +{ + "title": "Transformers", + "imdbId": "tt0418279" +} \ No newline at end of file From 6d9aee71bbbd62fe285f99f32e7bf8cb5a735638 Mon Sep 17 00:00:00 2001 From: Alex V Date: Thu, 18 Feb 2016 01:33:05 +0200 Subject: [PATCH 010/121] ExecutorService tutorial --- .../java8/Java8ExecutorServiceTest.java | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java new file mode 100644 index 0000000000..1609ae98a4 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java @@ -0,0 +1,155 @@ +package com.baeldung.java8; + + +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.*; +import static org.junit.Assert.*; + + +public class Java8ExecutorServiceTest { + + private Runnable runnableTask; + private Callable callableTask; + private List> callableTasks; + + @Before + public void init() { + + runnableTask = () -> { + try { + TimeUnit.MILLISECONDS.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }; + + callableTask = () -> { + TimeUnit.MILLISECONDS.sleep(300); + return "Task's execution"; + }; + + callableTasks = new ArrayList<>(); + callableTasks.add(callableTask); + callableTasks.add(callableTask); + callableTasks.add(callableTask); + } + + @Test + public void creationSubmittingTaskShuttingDown_whenShutDown_thenCorrect() { + + ExecutorService executorService = Executors.newFixedThreadPool(10); + executorService.submit(runnableTask); + executorService.submit(callableTask); + executorService.shutdown(); + + assertTrue(executorService.isShutdown()); + } + + @Test + public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() { + + ExecutorService threadPoolExecutor = + new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>()); + + for (int i = 0; i < 100; i++) { + threadPoolExecutor.submit(callableTask); + } + + List notExecutedTasks = smartShutdown(threadPoolExecutor); + + assertTrue(threadPoolExecutor.isShutdown()); + assertFalse(notExecutedTasks.isEmpty()); + assertTrue(notExecutedTasks.size() > 0 && notExecutedTasks.size() < 98); + } + + private List smartShutdown(ExecutorService executorService) { + + List notExecutedTasks = new ArrayList<>(); + executorService.shutdown(); + try { + if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) { + notExecutedTasks = executorService.shutdownNow(); + } + } catch (InterruptedException e) { + notExecutedTasks = executorService.shutdownNow(); + } + return notExecutedTasks; + } + + @Test + public void submittingTasks_whenExecutedOneAndAll_thenCorrect() { + + ExecutorService executorService = Executors.newFixedThreadPool(10); + + String result = null; + List> futures = new ArrayList<>(); + try { + result = executorService.invokeAny(callableTasks); + futures = executorService.invokeAll(callableTasks); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + + assertEquals("Task's execution", result); + assertTrue(futures.size() == 3); + } + + @Test + public void submittingTaskShuttingDown_whenGetExpectedResult_thenCorrect() { + + ExecutorService executorService = Executors.newFixedThreadPool(10); + + Future future = executorService.submit(callableTask); + String result = null; + try { + result = future.get(); + result = future.get(200, TimeUnit.MILLISECONDS); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + e.printStackTrace(); + } + + executorService.shutdown(); + + assertEquals("Task's execution", result); + } + + @Test + public void submittingTask_whenCanceled_thenCorrect() { + + ExecutorService executorService = Executors.newFixedThreadPool(10); + + Future future = executorService.submit(callableTask); + + boolean canceled = future.cancel(true); + boolean isCancelled = future.isCancelled(); + + executorService.shutdown(); + + assertTrue(canceled); + assertTrue(isCancelled); + } + + @Test + public void submittingTaskScheduling_whenExecuted_thenCorrect() { + + ScheduledExecutorService executorService = Executors + .newSingleThreadScheduledExecutor(); + + Future resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS); + String result = null; + try { + result = resultFuture.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + + executorService.shutdown(); + + assertEquals("Task's execution", result); + } +} From e58f0b0e43182616c1d3b1124778b1f6dfea8cdf Mon Sep 17 00:00:00 2001 From: David Morley Date: Thu, 18 Feb 2016 07:21:46 -0600 Subject: [PATCH 011/121] Refactor package name to conform to standard --- json-path/pom.xml | 2 +- .../baeldung/jsonpath/introduction/ChangingPasswordTest.java | 2 +- .../baeldung/jsonpath/introduction/LoggingInTest.java | 2 +- .../baeldung/jsonpath/introduction/OperationTest.java | 2 +- .../baeldung/jsonpath/introduction/RegisteringAccountTest.java | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) rename json-path/src/test/java/{org => com}/baeldung/jsonpath/introduction/ChangingPasswordTest.java (98%) rename json-path/src/test/java/{org => com}/baeldung/jsonpath/introduction/LoggingInTest.java (97%) rename json-path/src/test/java/{org => com}/baeldung/jsonpath/introduction/OperationTest.java (98%) rename json-path/src/test/java/{org => com}/baeldung/jsonpath/introduction/RegisteringAccountTest.java (97%) diff --git a/json-path/pom.xml b/json-path/pom.xml index b51f59c411..ca37447a50 100644 --- a/json-path/pom.xml +++ b/json-path/pom.xml @@ -1,7 +1,7 @@ 4.0.0 - org.baeldung + com.baeldung json-path 0.0.1-SNAPSHOT json-path diff --git a/json-path/src/test/java/org/baeldung/jsonpath/introduction/ChangingPasswordTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ChangingPasswordTest.java similarity index 98% rename from json-path/src/test/java/org/baeldung/jsonpath/introduction/ChangingPasswordTest.java rename to json-path/src/test/java/com/baeldung/jsonpath/introduction/ChangingPasswordTest.java index 24f8500d3d..9f616e1a32 100644 --- a/json-path/src/test/java/org/baeldung/jsonpath/introduction/ChangingPasswordTest.java +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ChangingPasswordTest.java @@ -1,4 +1,4 @@ -package org.baeldung.jsonpath.introduction; +package com.baeldung.jsonpath.introduction; import static org.junit.Assert.*; diff --git a/json-path/src/test/java/org/baeldung/jsonpath/introduction/LoggingInTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/LoggingInTest.java similarity index 97% rename from json-path/src/test/java/org/baeldung/jsonpath/introduction/LoggingInTest.java rename to json-path/src/test/java/com/baeldung/jsonpath/introduction/LoggingInTest.java index 1ab7dad88e..9f0be349c9 100644 --- a/json-path/src/test/java/org/baeldung/jsonpath/introduction/LoggingInTest.java +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/LoggingInTest.java @@ -1,4 +1,4 @@ -package org.baeldung.jsonpath.introduction; +package com.baeldung.jsonpath.introduction; import static org.junit.Assert.*; diff --git a/json-path/src/test/java/org/baeldung/jsonpath/introduction/OperationTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationTest.java similarity index 98% rename from json-path/src/test/java/org/baeldung/jsonpath/introduction/OperationTest.java rename to json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationTest.java index 9347a7f754..d90fafb7cb 100644 --- a/json-path/src/test/java/org/baeldung/jsonpath/introduction/OperationTest.java +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.jsonpath.introduction; +package com.baeldung.jsonpath.introduction; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; diff --git a/json-path/src/test/java/org/baeldung/jsonpath/introduction/RegisteringAccountTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/RegisteringAccountTest.java similarity index 97% rename from json-path/src/test/java/org/baeldung/jsonpath/introduction/RegisteringAccountTest.java rename to json-path/src/test/java/com/baeldung/jsonpath/introduction/RegisteringAccountTest.java index 6e5cba63b0..04bb04528a 100644 --- a/json-path/src/test/java/org/baeldung/jsonpath/introduction/RegisteringAccountTest.java +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/RegisteringAccountTest.java @@ -1,4 +1,4 @@ -package org.baeldung.jsonpath.introduction; +package com.baeldung.jsonpath.introduction; import static org.junit.Assert.*; From 54b0d4c0498a8e09405f3b3f23f9163c3fd2c3dd Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Thu, 18 Feb 2016 18:08:58 +0100 Subject: [PATCH 012/121] CleanUp --- .../src/main/java/com/baeldung/client/ServicesInterface.java | 2 +- .../src/test/java/com/baeldung/server/RestEasyClientTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/resteasy/src/main/java/com/baeldung/client/ServicesInterface.java b/resteasy/src/main/java/com/baeldung/client/ServicesInterface.java index 3d03c16faf..19ad0c1ec3 100644 --- a/resteasy/src/main/java/com/baeldung/client/ServicesInterface.java +++ b/resteasy/src/main/java/com/baeldung/client/ServicesInterface.java @@ -31,6 +31,6 @@ public interface ServicesInterface { @DELETE @Path("/deletemovie") - Response deleteMovie(@QueryParam("imdbId") String imdbID); + Response deleteMovie(@QueryParam("imdbId") String imdbId); } diff --git a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java b/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java index 2a13465ebc..680affe042 100644 --- a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -102,7 +102,7 @@ public class RestEasyClientTest { } @Test - public void testDeleteMovi1e() { + public void testDeleteMovie() { ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); From 66eb5d7270fc9d7eac0a13a0a76c6612bea2d713 Mon Sep 17 00:00:00 2001 From: sameira Date: Thu, 18 Feb 2016 22:48:42 +0530 Subject: [PATCH 013/121] Added publish subscribe example using redis --- spring-data-redis/pom.xml | 124 +++++++++--------- .../spring/data/redis/config/RedisConfig.java | 31 ++++- .../data/redis/queue/MessagePublisher.java | 7 + .../redis/queue/RedisMessagePublisher.java | 28 ++++ .../redis/queue/RedisMessageSubscriber.java | 19 +++ .../data/redis/repo/StudentRepository.java | 4 +- .../data/redis/RedisMessageListenerTest.java | 51 +++++++ 7 files changed, 198 insertions(+), 66 deletions(-) create mode 100644 spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java create mode 100644 spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java create mode 100644 spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java create mode 100644 spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java diff --git a/spring-data-redis/pom.xml b/spring-data-redis/pom.xml index 98da69934c..3f9eb705f4 100644 --- a/spring-data-redis/pom.xml +++ b/spring-data-redis/pom.xml @@ -1,76 +1,76 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - org.baeldung - sprint-data-redis - 0.0.1-SNAPSHOT - jar + org.baeldung + sprint-data-redis + 0.0.1-SNAPSHOT + jar - - UTF-8 - 4.2.2.RELEASE - 1.6.2.RELEASE - 0.8.0 - + + UTF-8 + 4.2.2.RELEASE + 1.6.2.RELEASE + 0.8.0 + - - - org.springframework.data - spring-data-redis - ${spring-data-redis} - + + + org.springframework.data + spring-data-redis + ${spring-data-redis} + - - cglib - cglib-nodep - 2.2 - + + cglib + cglib-nodep + 2.2 + - - log4j - log4j - 1.2.16 - + + log4j + log4j + 1.2.16 + - - redis.clients - jedis - 2.5.1 - jar - + + redis.clients + jedis + 2.5.1 + jar + - - org.springframework - spring-core - ${spring.version} - + + org.springframework + spring-core + ${spring.version} + - - org.springframework - spring-context - ${spring.version} - + + org.springframework + spring-context + ${spring.version} + - - junit - junit - 4.12 - test - + + junit + junit + 4.12 + test + - - org.springframework - spring-test - ${spring.version} - test - + + org.springframework + spring-test + ${spring.version} + test + - - com.lordofthejars - nosqlunit-redis - ${nosqlunit.version} - + + com.lordofthejars + nosqlunit-redis + ${nosqlunit.version} + - + diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java index a7e75a438a..0b64afe56c 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java @@ -1,10 +1,16 @@ package org.baeldung.spring.data.redis.config; +import org.baeldung.spring.data.redis.queue.RedisMessageSubscriber; +import org.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import org.baeldung.spring.data.redis.queue.MessagePublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.listener.ChannelTopic; +import org.springframework.data.redis.listener.RedisMessageListenerContainer; +import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; @Configuration @ComponentScan("org.baeldung.spring.data.redis") @@ -17,8 +23,31 @@ public class RedisConfig { @Bean public RedisTemplate redisTemplate() { - final RedisTemplate< String, Object> template = new RedisTemplate(); + final RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(jedisConnectionFactory()); return template; } + + @Bean + MessageListenerAdapter messageListener() { + return new MessageListenerAdapter(new RedisMessageSubscriber()); + } + + @Bean + RedisMessageListenerContainer redisContainer() { + final RedisMessageListenerContainer container = new RedisMessageListenerContainer(); + container.setConnectionFactory(jedisConnectionFactory()); + container.addMessageListener(messageListener(), topic()); + return container; + } + + @Bean + MessagePublisher redisPublisher() { + return new RedisMessagePublisher(redisTemplate(), topic()); + } + + @Bean + ChannelTopic topic() { + return new ChannelTopic("pubsub:queue"); + } } diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java new file mode 100644 index 0000000000..a05f524f60 --- /dev/null +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java @@ -0,0 +1,7 @@ +package org.baeldung.spring.data.redis.queue; + + +public interface MessagePublisher { + + void publish(String message); +} diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java new file mode 100644 index 0000000000..4eb7f69cdb --- /dev/null +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java @@ -0,0 +1,28 @@ +package org.baeldung.spring.data.redis.queue; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.listener.ChannelTopic; +import org.springframework.stereotype.Service; + +@Service +public class RedisMessagePublisher implements MessagePublisher { + + @Autowired + private RedisTemplate redisTemplate; + @Autowired + private ChannelTopic topic; + + public RedisMessagePublisher() { + } + + public RedisMessagePublisher(RedisTemplate redisTemplate, + ChannelTopic topic) { + this.redisTemplate = redisTemplate; + this.topic = topic; + } + + public void publish(String message) { + redisTemplate.convertAndSend(topic.getTopic(), message); + } +} diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java new file mode 100644 index 0000000000..4bc60849fb --- /dev/null +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java @@ -0,0 +1,19 @@ +package org.baeldung.spring.data.redis.queue; + +import org.springframework.data.redis.connection.Message; +import org.springframework.data.redis.connection.MessageListener; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class RedisMessageSubscriber implements MessageListener { + + public static List messageList = new ArrayList(); + + public void onMessage(final Message message, final byte[] pattern) { + messageList.add(message.toString()); + System.out.println("Message received: " + message.toString()); + } +} \ No newline at end of file diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java index 9e5502f8e0..2a1f6afcce 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java @@ -1,15 +1,13 @@ package org.baeldung.spring.data.redis.repo; import org.baeldung.spring.data.redis.model.Student; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Component; import java.util.Map; public interface StudentRepository { void saveStudent(Student person); - + void updateStudent(Student student); Student findStudent(String id); diff --git a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java new file mode 100644 index 0000000000..7308424a90 --- /dev/null +++ b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java @@ -0,0 +1,51 @@ +package org.baeldung.spring.data.redis; + +import org.baeldung.spring.data.redis.config.RedisConfig; +import org.baeldung.spring.data.redis.queue.RedisMessageSubscriber; +import org.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.UUID; + +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RedisConfig.class) +public class RedisMessageListenerTest { + + + @Autowired + private RedisMessagePublisher redisMessagePublisher; + + @Test + public void testOnMessage() throws Exception { + String message = "Message " + UUID.randomUUID(); + redisMessagePublisher.publish(message); + Thread.sleep(100); + assertTrue(RedisMessageSubscriber.messageList.get(0).contains(message)); + } + + public void testOnPMessage() throws Exception { + + } + + public void testOnSubscribe() throws Exception { + + } + + public void testOnUnsubscribe() throws Exception { + + } + + public void testOnPUnsubscribe() throws Exception { + + } + + public void testOnPSubscribe() throws Exception { + + } +} \ No newline at end of file From a304aa9860f60268bdbf33f2ff8fa428fd642f2f Mon Sep 17 00:00:00 2001 From: sameira Date: Thu, 18 Feb 2016 22:49:50 +0530 Subject: [PATCH 014/121] Refined the test case --- .../data/redis/RedisMessageListenerTest.java | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java index 7308424a90..19612e0029 100644 --- a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java +++ b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java @@ -28,24 +28,4 @@ public class RedisMessageListenerTest { Thread.sleep(100); assertTrue(RedisMessageSubscriber.messageList.get(0).contains(message)); } - - public void testOnPMessage() throws Exception { - - } - - public void testOnSubscribe() throws Exception { - - } - - public void testOnUnsubscribe() throws Exception { - - } - - public void testOnPUnsubscribe() throws Exception { - - } - - public void testOnPSubscribe() throws Exception { - - } } \ No newline at end of file From 2ccdd4ecbb16184a03ed095df8a020748b3a325b Mon Sep 17 00:00:00 2001 From: sameira Date: Thu, 18 Feb 2016 22:51:35 +0530 Subject: [PATCH 015/121] Refined the test case --- .../baeldung/spring/data/redis/queue/MessagePublisher.java | 2 +- .../spring/data/redis/queue/RedisMessagePublisher.java | 6 +++--- .../spring/data/redis/RedisMessageListenerTest.java | 1 - 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java index a05f524f60..e1f2e3d4b2 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java @@ -3,5 +3,5 @@ package org.baeldung.spring.data.redis.queue; public interface MessagePublisher { - void publish(String message); + void publish(final String message); } diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java index 4eb7f69cdb..58e789daab 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java @@ -16,13 +16,13 @@ public class RedisMessagePublisher implements MessagePublisher { public RedisMessagePublisher() { } - public RedisMessagePublisher(RedisTemplate redisTemplate, - ChannelTopic topic) { + public RedisMessagePublisher(final RedisTemplate redisTemplate, + final ChannelTopic topic) { this.redisTemplate = redisTemplate; this.topic = topic; } - public void publish(String message) { + public void publish(final String message) { redisTemplate.convertAndSend(topic.getTopic(), message); } } diff --git a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java index 19612e0029..f355e7f63a 100644 --- a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java +++ b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java @@ -17,7 +17,6 @@ import static org.junit.Assert.assertTrue; @ContextConfiguration(classes = RedisConfig.class) public class RedisMessageListenerTest { - @Autowired private RedisMessagePublisher redisMessagePublisher; From 54a1235d175827af25d7089f644549365fbb9ff9 Mon Sep 17 00:00:00 2001 From: David Morley Date: Thu, 18 Feb 2016 21:31:51 -0600 Subject: [PATCH 016/121] Clean up Apache Camel example --- spring-apache-camel/README.md | 4 +- .../baeldung}/camel/main/App.java | 22 +- .../camel/processor/FileProcessor.java | 14 ++ .../apache/camel/processor/FileProcessor.java | 14 -- .../src/main/resources/camel-context.xml | 49 +++-- .../src/test/data/sampleInputFile/file.txt | 2 +- .../java/org/apache/camel/main/AppTest.java | 190 +++++++++--------- 7 files changed, 147 insertions(+), 148 deletions(-) rename spring-apache-camel/src/main/java/{org/apache => com/baeldung}/camel/main/App.java (62%) create mode 100644 spring-apache-camel/src/main/java/com/baeldung/camel/processor/FileProcessor.java delete mode 100644 spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java diff --git a/spring-apache-camel/README.md b/spring-apache-camel/README.md index 28b95bdf89..f6ae77b2a5 100644 --- a/spring-apache-camel/README.md +++ b/spring-apache-camel/README.md @@ -23,6 +23,6 @@ To build this application execute following maven command in ApacheCamelFileProc mvn clean install -To run this application you can either run our main class org.apache.camel.main.App from your IDE or you can execute following maven command: +To run this application you can either run our main class App from your IDE or you can execute following maven command: -mvn exec:java -Dexec.mainClass="org.apache.camel.main.App" \ No newline at end of file +mvn exec:java -Dexec.mainClass="App" \ No newline at end of file diff --git a/spring-apache-camel/src/main/java/org/apache/camel/main/App.java b/spring-apache-camel/src/main/java/com/baeldung/camel/main/App.java similarity index 62% rename from spring-apache-camel/src/main/java/org/apache/camel/main/App.java rename to spring-apache-camel/src/main/java/com/baeldung/camel/main/App.java index 8674caefca..ac0605a215 100644 --- a/spring-apache-camel/src/main/java/org/apache/camel/main/App.java +++ b/spring-apache-camel/src/main/java/com/baeldung/camel/main/App.java @@ -1,12 +1,12 @@ -package org.apache.camel.main; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class App { - public static void main(final String[] args) throws Exception { - ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context.xml"); - // Keep main thread alive for some time to let application finish processing the input files. - Thread.sleep(5000); - applicationContext.close(); - } +package com.baeldung.camel.main; + +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class App { + public static void main(final String[] args) throws Exception { + ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context.xml"); + // Keep main thread alive for some time to let application finish processing the input files. + Thread.sleep(5000); + applicationContext.close(); + } } \ No newline at end of file diff --git a/spring-apache-camel/src/main/java/com/baeldung/camel/processor/FileProcessor.java b/spring-apache-camel/src/main/java/com/baeldung/camel/processor/FileProcessor.java new file mode 100644 index 0000000000..971dd206cd --- /dev/null +++ b/spring-apache-camel/src/main/java/com/baeldung/camel/processor/FileProcessor.java @@ -0,0 +1,14 @@ +package com.baeldung.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +public class FileProcessor implements Processor { + + public void process(Exchange exchange) throws Exception { + String originalFileContent = exchange.getIn().getBody(String.class); + String upperCaseFileContent = originalFileContent.toUpperCase(); + exchange.getIn().setBody(upperCaseFileContent); + } + +} diff --git a/spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java b/spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java deleted file mode 100644 index a98c77feb8..0000000000 --- a/spring-apache-camel/src/main/java/org/apache/camel/processor/FileProcessor.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.apache.camel.processor; - -import org.apache.camel.Exchange; -import org.apache.camel.Processor; - -public class FileProcessor implements Processor { - - public void process(Exchange exchange) throws Exception { - String originalFileContent = exchange.getIn().getBody(String.class); - String upperCaseFileContent = originalFileContent.toUpperCase(); - exchange.getIn().setBody(upperCaseFileContent); - } - -} diff --git a/spring-apache-camel/src/main/resources/camel-context.xml b/spring-apache-camel/src/main/resources/camel-context.xml index 75e2a61711..0c10e0ecef 100644 --- a/spring-apache-camel/src/main/resources/camel-context.xml +++ b/spring-apache-camel/src/main/resources/camel-context.xml @@ -1,40 +1,39 @@ - + - + - - + + - - + + - - + + - - - ${body.toLowerCase()} - + + + ${body.toLowerCase()} + - - + + - - - .......... File content conversion completed .......... - - - + + + .......... File content conversion completed .......... + + - + - + - + \ No newline at end of file diff --git a/spring-apache-camel/src/test/data/sampleInputFile/file.txt b/spring-apache-camel/src/test/data/sampleInputFile/file.txt index c1df3791c9..e057427864 100644 --- a/spring-apache-camel/src/test/data/sampleInputFile/file.txt +++ b/spring-apache-camel/src/test/data/sampleInputFile/file.txt @@ -1 +1 @@ -THIS IS UPPERCASE CONTENT. this is lowercase content. \ No newline at end of file +This is data that will be processed by a Camel route! \ No newline at end of file diff --git a/spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java b/spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java index 75a161d8cc..87b20369f3 100644 --- a/spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java +++ b/spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java @@ -1,5 +1,12 @@ package org.apache.camel.main; +import com.baeldung.camel.main.App; +import junit.framework.TestCase; +import org.apache.camel.util.FileUtil; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -8,110 +15,103 @@ import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Paths; -import junit.framework.TestCase; - -import org.apache.camel.util.FileUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - public class AppTest extends TestCase { - private static final String FILE_NAME = "file.txt"; - private static final String SAMPLE_INPUT_DIR = "src/test/data/sampleInputFile/"; - private static final String TEST_INPUT_DIR = "src/test/data/input/"; - private static final String UPPERCARE_OUTPUT_DIR = "src/test/data/outputUpperCase/"; - private static final String LOWERCASE_OUTPUT_DIR = "src/test/data/outputLowerCase/"; + private static final String FILE_NAME = "file.txt"; + private static final String SAMPLE_INPUT_DIR = "src/test/data/sampleInputFile/"; + private static final String TEST_INPUT_DIR = "src/test/data/input/"; + private static final String UPPERCASE_OUTPUT_DIR = "src/test/data/outputUpperCase/"; + private static final String LOWERCASE_OUTPUT_DIR = "src/test/data/outputLowerCase/"; - @Before - public void setUp() throws Exception { - // Prepare input file for test - copySampleFileToInputDirectory(); - } + @Before + public void setUp() throws Exception { + // Prepare input file for test + copySampleFileToInputDirectory(); + } - @After - public void tearDown() throws Exception { - System.out.println("Deleting the test input and output files..."); - deleteFile(TEST_INPUT_DIR); - deleteFile(LOWERCASE_OUTPUT_DIR); - deleteFile(UPPERCARE_OUTPUT_DIR); - } + @After + public void tearDown() throws Exception { + System.out.println("Deleting the test input and output files..."); + deleteFile(TEST_INPUT_DIR); + deleteFile(LOWERCASE_OUTPUT_DIR); + deleteFile(UPPERCASE_OUTPUT_DIR); + } - @Test - public final void testMain() throws Exception { - App.main(null); + @Test + public final void testMain() throws Exception { + App.main(null); - String inputFileContent = readFileContent(SAMPLE_INPUT_DIR+FILE_NAME); - String outputUpperCase = readFileContent(UPPERCARE_OUTPUT_DIR+FILE_NAME); - String outputLowerCase = readFileContent(LOWERCASE_OUTPUT_DIR+FILE_NAME); - - System.out.println("Input File content = ["+inputFileContent+"]"); - System.out.println("UpperCaseOutput file content = ["+outputUpperCase+"]"); - System.out.println("LowerCaseOtput file content = ["+outputLowerCase+"]"); - - assertEquals(inputFileContent.toUpperCase(), outputUpperCase); - assertEquals(inputFileContent.toLowerCase(), outputLowerCase); - } + String inputFileContent = readFileContent(SAMPLE_INPUT_DIR + FILE_NAME); + String outputUpperCase = readFileContent(UPPERCASE_OUTPUT_DIR + FILE_NAME); + String outputLowerCase = readFileContent(LOWERCASE_OUTPUT_DIR + FILE_NAME); - private String readFileContent(String path) throws IOException { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded); - } + System.out.println("Input File content = [" + inputFileContent + "]"); + System.out.println("UpperCaseOutput file content = [" + outputUpperCase + "]"); + System.out.println("LowerCaseOtput file content = [" + outputLowerCase + "]"); - private void deleteFile(String path) { - try { - FileUtil.removeDir(new File(path)); - } catch (Exception e) { - e.printStackTrace(); - } - } + assertEquals(inputFileContent.toUpperCase(), outputUpperCase); + assertEquals(inputFileContent.toLowerCase(), outputLowerCase); + } - /** - * Copy sample input file to input directory. - */ - private void copySampleFileToInputDirectory() { - File sourceFile = new File(SAMPLE_INPUT_DIR + FILE_NAME); - File destFile = new File(TEST_INPUT_DIR + FILE_NAME); - - if (!sourceFile.exists()) { - System.out.println("Sample input file not found at location = [" + SAMPLE_INPUT_DIR + FILE_NAME + "]. Please provide this file."); - } + private String readFileContent(String path) throws IOException { + byte[] encoded = Files.readAllBytes(Paths.get(path)); + return new String(encoded); + } - if (!destFile.exists()) { - try { - System.out.println("Creating input file = [" + TEST_INPUT_DIR + FILE_NAME + "]"); - - File destDir = new File(TEST_INPUT_DIR); - if(!destDir.exists()) { - destDir.mkdir(); - } - destFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - FileChannel source = null; - FileChannel destination = null; + private void deleteFile(String path) { + try { + FileUtil.removeDir(new File(path)); + } catch (Exception e) { + e.printStackTrace(); + } + } - try { - source = new FileInputStream(sourceFile).getChannel(); - destination = new FileOutputStream(destFile).getChannel(); - if (destination != null && source != null) { - destination.transferFrom(source, 0, source.size()); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - source.close(); - } catch (Exception e) { - e.printStackTrace(); - } - try { - destination.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } + /** + * Copy sample input file to input directory. + */ + private void copySampleFileToInputDirectory() { + File sourceFile = new File(SAMPLE_INPUT_DIR + FILE_NAME); + File destFile = new File(TEST_INPUT_DIR + FILE_NAME); + + if (!sourceFile.exists()) { + System.out.println("Sample input file not found at location = [" + SAMPLE_INPUT_DIR + FILE_NAME + "]. Please provide this file."); + } + + if (!destFile.exists()) { + try { + System.out.println("Creating input file = [" + TEST_INPUT_DIR + FILE_NAME + "]"); + + File destDir = new File(TEST_INPUT_DIR); + if (!destDir.exists()) { + destDir.mkdir(); + } + destFile.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + FileChannel source = null; + FileChannel destination = null; + + try { + source = new FileInputStream(sourceFile).getChannel(); + destination = new FileOutputStream(destFile).getChannel(); + if (destination != null && source != null) { + destination.transferFrom(source, 0, source.size()); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + source.close(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + destination.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } } From 90853626d29edd3516e9d83bcd9726de36494054 Mon Sep 17 00:00:00 2001 From: Ivan Date: Fri, 19 Feb 2016 17:25:54 +0100 Subject: [PATCH 017/121] Add form tag example --- .../spring/controller/PersonController.java | 39 +++++---- .../java/org/baeldung/spring/form/Person.java | 22 ++++- .../spring/validator/PersonValidator.java | 22 +++++ .../main/webapp/WEB-INF/view/personForm.jsp | 15 +++- .../main/webapp/WEB-INF/view/personResume.jsp | 65 --------------- .../main/webapp/WEB-INF/view/personView.jsp | 80 +++++++++++++++++++ 6 files changed, 156 insertions(+), 87 deletions(-) create mode 100644 spring-mvc-xml/src/main/java/org/baeldung/spring/validator/PersonValidator.java delete mode 100644 spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp create mode 100644 spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java index d5b68c7516..0d89a29b9d 100644 --- a/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/PersonController.java @@ -8,6 +8,8 @@ import java.util.Map; import javax.validation.Valid; import org.baeldung.spring.form.Person; +import org.baeldung.spring.validator.PersonValidator; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; @@ -20,6 +22,9 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class PersonController { + @Autowired + PersonValidator validator; + @RequestMapping(value = "/person", method = RequestMethod.GET) public ModelAndView showForm(final Model model) { @@ -31,6 +36,8 @@ public class PersonController { public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, final ModelMap modelMap, final Model model) { + validator.validate(person, result); + if (result.hasErrors()) { initData(model); @@ -39,28 +46,28 @@ public class PersonController { modelMap.addAttribute("person", person); - return "personResume"; + return "personView"; } private void initData(final Model model) { - final List favouriteLanguage = new ArrayList(); - favouriteLanguage.add("Java"); - favouriteLanguage.add("C++"); - favouriteLanguage.add("Perl"); - model.addAttribute("favouriteLanguage", favouriteLanguage); + final List favouriteLanguageItem = new ArrayList(); + favouriteLanguageItem.add("Java"); + favouriteLanguageItem.add("C++"); + favouriteLanguageItem.add("Perl"); + model.addAttribute("favouriteLanguageItem", favouriteLanguageItem); - final List job = new ArrayList(); - job.add("Full time"); - job.add("Part time"); - model.addAttribute("job", job); + final List jobItem = new ArrayList(); + jobItem.add("Full time"); + jobItem.add("Part time"); + model.addAttribute("jobItem", jobItem); - final Map country = new LinkedHashMap(); - country.put("US", "United Stated"); - country.put("IT", "Italy"); - country.put("UK", "United Kingdom"); - country.put("FR", "Grance"); - model.addAttribute("country", country); + final Map countryItems = new LinkedHashMap(); + countryItems.put("US", "United Stated"); + countryItems.put("IT", "Italy"); + countryItems.put("UK", "United Kingdom"); + countryItems.put("FR", "Grance"); + model.addAttribute("countryItems", countryItems); final List fruit = new ArrayList(); fruit.add("Banana"); diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java index 3db8cc4377..bf313b4d7d 100644 --- a/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Person.java @@ -9,8 +9,9 @@ public class Person { private long id; - @NotEmpty private String name; + private String email; + private String dateOfBirth; @NotEmpty private String password; @@ -18,7 +19,7 @@ public class Person { private String country; private String book; private String job; - boolean receiveNewsletter; + private boolean receiveNewsletter; private String[] hobbies; private List favouriteLanguage; private List fruit; @@ -45,6 +46,22 @@ public class Person { this.name = name; } + public String getEmail() { + return email; + } + + public void setEmail(final String email) { + this.email = email; + } + + public String getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(final String dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + public String getPassword() { return password; } @@ -132,5 +149,4 @@ public class Person { public void setFile(final MultipartFile file) { this.file = file; } - } diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/validator/PersonValidator.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/validator/PersonValidator.java new file mode 100644 index 0000000000..068a9fee7f --- /dev/null +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/validator/PersonValidator.java @@ -0,0 +1,22 @@ +package org.baeldung.spring.validator; + +import org.baeldung.spring.form.Person; +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import org.springframework.validation.ValidationUtils; +import org.springframework.validation.Validator; + +@Component +public class PersonValidator implements Validator { + + @Override + public boolean supports(final Class calzz) { + return Person.class.isAssignableFrom(calzz); + } + + @Override + public void validate(final Object obj, final Errors errors) { + + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name"); + } +} \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp index 9ef02efbae..9b0a78899c 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp @@ -28,6 +28,15 @@ + + E-mail + + + + + Date of birth + + Password @@ -43,13 +52,13 @@ Job - + Country - + @@ -82,7 +91,7 @@ Favourite languages - + diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp deleted file mode 100644 index 857738c545..0000000000 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personResume.jsp +++ /dev/null @@ -1,65 +0,0 @@ -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> - - - -Spring MVC Form Handling - - - -

Submitted Person Information

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Id :${person.id}
Name :${person.name}
Password :${person.password}
Sex :${person.sex}
Job :${person.job}
Country :${person.country}
Fruit :[]
Book :${person.book}
Receive Newsletter :${person.receiveNewsletter}
Hobbies :[]
Favourite Languages :[]
Notes :${person.notes}
File :${person.file.originalFilename}
- - \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp new file mode 100644 index 0000000000..8893314d20 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp @@ -0,0 +1,80 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + + + + Spring MVC Form Handling + + + +

Submitted Person Information

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Id :${person.id}
Name :${person.name}
Date of birth :${person.dateOfBirth}
Password :${person.password}
Sex :${person.sex}
Job :${person.job}
Country :${person.country}
Fruit :[]
Book :${person.book}
Receive Newsletter :${person.receiveNewsletter}
Hobbies :[]
Favourite Languages :[]
Notes :${person.notes}
+ +

Submitted File

+ + + + + + + + + + + + +
OriginalFileName :${person.file.originalFilename}
Type :${person.file.contentType}
+ + \ No newline at end of file From 2f1270d047690d6a58b5a2073bea24c062db0427 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Fri, 19 Feb 2016 19:50:19 +0100 Subject: [PATCH 018/121] HttpClient with Connection Pool --- .../baeldung/server/RestEasyClientTest.java | 51 ++++++++++++++++--- 1 file changed, 43 insertions(+), 8 deletions(-) diff --git a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java b/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java index 680affe042..9a292bf3c3 100644 --- a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -3,11 +3,15 @@ package com.baeldung.server; import com.baeldung.client.ServicesInterface; import com.baeldung.model.Movie; import org.apache.commons.io.IOUtils; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine; import org.junit.Before; import org.junit.Test; import javax.naming.NamingException; @@ -21,6 +25,7 @@ import java.util.Locale; public class RestEasyClientTest { + public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest"); Movie transformerMovie = null; Movie batmanMovie = null; ObjectMapper jsonMapper = null; @@ -54,7 +59,7 @@ public class RestEasyClientTest { public void testListAllMovies() { ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ResteasyWebTarget target = client.target(FULL_PATH); ServicesInterface simple = target.proxy(ServicesInterface.class); Response moviesResponse = simple.addMovie(transformerMovie); @@ -72,7 +77,7 @@ public class RestEasyClientTest { String transformerImdbId = "tt0418279"; ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ResteasyWebTarget target = client.target(FULL_PATH); ServicesInterface simple = target.proxy(ServicesInterface.class); Response moviesResponse = simple.addMovie(transformerMovie); @@ -86,7 +91,7 @@ public class RestEasyClientTest { public void testAddMovie() { ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ResteasyWebTarget target = client.target(FULL_PATH); ServicesInterface simple = target.proxy(ServicesInterface.class); Response moviesResponse = simple.addMovie(batmanMovie); @@ -98,14 +103,44 @@ public class RestEasyClientTest { } moviesResponse.close(); - System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + moviesResponse.getStatus()); + } + + @Test + public void testAddMovieMultiConnection() { + + PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); + CloseableHttpClient httpClient = HttpClients.custom() + .setConnectionManager(cm) + .build(); + ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); + ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); + ResteasyWebTarget target = client.target(FULL_PATH); + ServicesInterface simple = target.proxy(ServicesInterface.class); + + Response batmanResponse = simple.addMovie(batmanMovie); + Response transformerResponse = simple.addMovie(transformerMovie); + + if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { + System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus()); + } + if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { + System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus()); + } + + batmanResponse.close(); + transformerResponse.close(); + cm.close(); + + + } @Test public void testDeleteMovie() { ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ResteasyWebTarget target = client.target(FULL_PATH); ServicesInterface simple = target.proxy(ServicesInterface.class); Response moviesResponse = simple.addMovie(batmanMovie); @@ -118,14 +153,14 @@ public class RestEasyClientTest { } moviesResponse.close(); - System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + moviesResponse.getStatus()); } @Test public void testUpdateMovie() { ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest")); + ResteasyWebTarget target = client.target(FULL_PATH); ServicesInterface simple = target.proxy(ServicesInterface.class); Response moviesResponse = simple.addMovie(batmanMovie); @@ -138,7 +173,7 @@ public class RestEasyClientTest { } moviesResponse.close(); - System.out.println("Response Code: " + Response.Status.OK.getStatusCode()); + System.out.println("Response Code: " + moviesResponse.getStatus()); } } \ No newline at end of file From e00f62fb033e312e4a63bb17a971984583c32d42 Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Fri, 19 Feb 2016 20:04:06 +0100 Subject: [PATCH 019/121] cleanUp --- .../baeldung/server/RestEasyClientTest.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java b/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java index 9a292bf3c3..ef18b0f23f 100644 --- a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java @@ -60,14 +60,14 @@ public class RestEasyClientTest { ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(transformerMovie); + Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); - moviesResponse = simple.addMovie(batmanMovie); + moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); - List movies = simple.listMovies(); + List movies = proxy.listMovies(); System.out.println(movies); } @@ -78,12 +78,12 @@ public class RestEasyClientTest { ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(transformerMovie); + Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); - Movie movies = simple.movieByImdbId(transformerImdbId); + Movie movies = proxy.movieByImdbId(transformerImdbId); System.out.println(movies); } @@ -92,11 +92,11 @@ public class RestEasyClientTest { ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(batmanMovie); + Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); - moviesResponse = simple.addMovie(transformerMovie); + moviesResponse = proxy.addMovie(transformerMovie); if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); @@ -116,10 +116,10 @@ public class RestEasyClientTest { ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response batmanResponse = simple.addMovie(batmanMovie); - Response transformerResponse = simple.addMovie(transformerMovie); + Response batmanResponse = proxy.addMovie(batmanMovie); + Response transformerResponse = proxy.addMovie(transformerMovie); if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus()); @@ -141,11 +141,11 @@ public class RestEasyClientTest { ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(batmanMovie); + Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); - moviesResponse = simple.deleteMovie(batmanMovie.getImdbId()); + moviesResponse = proxy.deleteMovie(batmanMovie.getImdbId()); if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { System.out.println(moviesResponse.readEntity(String.class)); @@ -161,12 +161,12 @@ public class RestEasyClientTest { ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface simple = target.proxy(ServicesInterface.class); + ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response moviesResponse = simple.addMovie(batmanMovie); + Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); batmanMovie.setTitle("Batman Begins"); - moviesResponse = simple.updateMovie(batmanMovie); + moviesResponse = proxy.updateMovie(batmanMovie); if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); From 95bc7e515d37107a12b9d3e6b1f792bd15889ecb Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 19 Feb 2016 22:12:57 +0200 Subject: [PATCH 020/121] oauth multiple resources authorization --- .../config/OAuth2ResourceServerConfig.java | 26 +++++++--- .../web/controller/BarController.java | 41 +++++++++++++++ .../web/controller/FooController.java | 16 +++++- .../main/java/org/baeldung/web/dto/Bar.java | 36 +++++++++++++ .../OAuth2AuthorizationServerConfig.java | 6 +-- .../baeldung/config/ServerSecurityConfig.java | 3 +- .../.project | 10 ++-- .../src/main/resources/templates/header.html | 50 +++++++++++++++++-- .../src/main/resources/templates/index.html | 40 ++++++++++++--- 9 files changed, 200 insertions(+), 28 deletions(-) create mode 100644 spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java create mode 100644 spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Bar.java diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java index c5e33739ae..52bfeb4233 100644 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java @@ -7,12 +7,13 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; +import org.springframework.http.HttpMethod; import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; -import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; @@ -20,14 +21,25 @@ import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; @PropertySource({ "classpath:persistence.properties" }) @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true) -public class OAuth2ResourceServerConfig extends GlobalMethodSecurityConfiguration { - +public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { @Autowired private Environment env; @Override - protected MethodSecurityExpressionHandler createExpressionHandler() { - return new OAuth2MethodSecurityExpressionHandler(); + public void configure(HttpSecurity http) throws Exception { + // @formatter:off + http + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) + .and() + .requestMatchers().antMatchers("/foos/**","/bars/**") + .and() + .authorizeRequests() + .antMatchers(HttpMethod.GET,"/foos/**").access("#oauth2.hasScope('read')") + .antMatchers(HttpMethod.POST,"/foos/**").access("#oauth2.hasScope('write')") + .antMatchers(HttpMethod.GET,"/bars/**").access("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')") + .antMatchers(HttpMethod.POST,"/bars/**").access("#oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") + ; + // @formatter:on } @Bean diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java new file mode 100644 index 0000000000..a716635f6d --- /dev/null +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java @@ -0,0 +1,41 @@ +package org.baeldung.web.controller; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; + +import org.baeldung.web.dto.Bar; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +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.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +@Controller +public class BarController { + + public BarController() { + super(); + } + + // API - read + // @PreAuthorize("#oauth2.hasScope('read')") + @RequestMapping(method = RequestMethod.GET, value = "/bars/{id}") + @ResponseBody + public Bar findById(@PathVariable final long id) { + return new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); + } + + // API - write + // @PreAuthorize("#oauth2.hasScope('write')") + @RequestMapping(method = RequestMethod.POST, value = "/bars") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Bar create(@RequestBody final Bar bar) { + bar.setId(Long.parseLong(randomNumeric(2))); + return bar; + } + +} diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/FooController.java index 8dfa19bd84..a1275670f0 100644 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/FooController.java @@ -4,12 +4,14 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import org.baeldung.web.dto.Foo; -import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; 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.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; @Controller public class FooController { @@ -19,11 +21,21 @@ public class FooController { } // API - read - @PreAuthorize("#oauth2.hasScope('read')") + // @PreAuthorize("#oauth2.hasScope('read')") @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { return new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); } + // API - write + // @PreAuthorize("#oauth2.hasScope('write')") + @RequestMapping(method = RequestMethod.POST, value = "/foos") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo create(@RequestBody final Foo foo) { + foo.setId(Long.parseLong(randomNumeric(2))); + return foo; + } + } diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Bar.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Bar.java new file mode 100644 index 0000000000..adbb2aa2ad --- /dev/null +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Bar.java @@ -0,0 +1,36 @@ +package org.baeldung.web.dto; + +public class Bar { + private long id; + private String name; + + public Bar() { + super(); + } + + public Bar(final long id, final String name) { + super(); + + this.id = id; + this.name = name; + } + + // + + 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; + } + +} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java index c2f6ca41ae..a0f8baa4bc 100644 --- a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java +++ b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java @@ -47,10 +47,10 @@ public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigur public void configure(ClientDetailsServiceConfigurer clients) throws Exception { // @formatter:off clients.jdbc(dataSource()) - .withClient("clientId") + .withClient("sampleClientId") .authorizedGrantTypes("implicit") - .scopes("read") - .autoApprove(true) + .scopes("read","write") + .autoApprove(false) .and() .withClient("clientIdPassword") .secret("secret") diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerSecurityConfig.java b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerSecurityConfig.java index 3e1a8a8ccb..46870f3fc3 100644 --- a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerSecurityConfig.java +++ b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerSecurityConfig.java @@ -12,8 +12,7 @@ public class ServerSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("john").password("123").roles("USER"); - + auth.inMemoryAuthentication().withUser("john").password("123").roles("USER").and().withUser("tom").password("111").roles("ADMIN"); } @Override diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/.project b/spring-security-oauth/spring-security-oauth-ui-implicit/.project index c9fc2aa8f0..b96a26c60d 100644 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/.project +++ b/spring-security-oauth/spring-security-oauth-ui-implicit/.project @@ -25,11 +25,6 @@ - - org.eclipse.m2e.core.maven2Builder - - - org.springframework.ide.eclipse.core.springbuilder @@ -40,6 +35,11 @@ + + org.eclipse.m2e.core.maven2Builder + + + org.eclipse.jem.workbench.JavaEMFNature diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html index a62bce9747..8cd7be67c3 100644 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html +++ b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html @@ -11,9 +11,9 @@ @@ -34,9 +34,21 @@ app.config(function($locationProvider) { }).hashPrefix('!'); }); +app.config(['$httpProvider', function ($httpProvider) { + $httpProvider.interceptors.push(function ($q,$rootScope) { + return { + 'responseError': function (responseError) { + $rootScope.message = responseError.statusText; + console.log("error here"); + console.log(responseError); + return $q.reject(responseError); + } + }; + }); +}]); -app.controller('mainCtrl', function($scope,$resource,$http) { +app.controller('mainCtrl', function($scope,$resource,$http,$rootScope) { $scope.$on('oauth:login', function(event, token) { $http.defaults.headers.common.Authorization= 'Bearer ' + token.access_token; @@ -49,6 +61,38 @@ app.controller('mainCtrl', function($scope,$resource,$http) { $scope.getFoo = function(){ $scope.foo = $scope.foos.get({fooId:$scope.foo.id}); } + + $scope.createFoo = function(){ + if($scope.foo.name.length==0) + { + $rootScope.message = "Foo name can not be empty"; + return; + } + $scope.foo.id = null; + $scope.foo = $scope.foos.save($scope.foo, function(){ + $rootScope.message = "Foo Created Successfully"; + }); + } + + // bar + $scope.bar = {id:0 , name:"sample bar"}; + $scope.bars = $resource("http://localhost:8081/spring-security-oauth-resource/bars/:barId",{barId:'@id'}); + + $scope.getBar = function(){ + $scope.bar = $scope.bars.get({barId:$scope.bar.id}); + } + + $scope.createBar = function(){ + if($scope.bar.name.length==0) + { + $rootScope.message = "Bar name can not be empty"; + return; + } + $scope.bar.id = null; + $scope.bar = $scope.bars.save($scope.bar, function(){ + $rootScope.message = "Bar Created Successfully"; + }); + } }); /*]]>*/ diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html index c98ed493bd..c50781caf1 100755 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html +++ b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html @@ -10,19 +10,47 @@
-

Foo Details

+
{{message}}
+

Foo Details

+
- - {{foo.id}} + +
- -{{foo.name}} + +
+
+ +
+
+
+
+
+

Bar Details

+
+
+ + +
+ +
+ + +
+ + +
From f8258e92210dbd61dae5aeb010360dff577c77f7 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sun, 21 Feb 2016 12:58:42 +0200 Subject: [PATCH 021/121] oauth2 live test --- .../baeldung/config/MethodSecurityConfig.java | 16 ++++++ .../config/OAuth2ResourceServerConfig.java | 2 - .../web/controller/BarController.java | 4 +- .../OAuth2AuthorizationServerConfig.java | 2 +- .../spring-security-oauth-ui-password/pom.xml | 40 +++++++++++++ .../baeldung/live/AuthorizationLiveTest.java | 57 +++++++++++++++++++ 6 files changed, 116 insertions(+), 5 deletions(-) create mode 100644 spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/MethodSecurityConfig.java create mode 100644 spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/MethodSecurityConfig.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/MethodSecurityConfig.java new file mode 100644 index 0000000000..c0a7f86207 --- /dev/null +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/MethodSecurityConfig.java @@ -0,0 +1,16 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; +import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler; + +@Configuration +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { + @Override + protected MethodSecurityExpressionHandler createExpressionHandler() { + return new OAuth2MethodSecurityExpressionHandler(); + } +} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java index 52bfeb4233..c2db6748f1 100644 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java @@ -9,7 +9,6 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.http.HttpMethod; import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @@ -20,7 +19,6 @@ import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; @Configuration @PropertySource({ "classpath:persistence.properties" }) @EnableResourceServer -@EnableGlobalMethodSecurity(prePostEnabled = true) public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { @Autowired private Environment env; diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java index a716635f6d..1f42f9dafd 100644 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java @@ -21,7 +21,7 @@ public class BarController { } // API - read - // @PreAuthorize("#oauth2.hasScope('read')") + // @PreAuthorize("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')") @RequestMapping(method = RequestMethod.GET, value = "/bars/{id}") @ResponseBody public Bar findById(@PathVariable final long id) { @@ -29,7 +29,7 @@ public class BarController { } // API - write - // @PreAuthorize("#oauth2.hasScope('write')") + // @PreAuthorize("#oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") @RequestMapping(method = RequestMethod.POST, value = "/bars") @ResponseStatus(HttpStatus.CREATED) @ResponseBody diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java index a0f8baa4bc..caae7760d3 100644 --- a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java +++ b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java @@ -55,7 +55,7 @@ public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigur .withClient("clientIdPassword") .secret("secret") .authorizedGrantTypes("password","authorization_code", "refresh_token") - .scopes("read"); + .scopes("read","write"); // @formatter:on } diff --git a/spring-security-oauth/spring-security-oauth-ui-password/pom.xml b/spring-security-oauth/spring-security-oauth-ui-password/pom.xml index a2bf3d07bb..4a42081f78 100644 --- a/spring-security-oauth/spring-security-oauth-ui-password/pom.xml +++ b/spring-security-oauth/spring-security-oauth-ui-password/pom.xml @@ -22,8 +22,48 @@ org.springframework.boot spring-boot-starter-thymeleaf + + + + + + org.springframework + spring-test + test + + + + junit + junit + test + + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + + com.jayway.restassured + rest-assured + ${rest-assured.version} + test + + + commons-logging + commons-logging + + + + spring-security-oauth-ui-password diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java b/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java new file mode 100644 index 0000000000..456245daff --- /dev/null +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java @@ -0,0 +1,57 @@ +package org.baeldung.live; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +import com.jayway.restassured.RestAssured; +import com.jayway.restassured.response.Response; + +public class AuthorizationLiveTest { + + private String obtainAccessToken(String username, String password) { + final Map params = new HashMap(); + params.put("grant_type", "password"); + params.put("client_id", "clientIdPassword"); + params.put("username", username); + params.put("password", password); + final Response response = RestAssured.given().auth().preemptive().basic("clientIdPassword", "secret").and().with().params(params).when().post("http://localhost:8081/spring-security-oauth-server/oauth/token"); + return response.jsonPath().getString("access_token"); + } + + @Test + public void givenUser_whenAccessFoosResource_thenOk() { + final String accessToken = obtainAccessToken("john", "123"); + final Response response = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); + assertEquals(200, response.getStatusCode()); + assertNotNull(response.jsonPath().get("name")); + } + + @Test + public void givenUser_whenAccessBarssResource_thenUnauthorized() { + final String accessToken = obtainAccessToken("john", "123"); + final Response response = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); + assertEquals(403, response.getStatusCode()); + } + + @Test + public void givenAdmin_whenAccessFoosResource_thenOk() { + final String accessToken = obtainAccessToken("tom", "111"); + final Response response = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); + assertEquals(200, response.getStatusCode()); + assertNotNull(response.jsonPath().get("name")); + } + + @Test + public void givenAdmin_whenAccessBarssResource_thenOk() { + final String accessToken = obtainAccessToken("tom", "111"); + final Response response = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); + assertEquals(200, response.getStatusCode()); + assertNotNull(response.jsonPath().get("name")); + } + +} From 04f794a255506f6f2ef0018f6957cbee15889eae Mon Sep 17 00:00:00 2001 From: joetaras Date: Sun, 21 Feb 2016 20:03:37 +0100 Subject: [PATCH 022/121] zip and unzip --- .../java/com/baeldung/unzip/UnzipFile.java | 31 +++++++++++++++++++ .../main/java/com/baeldung/zip/ZipFile.java | 29 +++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java create mode 100644 core-java-8/src/main/java/com/baeldung/zip/ZipFile.java diff --git a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java new file mode 100644 index 0000000000..d0b4274731 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java @@ -0,0 +1,31 @@ +package com.baeldung.unzip; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class UnzipFile { + public static void main(String[] args) throws FileNotFoundException, IOException { + String fileZip = "/opt/zipped/cities.zip"; + byte[] buffer = new byte[1024]; + ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip)); + ZipEntry zipEntry = zis.getNextEntry(); + while(zipEntry != null){ + String fileName = zipEntry.getName(); + File newFile = new File("/opt/unzipped/" + fileName); + FileOutputStream fos = new FileOutputStream(newFile); + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + fos.close(); + zipEntry = zis.getNextEntry(); + } + zis.closeEntry(); + zis.close(); + } +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java new file mode 100644 index 0000000000..dccd3f2347 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java @@ -0,0 +1,29 @@ +package com.baeldung.zip; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ZipFile { + public static void main(String[] args) throws FileNotFoundException, IOException { + String sourceFile = "/opt/photos/photo.png"; + FileOutputStream fos = new FileOutputStream("/opt/zipped/cities.zip"); + ZipOutputStream zipOut = new ZipOutputStream(fos); + File fileToZip = new File(sourceFile); + FileInputStream fis = new FileInputStream(fileToZip); + ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); + zipOut.putNextEntry(zipEntry); + byte[] bytes = new byte[1024]; + int length; + while((length = fis.read(bytes)) >= 0) { + zipOut.write(bytes, 0, length); + } + zipOut.close(); + fis.close(); + fos.close(); + } +} \ No newline at end of file From 87392e16b6dfbe2a16a4733a42e1611c7a0c5172 Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 23 Feb 2016 21:44:57 +0200 Subject: [PATCH 023/121] modify oauth scopes --- .../config/OAuth2ResourceServerConfig.java | 12 +-- .../web/controller/BarController.java | 4 +- .../web/controller/BazController.java | 41 ++++++++++ .../web/controller/FooController.java | 4 +- .../main/java/org/baeldung/web/dto/Baz.java | 36 +++++++++ .../OAuth2AuthorizationServerConfig.java | 12 ++- .../src/main/resources/templates/header.html | 22 +++++- .../src/main/resources/templates/index.html | 25 ++++++- .../src/main/resources/templates/header.html | 4 +- .../baeldung/live/AuthorizationLiveTest.java | 75 +++++++++++++------ 10 files changed, 197 insertions(+), 38 deletions(-) create mode 100644 spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BazController.java create mode 100644 spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Baz.java diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java index c2db6748f1..8fe4cda6a1 100644 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java @@ -29,13 +29,15 @@ public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter http .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() - .requestMatchers().antMatchers("/foos/**","/bars/**") + .requestMatchers().antMatchers("/foos/**","/bars/**","/bazes/**") .and() .authorizeRequests() - .antMatchers(HttpMethod.GET,"/foos/**").access("#oauth2.hasScope('read')") - .antMatchers(HttpMethod.POST,"/foos/**").access("#oauth2.hasScope('write')") - .antMatchers(HttpMethod.GET,"/bars/**").access("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')") - .antMatchers(HttpMethod.POST,"/bars/**").access("#oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") + .antMatchers(HttpMethod.GET,"/foos/**").access("#oauth2.hasScope('foo') and #oauth2.hasScope('read')") + .antMatchers(HttpMethod.POST,"/foos/**").access("#oauth2.hasScope('foo') and #oauth2.hasScope('write')") + .antMatchers(HttpMethod.GET,"/bars/**").access("#oauth2.hasScope('bar') and #oauth2.hasScope('read')") + .antMatchers(HttpMethod.POST,"/bars/**").access("#oauth2.hasScope('bar') and #oauth2.hasScope('write')") + .antMatchers(HttpMethod.GET,"/bazes/**").access("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')") + .antMatchers(HttpMethod.POST,"/bazes/**").access("#oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") ; // @formatter:on } diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java index 1f42f9dafd..938cf18129 100644 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java @@ -21,7 +21,7 @@ public class BarController { } // API - read - // @PreAuthorize("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')") + // @PreAuthorize("#oauth2.hasScope('bar') and #oauth2.hasScope('read')") @RequestMapping(method = RequestMethod.GET, value = "/bars/{id}") @ResponseBody public Bar findById(@PathVariable final long id) { @@ -29,7 +29,7 @@ public class BarController { } // API - write - // @PreAuthorize("#oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") + // @PreAuthorize("#oauth2.hasScope('bar') and #oauth2.hasScope('write')") @RequestMapping(method = RequestMethod.POST, value = "/bars") @ResponseStatus(HttpStatus.CREATED) @ResponseBody diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BazController.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BazController.java new file mode 100644 index 0000000000..880f41de07 --- /dev/null +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BazController.java @@ -0,0 +1,41 @@ +package org.baeldung.web.controller; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; + +import org.baeldung.web.dto.Baz; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +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.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +@Controller +public class BazController { + + public BazController() { + super(); + } + + // API - read + // @PreAuthorize("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')") + @RequestMapping(method = RequestMethod.GET, value = "/bazes/{id}") + @ResponseBody + public Baz findById(@PathVariable final long id) { + return new Baz(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); + } + + // API - write + // @PreAuthorize("#oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") + @RequestMapping(method = RequestMethod.POST, value = "/bazes") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Baz create(@RequestBody final Baz baz) { + baz.setId(Long.parseLong(randomNumeric(2))); + return baz; + } + +} diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/FooController.java index a1275670f0..d9ef1baa31 100644 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/FooController.java @@ -21,7 +21,7 @@ public class FooController { } // API - read - // @PreAuthorize("#oauth2.hasScope('read')") + // @PreAuthorize("#oauth2.hasScope('foo') and #oauth2.hasScope('read')") @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { @@ -29,7 +29,7 @@ public class FooController { } // API - write - // @PreAuthorize("#oauth2.hasScope('write')") + // @PreAuthorize("#oauth2.hasScope('foo') and #oauth2.hasScope('write')") @RequestMapping(method = RequestMethod.POST, value = "/foos") @ResponseStatus(HttpStatus.CREATED) @ResponseBody diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Baz.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Baz.java new file mode 100644 index 0000000000..69a6bf2e6a --- /dev/null +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Baz.java @@ -0,0 +1,36 @@ +package org.baeldung.web.dto; + +public class Baz { + private long id; + private String name; + + public Baz() { + super(); + } + + public Baz(final long id, final String name) { + super(); + + this.id = id; + this.name = name; + } + + // + + 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; + } + +} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java index caae7760d3..c7c90d177a 100644 --- a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java +++ b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java @@ -49,13 +49,19 @@ public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigur clients.jdbc(dataSource()) .withClient("sampleClientId") .authorizedGrantTypes("implicit") - .scopes("read","write") + .scopes("read","write","foo","bar") .autoApprove(false) .and() - .withClient("clientIdPassword") + .withClient("fooClientIdPassword") .secret("secret") .authorizedGrantTypes("password","authorization_code", "refresh_token") - .scopes("read","write"); + .scopes("foo","read","write") + .and() + .withClient("barClientIdPassword") + .secret("secret") + .authorizedGrantTypes("password","authorization_code", "refresh_token") + .scopes("bar","read","write") + ; // @formatter:on } diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html index 8cd7be67c3..d3cf521c0a 100644 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html +++ b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html @@ -13,7 +13,7 @@ site="http://localhost:8081/spring-security-oauth-server" client-id="sampleClientId" redirect-uri="http://localhost:8081/spring-security-oauth-ui-implicit/" - scope="read write" + scope="read write foo bar" template="oauthTemp"> @@ -94,6 +94,26 @@ app.controller('mainCtrl', function($scope,$resource,$http,$rootScope) { }); } + // baz + $scope.baz = {id:0 , name:"sample baz"}; + $scope.bazes = $resource("http://localhost:8081/spring-security-oauth-resource/bazes/:bazId",{bazId:'@id'}); + + $scope.getBaz = function(){ + $scope.baz = $scope.bazes.get({bazId:$scope.baz.id}); + } + + $scope.createBaz = function(){ + if($scope.baz.name.length==0) + { + $rootScope.message = "Baz name can not be empty"; + return; + } + $scope.baz.id = null; + $scope.baz = $scope.bazes.save($scope.baz, function(){ + $rootScope.message = "Baz Created Successfully"; + }); + } + }); /*]]>*/ diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html index c50781caf1..0b4c7563ce 100755 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html +++ b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html @@ -50,8 +50,31 @@ Get Bar Create Bar - +
+
+
+
+
+

Baz Details

+
+
+ + +
+ +
+ + +
+ + +
+ + \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html index 0bfe086bf1..cafba4eb65 100644 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html @@ -28,8 +28,8 @@ app.controller('mainCtrl', function($scope,$resource,$http,$httpParamSerializer, $scope.foo = $scope.foos.get({fooId:$scope.foo.id}); } - $scope.data = {grant_type:"password", username: "", password: "", client_id: "clientIdPassword"}; - $scope.encoded = btoa("clientIdPassword:secret"); + $scope.data = {grant_type:"password", username: "", password: "", client_id: "fooClientIdPassword"}; + $scope.encoded = btoa("fooClientIdPassword:secret"); var isLoginPage = window.location.href.indexOf("login") != -1; if(isLoginPage){ diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java b/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java index 456245daff..5827be548b 100644 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java @@ -13,45 +13,76 @@ import com.jayway.restassured.response.Response; public class AuthorizationLiveTest { - private String obtainAccessToken(String username, String password) { + private String obtainAccessToken(String clientId, String username, String password) { final Map params = new HashMap(); params.put("grant_type", "password"); - params.put("client_id", "clientIdPassword"); + params.put("client_id", clientId); params.put("username", username); params.put("password", password); - final Response response = RestAssured.given().auth().preemptive().basic("clientIdPassword", "secret").and().with().params(params).when().post("http://localhost:8081/spring-security-oauth-server/oauth/token"); + final Response response = RestAssured.given().auth().preemptive().basic(clientId, "secret").and().with().params(params).when().post("http://localhost:8081/spring-security-oauth-server/oauth/token"); return response.jsonPath().getString("access_token"); } @Test - public void givenUser_whenAccessFoosResource_thenOk() { - final String accessToken = obtainAccessToken("john", "123"); - final Response response = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); - assertEquals(200, response.getStatusCode()); - assertNotNull(response.jsonPath().get("name")); + public void givenUser_whenUseFooClient_thenOkForFooResourceOnly() { + final String accessToken = obtainAccessToken("fooClientIdPassword", "john", "123"); + + final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); + assertEquals(200, fooResponse.getStatusCode()); + assertNotNull(fooResponse.jsonPath().get("name")); + + final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); + assertEquals(403, barResponse.getStatusCode()); + + final Response bazResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bazes/1"); + assertEquals(403, bazResponse.getStatusCode()); } @Test - public void givenUser_whenAccessBarssResource_thenUnauthorized() { - final String accessToken = obtainAccessToken("john", "123"); - final Response response = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); - assertEquals(403, response.getStatusCode()); + public void givenUser_whenUseBarClient_thenOkForBarResourceOnly() { + final String accessToken = obtainAccessToken("barClientIdPassword", "john", "123"); + + final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); + assertEquals(200, barResponse.getStatusCode()); + assertNotNull(barResponse.jsonPath().get("name")); + + final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); + assertEquals(403, fooResponse.getStatusCode()); + + final Response bazResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bazes/1"); + assertEquals(403, bazResponse.getStatusCode()); } @Test - public void givenAdmin_whenAccessFoosResource_thenOk() { - final String accessToken = obtainAccessToken("tom", "111"); - final Response response = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); - assertEquals(200, response.getStatusCode()); - assertNotNull(response.jsonPath().get("name")); + public void givenAdmin_whenUseFooClient_thenOkForFooAndBazResourceOnly() { + final String accessToken = obtainAccessToken("fooClientIdPassword", "tom", "111"); + + final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); + assertEquals(200, fooResponse.getStatusCode()); + assertNotNull(fooResponse.jsonPath().get("name")); + + final Response bazResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bazes/1"); + assertEquals(200, bazResponse.getStatusCode()); + assertNotNull(bazResponse.jsonPath().get("name")); + + final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); + assertEquals(403, barResponse.getStatusCode()); } @Test - public void givenAdmin_whenAccessBarssResource_thenOk() { - final String accessToken = obtainAccessToken("tom", "111"); - final Response response = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); - assertEquals(200, response.getStatusCode()); - assertNotNull(response.jsonPath().get("name")); + public void givenAdmin_whenUseBarClient_thenOkForBarAndBazResourceOnly() { + final String accessToken = obtainAccessToken("barClientIdPassword", "tom", "111"); + + final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); + assertEquals(200, barResponse.getStatusCode()); + assertNotNull(barResponse.jsonPath().get("name")); + + final Response bazResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bazes/1"); + assertEquals(200, bazResponse.getStatusCode()); + assertNotNull(bazResponse.jsonPath().get("name")); + + final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); + assertEquals(403, fooResponse.getStatusCode()); } } From 595c1c2b1128de279db5f0ebd2ac5713e225139b Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 24 Feb 2016 00:06:52 +0200 Subject: [PATCH 024/121] minor cleanup --- .../baeldung/config/ResourceServerWebConfig.java | 2 +- .../spring-security-oauth-server/.springBeans | 16 ++++++++++++++++ ....java => AuthorizationServerApplication.java} | 4 ++-- ...ecurityConfig.java => WebSecurityConfig.java} | 2 +- 4 files changed, 20 insertions(+), 4 deletions(-) create mode 100644 spring-security-oauth/spring-security-oauth-server/.springBeans rename spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/{ServerApplication.java => AuthorizationServerApplication.java} (65%) rename spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/{ServerSecurityConfig.java => WebSecurityConfig.java} (94%) diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java index c040c8ac42..81b2d242ac 100644 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java @@ -9,5 +9,5 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @EnableWebMvc @ComponentScan({ "org.baeldung.web.controller" }) public class ResourceServerWebConfig extends WebMvcConfigurerAdapter { - + // } diff --git a/spring-security-oauth/spring-security-oauth-server/.springBeans b/spring-security-oauth/spring-security-oauth-server/.springBeans new file mode 100644 index 0000000000..18656ebe2e --- /dev/null +++ b/spring-security-oauth/spring-security-oauth-server/.springBeans @@ -0,0 +1,16 @@ + + + 1 + + + + + + + java:org.baeldung.config.AuthorizationServerApplication + + + + + + diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerApplication.java b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java similarity index 65% rename from spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerApplication.java rename to spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java index 4b1ff2c7ad..73b8fc1976 100644 --- a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerApplication.java +++ b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java @@ -5,10 +5,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.web.SpringBootServletInitializer; @SpringBootApplication -public class ServerApplication extends SpringBootServletInitializer { +public class AuthorizationServerApplication extends SpringBootServletInitializer { public static void main(String[] args) { - SpringApplication.run(ServerApplication.class, args); + SpringApplication.run(AuthorizationServerApplication.class, args); } } \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerSecurityConfig.java b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/WebSecurityConfig.java similarity index 94% rename from spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerSecurityConfig.java rename to spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/WebSecurityConfig.java index 46870f3fc3..f8218a0c03 100644 --- a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/ServerSecurityConfig.java +++ b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/WebSecurityConfig.java @@ -8,7 +8,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration -public class ServerSecurityConfig extends WebSecurityConfigurerAdapter { +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { From 11461268feeb62bf76064ec60e681d826c0a0c14 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 24 Feb 2016 01:10:50 +0200 Subject: [PATCH 025/121] remove oauth extra resource --- .../config/OAuth2ResourceServerConfig.java | 6 +-- .../web/controller/BarController.java | 2 +- .../web/controller/BazController.java | 41 ---------------- .../main/java/org/baeldung/web/dto/Baz.java | 36 -------------- .../src/main/resources/templates/header.html | 19 -------- .../src/main/resources/templates/index.html | 22 --------- .../baeldung/live/AuthorizationLiveTest.java | 48 ++++++------------- 7 files changed, 18 insertions(+), 156 deletions(-) delete mode 100644 spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BazController.java delete mode 100644 spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Baz.java diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java index 8fe4cda6a1..7809278ad8 100644 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java @@ -29,15 +29,13 @@ public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter http .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() - .requestMatchers().antMatchers("/foos/**","/bars/**","/bazes/**") + .requestMatchers().antMatchers("/foos/**","/bars/**") .and() .authorizeRequests() .antMatchers(HttpMethod.GET,"/foos/**").access("#oauth2.hasScope('foo') and #oauth2.hasScope('read')") .antMatchers(HttpMethod.POST,"/foos/**").access("#oauth2.hasScope('foo') and #oauth2.hasScope('write')") .antMatchers(HttpMethod.GET,"/bars/**").access("#oauth2.hasScope('bar') and #oauth2.hasScope('read')") - .antMatchers(HttpMethod.POST,"/bars/**").access("#oauth2.hasScope('bar') and #oauth2.hasScope('write')") - .antMatchers(HttpMethod.GET,"/bazes/**").access("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')") - .antMatchers(HttpMethod.POST,"/bazes/**").access("#oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") + .antMatchers(HttpMethod.POST,"/bars/**").access("#oauth2.hasScope('bar') and #oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") ; // @formatter:on } diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java index 938cf18129..72163ff9ff 100644 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java +++ b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java @@ -29,7 +29,7 @@ public class BarController { } // API - write - // @PreAuthorize("#oauth2.hasScope('bar') and #oauth2.hasScope('write')") + // @PreAuthorize("#oauth2.hasScope('bar') and #oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") @RequestMapping(method = RequestMethod.POST, value = "/bars") @ResponseStatus(HttpStatus.CREATED) @ResponseBody diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BazController.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BazController.java deleted file mode 100644 index 880f41de07..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BazController.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.web.controller; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; - -import org.baeldung.web.dto.Baz; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -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.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; - -@Controller -public class BazController { - - public BazController() { - super(); - } - - // API - read - // @PreAuthorize("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')") - @RequestMapping(method = RequestMethod.GET, value = "/bazes/{id}") - @ResponseBody - public Baz findById(@PathVariable final long id) { - return new Baz(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); - } - - // API - write - // @PreAuthorize("#oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") - @RequestMapping(method = RequestMethod.POST, value = "/bazes") - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Baz create(@RequestBody final Baz baz) { - baz.setId(Long.parseLong(randomNumeric(2))); - return baz; - } - -} diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Baz.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Baz.java deleted file mode 100644 index 69a6bf2e6a..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Baz.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.web.dto; - -public class Baz { - private long id; - private String name; - - public Baz() { - super(); - } - - public Baz(final long id, final String name) { - super(); - - this.id = id; - this.name = name; - } - - // - - 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; - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html index d3cf521c0a..aa891bc289 100644 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html +++ b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html @@ -94,25 +94,6 @@ app.controller('mainCtrl', function($scope,$resource,$http,$rootScope) { }); } - // baz - $scope.baz = {id:0 , name:"sample baz"}; - $scope.bazes = $resource("http://localhost:8081/spring-security-oauth-resource/bazes/:bazId",{bazId:'@id'}); - - $scope.getBaz = function(){ - $scope.baz = $scope.bazes.get({bazId:$scope.baz.id}); - } - - $scope.createBaz = function(){ - if($scope.baz.name.length==0) - { - $rootScope.message = "Baz name can not be empty"; - return; - } - $scope.baz.id = null; - $scope.baz = $scope.bazes.save($scope.baz, function(){ - $rootScope.message = "Baz Created Successfully"; - }); - } }); /*]]>*/ diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html index 0b4c7563ce..2996af04f0 100755 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html +++ b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html @@ -51,28 +51,6 @@ Create Bar -
-
-
-
-
-

Baz Details

-
-
- - -
- -
- - -
- - -
diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java b/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java index 5827be548b..e5e9d8428f 100644 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java @@ -7,6 +7,7 @@ import java.util.HashMap; import java.util.Map; import org.junit.Test; +import org.springframework.http.MediaType; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; @@ -33,56 +34,37 @@ public class AuthorizationLiveTest { final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); assertEquals(403, barResponse.getStatusCode()); - - final Response bazResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bazes/1"); - assertEquals(403, bazResponse.getStatusCode()); } @Test - public void givenUser_whenUseBarClient_thenOkForBarResourceOnly() { + public void givenUser_whenUseBarClient_thenOkForBarResourceReadOnly() { final String accessToken = obtainAccessToken("barClientIdPassword", "john", "123"); - final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); - assertEquals(200, barResponse.getStatusCode()); - assertNotNull(barResponse.jsonPath().get("name")); - final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); assertEquals(403, fooResponse.getStatusCode()); - final Response bazResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bazes/1"); - assertEquals(403, bazResponse.getStatusCode()); + final Response barReadResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); + assertEquals(200, barReadResponse.getStatusCode()); + assertNotNull(barReadResponse.jsonPath().get("name")); + + final Response barWritResponse = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).header("Authorization", "Bearer " + accessToken).body("{\"id\":1,\"name\":\"MyBar\"}").post("http://localhost:8081/spring-security-oauth-resource/bars"); + assertEquals(403, barWritResponse.getStatusCode()); } @Test - public void givenAdmin_whenUseFooClient_thenOkForFooAndBazResourceOnly() { - final String accessToken = obtainAccessToken("fooClientIdPassword", "tom", "111"); - - final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); - assertEquals(200, fooResponse.getStatusCode()); - assertNotNull(fooResponse.jsonPath().get("name")); - - final Response bazResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bazes/1"); - assertEquals(200, bazResponse.getStatusCode()); - assertNotNull(bazResponse.jsonPath().get("name")); - - final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); - assertEquals(403, barResponse.getStatusCode()); - } - - @Test - public void givenAdmin_whenUseBarClient_thenOkForBarAndBazResourceOnly() { + public void givenAdmin_whenUseBarClient_thenOkForBarResourceReadWrite() { final String accessToken = obtainAccessToken("barClientIdPassword", "tom", "111"); + final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); + assertEquals(403, fooResponse.getStatusCode()); + final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); assertEquals(200, barResponse.getStatusCode()); assertNotNull(barResponse.jsonPath().get("name")); - final Response bazResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bazes/1"); - assertEquals(200, bazResponse.getStatusCode()); - assertNotNull(bazResponse.jsonPath().get("name")); - - final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); - assertEquals(403, fooResponse.getStatusCode()); + final Response barWritResponse = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).header("Authorization", "Bearer " + accessToken).body("{\"id\":1,\"name\":\"MyBar\"}").post("http://localhost:8081/spring-security-oauth-resource/bars"); + assertEquals(201, barWritResponse.getStatusCode()); + assertEquals("MyBar", barWritResponse.jsonPath().get("name")); } } From 3b5c46bbbf9b0c99344ff0973807ebc9d406c8ab Mon Sep 17 00:00:00 2001 From: "giuseppe.bueti" Date: Fri, 26 Feb 2016 16:43:11 +0100 Subject: [PATCH 026/121] JPA Stored Procedure --- persistence-jpa/pom.xml | 81 +++++++++++++++++++ .../main/java/com/baeldung/jpa/model/Car.java | 59 ++++++++++++++ .../baeldung/jpa/model/QueryParameter.java | 27 +++++++ .../main/resources/META-INF/persistence.xml | 20 +++++ .../config/database/create_database.sql | 34 ++++++++ .../resources/config/database/insert_cars.sql | 4 + .../storedprocedure/StoredProcedureTest.java | 66 +++++++++++++++ .../src/test/resources/persistence.xml | 21 +++++ 8 files changed, 312 insertions(+) create mode 100644 persistence-jpa/pom.xml create mode 100644 persistence-jpa/src/main/java/com/baeldung/jpa/model/Car.java create mode 100644 persistence-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java create mode 100644 persistence-jpa/src/main/resources/META-INF/persistence.xml create mode 100644 persistence-jpa/src/main/resources/config/database/create_database.sql create mode 100644 persistence-jpa/src/main/resources/config/database/insert_cars.sql create mode 100644 persistence-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java create mode 100644 persistence-jpa/src/test/resources/persistence.xml diff --git a/persistence-jpa/pom.xml b/persistence-jpa/pom.xml new file mode 100644 index 0000000000..66f0264f2c --- /dev/null +++ b/persistence-jpa/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + + com.baeldung + jpa-storedprocedure + 1.0 + jar + + + 7.0 + 11.2.0.4 + 5.1.0.Final + + + + JpaStoredProcedure + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + maven-assembly-plugin + + + + jar-with-dependencies + + + + + + + + + + + + javax + javaee-api + ${jee.version} + provided + + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + + + + + com.oracle + ojdbc6 + ${oracle.version} + + + + + + junit + junit + 4.4 + + + + commons-io + commons-io + 2.4 + + + + + \ No newline at end of file diff --git a/persistence-jpa/src/main/java/com/baeldung/jpa/model/Car.java b/persistence-jpa/src/main/java/com/baeldung/jpa/model/Car.java new file mode 100644 index 0000000000..d57cff200e --- /dev/null +++ b/persistence-jpa/src/main/java/com/baeldung/jpa/model/Car.java @@ -0,0 +1,59 @@ +package com.baeldung.jpa.model; + +import javax.persistence.*; + +/** + * Created by Giuseppe Bueti on 22/02/2016. + */ + +@Entity +@Table(name = "CAR") +@NamedStoredProcedureQueries({ + @NamedStoredProcedureQuery(name = "findByModelProcedure", procedureName = "FIND_CAR_BY_MODEL", resultClasses = { Car.class }, parameters = { @StoredProcedureParameter(name = "p_model", type = String.class, mode = ParameterMode.IN), + @StoredProcedureParameter(name = "data", type = Car.class, mode = ParameterMode.REF_CURSOR) }), + @NamedStoredProcedureQuery(name = "findByYearProcedure", procedureName = "FIND_CAR_BY_YEAR", resultClasses = { Car.class }, parameters = { @StoredProcedureParameter(name = "p_year", type = Integer.class, mode = ParameterMode.IN), + @StoredProcedureParameter(name = "data", type = Car.class, mode = ParameterMode.REF_CURSOR) }) }) +public class Car { + + private long id; + private String model; + private Integer year; + + public Car(String model, Integer year) { + this.model = model; + this.year = year; + } + + public Car() { + } + + @Id + @SequenceGenerator(name = "CarIdSequence", sequenceName = "SEQ_CAR_ID", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CarIdSequence") + @Column(name = "ID", unique = true, nullable = false, scale = 0) + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + @Column(name = "MODEL") + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + @Column(name = "YEAR") + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } +} diff --git a/persistence-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java b/persistence-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java new file mode 100644 index 0000000000..326886842d --- /dev/null +++ b/persistence-jpa/src/main/java/com/baeldung/jpa/model/QueryParameter.java @@ -0,0 +1,27 @@ +package com.baeldung.jpa.model; + +import java.util.HashMap; +import java.util.Map; + +public class QueryParameter { + + private Map parameters = null; + + private QueryParameter(String name, Object value) { + this.parameters = new HashMap<>(); + this.parameters.put(name, value); + } + + public static QueryParameter with(String name, Object value) { + return new QueryParameter(name, value); + } + + public QueryParameter and(String name, Object value) { + this.parameters.put(name, value); + return this; + } + + public Map parameters() { + return this.parameters; + } +} \ No newline at end of file diff --git a/persistence-jpa/src/main/resources/META-INF/persistence.xml b/persistence-jpa/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..9c5adbac2a --- /dev/null +++ b/persistence-jpa/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,20 @@ + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.model.Car + + + + + + + + + + \ No newline at end of file diff --git a/persistence-jpa/src/main/resources/config/database/create_database.sql b/persistence-jpa/src/main/resources/config/database/create_database.sql new file mode 100644 index 0000000000..d84007b74d --- /dev/null +++ b/persistence-jpa/src/main/resources/config/database/create_database.sql @@ -0,0 +1,34 @@ +CREATE TABLESPACE JPA DATAFILE 'C:\oraclexe\app\oracle\oradata\XE\JPA.DBF' SIZE 100M AUTOEXTEND ON MAXSIZE 2048M; + +--DROP USER JPA CASCADE; +CREATE USER JPA IDENTIFIED BY JPA DEFAULT TABLESPACE JPA; +ALTER USER JPA QUOTA UNLIMITED ON "JPA" ACCOUNT UNLOCK; + +GRANT CREATE SESSION TO "JPA"; +GRANT ALTER SESSION TO "JPA"; +GRANT CREATE TABLE TO "JPA"; +GRANT CREATE TRIGGER TO "JPA"; +GRANT CREATE VIEW TO "JPA"; +GRANT CREATE DIMENSION TO "JPA"; +GRANT CREATE CLUSTER TO "JPA"; +GRANT CREATE INDEXTYPE TO "JPA"; +GRANT CREATE ROLE TO "JPA"; +GRANT CREATE SEQUENCE TO "JPA"; +GRANT CREATE TYPE TO "JPA"; +GRANT CREATE MATERIALIZED VIEW TO "JPA"; +GRANT CREATE PROCEDURE TO "JPA"; +GRANT CREATE SYNONYM TO "JPA"; + +CREATE SEQUENCE SEQ_CAR_ID INCREMENT BY 1 START WITH 1 MAXVALUE 999999999999999 MINVALUE 1; + +CREATE TABLE CAR +( + ID NUMBER NOT NULL, + MODEL VARCHAR2(50) NOT NULL, + YEAR NUMBER(4) NOT NULL +); + +ALTER TABLE CAR ADD CONSTRAINT CAR_PK PRIMARY KEY ( ID ); + +commit; + diff --git a/persistence-jpa/src/main/resources/config/database/insert_cars.sql b/persistence-jpa/src/main/resources/config/database/insert_cars.sql new file mode 100644 index 0000000000..5fef151c70 --- /dev/null +++ b/persistence-jpa/src/main/resources/config/database/insert_cars.sql @@ -0,0 +1,4 @@ +INSERT INTO CAR (ID, MODEL, YEAR) VALUES ('123456', 'Camaro', '2012'); +INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('12112', 'Fiat Panda', '2000') +INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('111000', 'Fiat Punto', '2007') +INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('3382', 'Citroen C3', '2009') diff --git a/persistence-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java b/persistence-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java new file mode 100644 index 0000000000..61d4aca85e --- /dev/null +++ b/persistence-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java @@ -0,0 +1,66 @@ +package com.baeldung.jpa.storedprocedure; + +import com.baeldung.jpa.model.Car; +import org.junit.*; + +import javax.persistence.*; + +/** + * Created by Giuseppe Bueti on 23/02/2016. + */ +public class StoredProcedureTest { + + private static EntityManagerFactory factory = null; + private static EntityManager entityManager = null; + + @BeforeClass + public static void init() { + factory = Persistence.createEntityManagerFactory("jpa-db"); + entityManager = factory.createEntityManager(); + } + + @Before + public void setup() { + } + + @Test + public void createCarTest() { + EntityTransaction transaction = entityManager.getTransaction(); + try { + transaction.begin(); + Car car = new Car("Ford Mustang", 2015); + entityManager.persist(car); + transaction.commit(); + } catch (Exception e) { + System.out.println(e.getCause()); + if (transaction.isActive()) { + transaction.rollback(); + } + } + } + + @Test + public void findCarsByYear() { + final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure"); + StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015); + storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); + } + + @Test + public void findCarsByModel() { + final StoredProcedureQuery findByModelProcedure = entityManager.createNamedStoredProcedureQuery("findByModelProcedure"); + StoredProcedureQuery storedProcedure = findByModelProcedure.setParameter("p_model", "Camaro"); + storedProcedure.getResultList().forEach(c -> Assert.assertEquals("Camaro", ((Car) c).getModel())); + } + + @AfterClass + public static void destroy() { + + if (entityManager != null) { + entityManager.close(); + } + if (factory != null) { + factory.close(); + } + } +} diff --git a/persistence-jpa/src/test/resources/persistence.xml b/persistence-jpa/src/test/resources/persistence.xml new file mode 100644 index 0000000000..9a5d8acc36 --- /dev/null +++ b/persistence-jpa/src/test/resources/persistence.xml @@ -0,0 +1,21 @@ + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.model.Car + + + + + + + + + + + From f8b8a5d7bb8e08bb1dd5c259bae7358cfc585f13 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 27 Feb 2016 20:37:56 +0200 Subject: [PATCH 027/121] oauth refresh token --- .../spring-security-oauth-ui-password/pom.xml | 8 +- .../baeldung/config/CustomPostZuulFilter.java | 70 +++++++++++++++++ .../baeldung/config/CustomPreZuulFilter.java | 52 +++++++++++++ .../org/baeldung/config/HomeController.java | 20 +++++ .../org/baeldung/config/UiApplication.java | 2 + .../src/main/resources/application.properties | 2 - .../src/main/resources/application.yml | 13 ++++ .../src/main/resources/templates/header.html | 77 +++++++++++-------- .../src/main/resources/templates/login.html | 5 +- spring-zuul/spring-zuul-ui/.project | 10 +-- 10 files changed, 216 insertions(+), 43 deletions(-) create mode 100644 spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPostZuulFilter.java create mode 100644 spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPreZuulFilter.java create mode 100644 spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/HomeController.java delete mode 100644 spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.properties create mode 100644 spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.yml diff --git a/spring-security-oauth/spring-security-oauth-ui-password/pom.xml b/spring-security-oauth/spring-security-oauth-ui-password/pom.xml index 4a42081f78..e8b2aa3d0d 100644 --- a/spring-security-oauth/spring-security-oauth-ui-password/pom.xml +++ b/spring-security-oauth/spring-security-oauth-ui-password/pom.xml @@ -17,11 +17,17 @@ org.springframework.boot spring-boot-starter-web - + org.springframework.boot spring-boot-starter-thymeleaf + + + org.springframework.cloud + spring-cloud-starter-zuul + 1.0.4.RELEASE + diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPostZuulFilter.java b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPostZuulFilter.java new file mode 100644 index 0000000000..319bd2f783 --- /dev/null +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPostZuulFilter.java @@ -0,0 +1,70 @@ +package org.baeldung.config; + +import java.io.InputStream; + +import javax.servlet.http.Cookie; + +import org.apache.commons.io.IOUtils; +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.map.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.context.RequestContext; + +@Component +public class CustomPostZuulFilter extends ZuulFilter { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Override + public Object run() { + final RequestContext ctx = RequestContext.getCurrentContext(); + logger.info("in zuul filter " + ctx.getRequest().getRequestURI()); + if (ctx.getRequest().getRequestURI().contains("oauth/token")) { + + final ObjectMapper mapper = new ObjectMapper(); + JsonNode json; + try { + final InputStream is = ctx.getResponseDataStream(); + final String responseBody = IOUtils.toString(is, "UTF-8"); + + ctx.setResponseBody(responseBody); + + if (responseBody.contains("refresh_token")) { + json = mapper.readTree(responseBody); + final String refreshToken = json.get("refresh_token").getTextValue(); + final Cookie cookie = new Cookie("refreshToken", refreshToken); + cookie.setHttpOnly(true); + cookie.setPath(ctx.getRequest().getContextPath() + "/refreshToken"); + cookie.setMaxAge(2592000); // 30 days + ctx.getResponse().addCookie(cookie); + + logger.info("refresh token = " + refreshToken); + } + } catch (final Exception e) { + logger.error("Error occured in zuul post filter", e); + } + + } + return null; + } + + @Override + public boolean shouldFilter() { + return true; + } + + @Override + public int filterOrder() { + return 10; + } + + @Override + public String filterType() { + return "post"; + } + +} diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPreZuulFilter.java b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPreZuulFilter.java new file mode 100644 index 0000000000..e0e38b2030 --- /dev/null +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPreZuulFilter.java @@ -0,0 +1,52 @@ +package org.baeldung.config; + +import java.io.UnsupportedEncodingException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.crypto.codec.Base64; +import org.springframework.stereotype.Component; + +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.context.RequestContext; + +@Component +public class CustomPreZuulFilter extends ZuulFilter { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Override + public Object run() { + final RequestContext ctx = RequestContext.getCurrentContext(); + logger.info("in zuul filter " + ctx.getRequest().getRequestURI()); + if (ctx.getRequest().getRequestURI().contains("oauth/token")) { + byte[] encoded; + try { + encoded = Base64.encode("fooClientIdPassword:secret".getBytes("UTF-8")); + ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded)); + logger.info("pre filter"); + logger.info(ctx.getRequest().getHeader("Authorization")); + } catch (final UnsupportedEncodingException e) { + logger.error("Error occured in pre filter", e); + } + + } + return null; + } + + @Override + public boolean shouldFilter() { + return true; + } + + @Override + public int filterOrder() { + return 111110; + } + + @Override + public String filterType() { + return "pre"; + } + +} diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/HomeController.java b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/HomeController.java new file mode 100644 index 0000000000..a56407a58e --- /dev/null +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/HomeController.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseStatus; + +@Controller +public class HomeController { + + @RequestMapping(method = RequestMethod.GET, value = "/refreshToken") + @ResponseStatus(HttpStatus.OK) + public void getRefreshToken(@CookieValue(value = "refreshToken", defaultValue = "") String cookie, HttpServletResponse response) { + response.addHeader("refreshToken", cookie); + } +} diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiApplication.java index 8f491516aa..60c92d9eef 100644 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiApplication.java @@ -3,7 +3,9 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.cloud.netflix.zuul.EnableZuulProxy; +@EnableZuulProxy @SpringBootApplication public class UiApplication extends SpringBootServletInitializer { diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.properties b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.properties deleted file mode 100644 index e76a587680..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -server.contextPath=/spring-security-oauth-ui-password -server.port=8081 \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.yml b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.yml new file mode 100644 index 0000000000..9c9e9000e7 --- /dev/null +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.yml @@ -0,0 +1,13 @@ +server: + port: 8081 +zuul: + routes: + foos: + path: /foos/** + url: http://localhost:8081/spring-security-oauth-resource/foos + bars: + path: /bars/** + url: http://localhost:8081/spring-security-oauth-resource/bars + oauth: + path: /oauth/** + url: http://localhost:8081/spring-security-oauth-server/oauth diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html index cafba4eb65..92a771de12 100644 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html @@ -21,52 +21,63 @@ var app = angular.module('myApp', ["ngResource","ngRoute","ngCookies"]); app.controller('mainCtrl', function($scope,$resource,$http,$httpParamSerializer,$cookies) { - $scope.foo = {id:0 , name:"sample foo"}; - $scope.foos = $resource("http://localhost:8081/spring-security-oauth-resource/foos/:fooId",{fooId:'@id'}); + $scope.foo = {id:0 , name:"sample foo"}; + $scope.foos = $resource("foos/:fooId",{fooId:'@id'}); - $scope.getFoo = function(){ - $scope.foo = $scope.foos.get({fooId:$scope.foo.id}); - } - - $scope.data = {grant_type:"password", username: "", password: "", client_id: "fooClientIdPassword"}; - $scope.encoded = btoa("fooClientIdPassword:secret"); + $scope.getFoo = function(){ + $scope.foo = $scope.foos.get({fooId:$scope.foo.id}); + } + $scope.loginData = {grant_type:"password", username: "", password: "", client_id: "fooClientIdPassword"}; + $scope.refreshData = {grant_type:"refresh_token", refresh_token:""}; + var isLoginPage = window.location.href.indexOf("login") != -1; if(isLoginPage){ - if($cookies.get("access_token")){ + if($cookies.get("access_token")){ window.location.href = "index"; - }else{ - $http.defaults.headers.common.Authorization= 'Basic ' + $scope.encoded; } }else{ - if($cookies.get("access_token")){ - $http.defaults.headers.common.Authorization= 'Bearer ' + $cookies.get("access_token"); - }else{ - window.location.href = "login"; - } - + if($cookies.get("access_token")){ + $http.defaults.headers.common.Authorization= 'Bearer ' + $cookies.get("access_token"); + }else{ + refreshAccessToken(); + } } $scope.login = function() { - var req = { + $scope.obtainAccessToken($scope.loginData); + } + + function refreshAccessToken(){ + $http.get("refreshToken"). + success(function(data, status, headers, config) { + if(headers("refreshToken") && headers("refreshToken").length>0){ + $scope.refreshData.refresh_token = headers("refreshToken"); + $scope.obtainAccessToken($scope.refreshData); + }else{ + window.location.href = "login"; + } + }); + } + + $scope.obtainAccessToken = function(params){ + var req = { method: 'POST', - url: "http://localhost:8081/spring-security-oauth-server/oauth/token", - headers: { - "Authorization": "Basic " + $scope.encoded, - "Content-type": "application/x-www-form-urlencoded; charset=utf-8" - }, - data: $httpParamSerializer($scope.data) + url: "oauth/token", + headers: {"Content-type": "application/x-www-form-urlencoded; charset=utf-8"}, + data: $httpParamSerializer(params) } $http(req).then( - function(data){ - $http.defaults.headers.common.Authorization= 'Bearer ' + data.data.access_token; - $cookies.put("access_token", data.data.access_token); - window.location.href="index"; - },function(){ - console.log("error"); - }); - } - + function(data){ + $http.defaults.headers.common.Authorization= 'Bearer ' + data.data.access_token; + var expireDate = new Date (new Date().getTime() + (1000 * data.data.expires_in)); + $cookies.put("access_token", data.data.access_token, {'expires': expireDate}); + window.location.href="index"; + },function(){ + console.log("error"); + window.location.href = "login"; + }); + } }); /*]]>*/ diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/login.html b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/login.html index 4d105cec6c..e1e6e3e6e0 100755 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/login.html +++ b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/login.html @@ -15,16 +15,17 @@
- +
- +
Login +
diff --git a/spring-zuul/spring-zuul-ui/.project b/spring-zuul/spring-zuul-ui/.project index ec0f2cde81..d87aec6bec 100644 --- a/spring-zuul/spring-zuul-ui/.project +++ b/spring-zuul/spring-zuul-ui/.project @@ -20,11 +20,6 @@ - - org.eclipse.m2e.core.maven2Builder - - - org.springframework.ide.eclipse.core.springbuilder @@ -35,6 +30,11 @@ + + org.eclipse.m2e.core.maven2Builder + + + org.eclipse.jem.workbench.JavaEMFNature From 50fc18b7d2e67ce4fd51c13ecbc9dff7552897b0 Mon Sep 17 00:00:00 2001 From: sghosh Date: Sun, 28 Feb 2016 17:40:14 +0530 Subject: [PATCH 028/121] more queries using QueryDSL --- .../src/main/java/org/baeldung/dao/PersonDao.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/querydsl/src/main/java/org/baeldung/dao/PersonDao.java b/querydsl/src/main/java/org/baeldung/dao/PersonDao.java index cc193de44b..17be05bff8 100644 --- a/querydsl/src/main/java/org/baeldung/dao/PersonDao.java +++ b/querydsl/src/main/java/org/baeldung/dao/PersonDao.java @@ -2,11 +2,22 @@ package org.baeldung.dao; import org.baeldung.entity.Person; +import javax.persistence.Tuple; import java.util.List; +import java.util.Map; public interface PersonDao { public Person save(Person person); public List findPersonsByFirstnameQueryDSL(String firstname); + + public List findPersonsByFirstnameAndSurnameQueryDSL(String firstname, String surname); + + public List findPersonsByFirstnameInDescendingOrderQueryDSL(String firstname); + + public int findMaxAge(); + + public Map findMaxAgeByName(); + } \ No newline at end of file From 1ff8bc970dcd7bd3d0d1b94928e1f492c35fbb7f Mon Sep 17 00:00:00 2001 From: sghosh Date: Sun, 28 Feb 2016 18:04:44 +0530 Subject: [PATCH 029/121] more queries using QueryDSL --- .../java/org/baeldung/dao/PersonDaoImpl.java | 40 ++++++++++++++++ .../main/java/org/baeldung/entity/Person.java | 15 ++++++ .../java/org/baeldung/dao/PersonDaoTest.java | 46 +++++++++++++++++++ 3 files changed, 101 insertions(+) diff --git a/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java b/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java index 82ee4c16cd..209ff699af 100644 --- a/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java +++ b/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java @@ -1,13 +1,18 @@ package org.baeldung.dao; +import com.mysema.query.group.GroupBy; import com.mysema.query.jpa.impl.JPAQuery; +import com.mysema.query.jpa.impl.JPAQueryFactory; import org.baeldung.entity.Person; import org.baeldung.entity.QPerson; import org.springframework.stereotype.Repository; +import javax.inject.Provider; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; +import javax.persistence.Tuple; import java.util.List; +import java.util.Map; @Repository public class PersonDaoImpl implements PersonDao { @@ -20,6 +25,7 @@ public class PersonDaoImpl implements PersonDao { return person; } + @Override public List findPersonsByFirstnameQueryDSL(String firstname) { JPAQuery query = new JPAQuery(em); QPerson person = QPerson.person; @@ -27,4 +33,38 @@ public class PersonDaoImpl implements PersonDao { return query.from(person).where(person.firstname.eq(firstname)).list(person); } + @Override + public List findPersonsByFirstnameAndSurnameQueryDSL(String firstname, String surname) { + JPAQuery query = new JPAQuery(em); + QPerson person = QPerson.person; + + return query.from(person).where(person.firstname.eq(firstname).and( + person.surname.eq(surname))).list(person); + } + + @Override + public List findPersonsByFirstnameInDescendingOrderQueryDSL(String firstname) { + JPAQuery query = new JPAQuery(em); + QPerson person = QPerson.person; + + return query.from(person).where(person.firstname.eq(firstname)).orderBy( + person.surname.desc()).list(person); + } + + @Override + public int findMaxAge() { + JPAQuery query = new JPAQuery(em); + QPerson person = QPerson.person; + + return query.from(person).list(person.age.max()).get(0); + } + + @Override + public Map findMaxAgeByName() { + JPAQuery query = new JPAQuery(em); + QPerson person = QPerson.person; + + return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age))); + } + } \ No newline at end of file diff --git a/querydsl/src/main/java/org/baeldung/entity/Person.java b/querydsl/src/main/java/org/baeldung/entity/Person.java index d9b0a5a97d..056b2eb79c 100644 --- a/querydsl/src/main/java/org/baeldung/entity/Person.java +++ b/querydsl/src/main/java/org/baeldung/entity/Person.java @@ -15,6 +15,9 @@ public class Person { @Column private String surname; + @Column + private int age; + Person() { } @@ -23,6 +26,11 @@ public class Person { this.surname = surname; } + public Person(String firstname, String surname, int age) { + this(firstname, surname); + this.age = age; + } + public Long getId() { return id; } @@ -47,4 +55,11 @@ public class Person { this.surname = surname; } + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } } \ No newline at end of file diff --git a/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java b/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java index 29d4dd98e9..da3a95b7f8 100644 --- a/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java +++ b/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java @@ -10,6 +10,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; +import java.util.Map; + @ContextConfiguration("/test-context.xml") @RunWith(SpringJUnit4ClassRunner.class) @@ -30,4 +32,48 @@ public class PersonDaoTest { Person personFromDb = personDao.findPersonsByFirstnameQueryDSL("Kent").get(0); Assert.assertEquals(person.getId(), personFromDb.getId()); } + + @Test + public void testMultipleFilter() { + personDao.save(new Person("Erich", "Gamma")); + Person person = personDao.save(new Person("Ralph", "Beck")); + Person person2 = personDao.save(new Person("Ralph", "Johnson")); + + Person personFromDb = personDao.findPersonsByFirstnameAndSurnameQueryDSL("Ralph", "Johnson").get(0); + Assert.assertNotSame(person.getId(), personFromDb.getId()); + Assert.assertEquals(person2.getId(), personFromDb.getId()); + } + + @Test + public void testOrdering() { + Person person = personDao.save(new Person("Kent", "Gamma")); + personDao.save(new Person("Ralph", "Johnson")); + Person person2 = personDao.save(new Person("Kent", "Zivago")); + + Person personFromDb = personDao.findPersonsByFirstnameInDescendingOrderQueryDSL("Kent").get(0); + Assert.assertNotSame(person.getId(), personFromDb.getId()); + Assert.assertEquals(person2.getId(), personFromDb.getId()); + } + + @Test + public void testMaxAge() { + personDao.save(new Person("Kent", "Gamma", 20)); + personDao.save(new Person("Ralph", "Johnson", 35)); + personDao.save(new Person("Kent", "Zivago", 30)); + + int maxAge = personDao.findMaxAge(); + Assert.assertTrue(maxAge == 35); + } + + @Test + public void testMaxAgeByName() { + personDao.save(new Person("Kent", "Gamma", 20)); + personDao.save(new Person("Ralph", "Johnson", 35)); + personDao.save(new Person("Kent", "Zivago", 30)); + + Map maxAge = personDao.findMaxAgeByName(); + Assert.assertTrue(maxAge.size() == 2); + Assert.assertSame(35, maxAge.get("Ralph")); + Assert.assertSame(30, maxAge.get("Kent")); + } } \ No newline at end of file From 202a99786a68802645105390e5ca3868360c5a9f Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sat, 27 Feb 2016 10:52:54 +0100 Subject: [PATCH 030/121] Stored Procedure added. Added TestCase without using NamedStoredProcedure --- .../config/database/FIND_CAR_BY_YEAR_PROCEDURE.sql | 7 +++++++ .../src/main/resources/config/database/insert_cars.sql | 7 ++++--- .../jpa/storedprocedure/StoredProcedureTest.java | 10 ++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 persistence-jpa/src/main/resources/config/database/FIND_CAR_BY_YEAR_PROCEDURE.sql diff --git a/persistence-jpa/src/main/resources/config/database/FIND_CAR_BY_YEAR_PROCEDURE.sql b/persistence-jpa/src/main/resources/config/database/FIND_CAR_BY_YEAR_PROCEDURE.sql new file mode 100644 index 0000000000..f9230aad42 --- /dev/null +++ b/persistence-jpa/src/main/resources/config/database/FIND_CAR_BY_YEAR_PROCEDURE.sql @@ -0,0 +1,7 @@ +create or replace PROCEDURE FIND_CAR_BY_YEAR ( p_year IN NUMBER, data OUT SYS_REFCURSOR ) AS + BEGIN + OPEN data FOR + SELECT ID, MODEL, YEAR + FROM CAR + WHERE YEAR = p_year; + END FIND_CAR_BY_YEAR; \ No newline at end of file diff --git a/persistence-jpa/src/main/resources/config/database/insert_cars.sql b/persistence-jpa/src/main/resources/config/database/insert_cars.sql index 5fef151c70..4879ffc79e 100644 --- a/persistence-jpa/src/main/resources/config/database/insert_cars.sql +++ b/persistence-jpa/src/main/resources/config/database/insert_cars.sql @@ -1,4 +1,5 @@ INSERT INTO CAR (ID, MODEL, YEAR) VALUES ('123456', 'Camaro', '2012'); -INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('12112', 'Fiat Panda', '2000') -INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('111000', 'Fiat Punto', '2007') -INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('3382', 'Citroen C3', '2009') +INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('12112', 'Fiat Panda', '2000'); +INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('111000', 'Fiat Punto', '2007'); +INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('3382', 'Citroen C3', '2009'); +commit; \ No newline at end of file diff --git a/persistence-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java b/persistence-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java index 61d4aca85e..e6880c4d76 100644 --- a/persistence-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java +++ b/persistence-jpa/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java @@ -53,6 +53,16 @@ public class StoredProcedureTest { storedProcedure.getResultList().forEach(c -> Assert.assertEquals("Camaro", ((Car) c).getModel())); } + @Test + public void findCarsByYearNoNamedStored() { + StoredProcedureQuery findByYearProcedure = + entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class) + .registerStoredProcedureParameter("p_year", Integer.class, ParameterMode.IN) + .registerStoredProcedureParameter("data", Void.class, ParameterMode.REF_CURSOR).setParameter("p_year", 2015); + + findByYearProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); + } + @AfterClass public static void destroy() { From 24786192029922ce3e5ad392e88cd3b3f86d5df8 Mon Sep 17 00:00:00 2001 From: Giuseppe Bueti Date: Sat, 27 Feb 2016 11:03:32 +0100 Subject: [PATCH 031/121] Modified persistence xsd reference --- .../src/main/resources/META-INF/persistence.xml | 10 +++++----- persistence-jpa/src/test/resources/persistence.xml | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/persistence-jpa/src/main/resources/META-INF/persistence.xml b/persistence-jpa/src/main/resources/META-INF/persistence.xml index 9c5adbac2a..e862311620 100644 --- a/persistence-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-jpa/src/main/resources/META-INF/persistence.xml @@ -1,9 +1,9 @@ - + org.hibernate.jpa.HibernatePersistenceProvider diff --git a/persistence-jpa/src/test/resources/persistence.xml b/persistence-jpa/src/test/resources/persistence.xml index 9a5d8acc36..fc6c7273b2 100644 --- a/persistence-jpa/src/test/resources/persistence.xml +++ b/persistence-jpa/src/test/resources/persistence.xml @@ -1,9 +1,9 @@ - + org.hibernate.jpa.HibernatePersistenceProvider From ac458df0c7cbf275cd2a1c1f6703d4c83898fe30 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:02:46 +0200 Subject: [PATCH 032/121] Update README.md --- spring-data-redis/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-data-redis/README.md b/spring-data-redis/README.md index b9b2e5d93d..89eae99f05 100644 --- a/spring-data-redis/README.md +++ b/spring-data-redis/README.md @@ -1,7 +1,7 @@ ## Spring Data Redis ### Relevant Articles: -- [Introduction to Spring Data Redis] +- [Introduction to Spring Data Redis](http://www.baeldung.com/spring-data-redis-tutorial) ### Build the Project with Tests Running ``` From 1259a0c41ed74d4b7b69577a3b40ceb6f3783267 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:09:52 +0200 Subject: [PATCH 033/121] Create ========= --- raml/modularization/========= | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 raml/modularization/========= diff --git a/raml/modularization/========= b/raml/modularization/========= new file mode 100644 index 0000000000..bb1839f361 --- /dev/null +++ b/raml/modularization/========= @@ -0,0 +1,6 @@ +========= + +## Modular RAML + +### Relevant Articles: +- [Modular RAML Using Includes, Libraries, Overlays and Extensions](http://www.baeldung.com/modular-raml-includes-overlays-libraries-extensions) From b8f0d8a077df29b7a645b7d73ba2e714c119e609 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:10:16 +0200 Subject: [PATCH 034/121] Rename ========= to README.md --- raml/modularization/{========= => README.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename raml/modularization/{========= => README.md} (100%) diff --git a/raml/modularization/========= b/raml/modularization/README.md similarity index 100% rename from raml/modularization/========= rename to raml/modularization/README.md From bea7d842c2e6fac36c360687fb58bf356e74074e Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:11:36 +0200 Subject: [PATCH 035/121] Update README.md --- raml/modularization/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raml/modularization/README.md b/raml/modularization/README.md index bb1839f361..de0e047ea6 100644 --- a/raml/modularization/README.md +++ b/raml/modularization/README.md @@ -1,6 +1,6 @@ ========= -## Modular RAML +## Modular RESTful API Modeling Language ### Relevant Articles: - [Modular RAML Using Includes, Libraries, Overlays and Extensions](http://www.baeldung.com/modular-raml-includes-overlays-libraries-extensions) From f76c47ee8f3ccd1d384b6563946f5ad29a8587e3 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:19:33 +0200 Subject: [PATCH 036/121] Update README.md --- spring-data-elasticsearch/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-data-elasticsearch/README.md b/spring-data-elasticsearch/README.md index 0dae92e0e7..e94f99f587 100644 --- a/spring-data-elasticsearch/README.md +++ b/spring-data-elasticsearch/README.md @@ -1,5 +1,5 @@ ## Spring Data Elasticsearch - +- [Introduction to Spring Data Elasticsearch](http://www.baeldung.com/spring-data-elasticsearch-tutorial) ### Build the Project with Tests Running ``` mvn clean install From cff3d8665f8a8c8863ee72386a8a65eb860f041c Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:19:56 +0200 Subject: [PATCH 037/121] Update README.md --- spring-data-elasticsearch/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-data-elasticsearch/README.md b/spring-data-elasticsearch/README.md index e94f99f587..74d9e4f642 100644 --- a/spring-data-elasticsearch/README.md +++ b/spring-data-elasticsearch/README.md @@ -1,5 +1,6 @@ ## Spring Data Elasticsearch - [Introduction to Spring Data Elasticsearch](http://www.baeldung.com/spring-data-elasticsearch-tutorial) + ### Build the Project with Tests Running ``` mvn clean install From 2c7262dac54e0821e8b5e7b4273f09139322815a Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:23:59 +0200 Subject: [PATCH 038/121] Create README.md --- guava19/README.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 guava19/README.md diff --git a/guava19/README.md b/guava19/README.md new file mode 100644 index 0000000000..5602ad83f6 --- /dev/null +++ b/guava19/README.md @@ -0,0 +1,7 @@ +========= + +## Guava 19 + + +### Relevant Articles: +[Guava 19: What’s New?](http://www.baeldung.com/whats-new-in-guava-19) From 72ac8a9d4137907a0601a9529f3849c5ef7590f8 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:26:19 +0200 Subject: [PATCH 039/121] Create README.md --- resteasy/README.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 resteasy/README.md diff --git a/resteasy/README.md b/resteasy/README.md new file mode 100644 index 0000000000..67550d77d0 --- /dev/null +++ b/resteasy/README.md @@ -0,0 +1,7 @@ +========= + +## A Guide to RESTEasy + + +### Relevant Articles: +- [A Guide to RESTEasy](http://www.baeldung.com/resteasy-tutorial) From b189d03388f13aee01bc2e2f8dbb955655a45706 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:27:08 +0200 Subject: [PATCH 040/121] Update README.md --- guava19/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guava19/README.md b/guava19/README.md index 5602ad83f6..be9f2d72a4 100644 --- a/guava19/README.md +++ b/guava19/README.md @@ -4,4 +4,4 @@ ### Relevant Articles: -[Guava 19: What’s New?](http://www.baeldung.com/whats-new-in-guava-19) +- [Guava 19: What’s New?](http://www.baeldung.com/whats-new-in-guava-19) From 31a5c6ea5c96502bcbf89a9f1728e61e9b871f4b Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:29:53 +0200 Subject: [PATCH 041/121] Create README.md --- raml/annotations/README.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 raml/annotations/README.md diff --git a/raml/annotations/README.md b/raml/annotations/README.md new file mode 100644 index 0000000000..4142b33353 --- /dev/null +++ b/raml/annotations/README.md @@ -0,0 +1,7 @@ +========= + +## Define Custom RAML + + +### Relevant Articles: +- [Define Custom RAML Properties Using Annotations](http://www.baeldung.com/raml-custom-properties-with-annotations) From f02faf32a7410f1d721a19a8335a37444cae6c1b Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:31:47 +0200 Subject: [PATCH 042/121] Update README.md --- resteasy/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/resteasy/README.md b/resteasy/README.md index 67550d77d0..722f1dfe93 100644 --- a/resteasy/README.md +++ b/resteasy/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [A Guide to RESTEasy](http://www.baeldung.com/resteasy-tutorial) +- [RESTEasy Client API](http://www.baeldung.com/resteasy-client-tutorial) From 7cffb8a17ca97005f5ad5804db8bfd118613057a Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:34:23 +0200 Subject: [PATCH 043/121] Update README.md --- spring-apache-camel/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-apache-camel/README.md b/spring-apache-camel/README.md index f6ae77b2a5..d9f380055b 100644 --- a/spring-apache-camel/README.md +++ b/spring-apache-camel/README.md @@ -15,6 +15,7 @@ This article will demonstrate how to configure and use Apache Camel with Spring
  • Spring 4.2.4
  • Apache Camel 2.16.1
  • +
  • Using Apache Camel with Spring

Build and Run Application

@@ -25,4 +26,4 @@ To build this application execute following maven command in ApacheCamelFileProc To run this application you can either run our main class App from your IDE or you can execute following maven command: -mvn exec:java -Dexec.mainClass="App" \ No newline at end of file +mvn exec:java -Dexec.mainClass="App" From 95046958487bb7ba84406c69cbaaaf223e6be642 Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:34:55 +0200 Subject: [PATCH 044/121] Update README.md --- spring-apache-camel/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-apache-camel/README.md b/spring-apache-camel/README.md index d9f380055b..5b24c63cbc 100644 --- a/spring-apache-camel/README.md +++ b/spring-apache-camel/README.md @@ -15,7 +15,6 @@ This article will demonstrate how to configure and use Apache Camel with Spring
  • Spring 4.2.4
  • Apache Camel 2.16.1
  • -
  • Using Apache Camel with Spring

Build and Run Application

From bf9e0b607f46121669249cbcda1275f7bc713e6f Mon Sep 17 00:00:00 2001 From: MichelLeBon Date: Tue, 1 Mar 2016 02:38:43 +0200 Subject: [PATCH 045/121] Update README.md --- core-java-8/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-8/README.md b/core-java-8/README.md index 8bef3a1be0..b03d24c34e 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -8,3 +8,4 @@ - [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources) - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) +- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) From 87e391661d5336f06d2eb19010aadbc772ee8a32 Mon Sep 17 00:00:00 2001 From: Eugen Date: Tue, 1 Mar 2016 11:38:37 +0200 Subject: [PATCH 046/121] Update README.md --- spring-apache-camel/README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/spring-apache-camel/README.md b/spring-apache-camel/README.md index 5b24c63cbc..4015760f7d 100644 --- a/spring-apache-camel/README.md +++ b/spring-apache-camel/README.md @@ -3,7 +3,7 @@ This article will demonstrate how to configure and use Apache Camel with Spring Framework. -

Relevant Article

+

Relevant Articles