From a19854cceb9353a5eafcff737ef1b25a3c021648 Mon Sep 17 00:00:00 2001 From: Alexander Odinets Date: Wed, 30 Dec 2015 16:56:51 +0300 Subject: [PATCH 01/65] Audit with JPA callbacks, Hibernate Envers and Spring Data JPA --- spring-hibernate4/pom.xml | 80 ++++++++-- .../persistence/dao/IBarAuditableDao.java | 8 + .../persistence/dao/IBarCrudRepository.java | 10 ++ .../org/baeldung/persistence/dao/IBarDao.java | 8 + .../persistence/dao/IFooAuditableDao.java | 8 + .../persistence/dao/common/AbstractDao.java | 14 ++ .../common/AbstractHibernateAuditableDao.java | 37 +++++ .../dao/common/AbstractHibernateDao.java | 24 ++- .../dao/common/AbstractJpaDao.java | 56 +++++++ .../dao/common/IAuditOperations.java | 14 ++ .../persistence/dao/impl/BarAuditableDao.java | 28 ++++ .../baeldung/persistence/dao/impl/BarDao.java | 19 +++ .../persistence/dao/impl/BarJpaDao.java | 19 +++ .../persistence/dao/impl/FooAuditableDao.java | 17 +++ .../baeldung/persistence/dao/impl/FooDao.java | 2 +- .../org/baeldung/persistence/model/Bar.java | 138 ++++++++++++++++- .../org/baeldung/persistence/model/Foo.java | 4 + .../service/IBarAuditableService.java | 8 + .../persistence/service/IBarService.java | 8 + .../service/IFooAuditableService.java | 8 + .../AbstractHibernateAuditableService.java | 30 ++++ .../common/AbstractHibernateService.java | 42 ++++++ .../service/common/AbstractJpaService.java | 42 ++++++ .../service/common/AbstractService.java | 2 - .../common/AbstractSpringDataJpaService.java | 46 ++++++ .../service/impl/BarAuditableService.java | 41 +++++ .../service/impl/BarJpaService.java | 30 ++++ .../persistence/service/impl/BarService.java | 30 ++++ .../service/impl/BarSpringDataJpaService.java | 26 ++++ .../service/impl/ChildService.java | 4 +- .../service/impl/FooAuditableService.java | 41 +++++ .../persistence/service/impl/FooService.java | 6 +- .../service/impl/ParentService.java | 4 +- .../baeldung/spring/PersistenceConfig.java | 111 +++++++++++++- .../resources/persistence-mysql.properties | 3 + .../src/main/resources/webSecurityConfig.xml | 3 +- .../persistence/audit/AuditTestSuite.java | 14 ++ .../audit/EnversFooBarAuditTest.java | 142 ++++++++++++++++++ .../persistence/audit/JPABarAuditTest.java | 106 +++++++++++++ .../audit/SpringDataJPABarAuditTest.java | 76 ++++++++++ .../FooServicePersistenceIntegrationTest.java | 2 + 41 files changed, 1263 insertions(+), 48 deletions(-) create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarAuditableDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarCrudRepository.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IFooAuditableDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractJpaDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/IAuditOperations.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarAuditableDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarJpaDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooAuditableDao.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarAuditableService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/IFooAuditableService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateAuditableService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractJpaService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractSpringDataJpaService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarAuditableService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarJpaService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarSpringDataJpaService.java create mode 100644 spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooAuditableService.java create mode 100644 spring-hibernate4/src/test/java/org/baeldung/persistence/audit/AuditTestSuite.java create mode 100644 spring-hibernate4/src/test/java/org/baeldung/persistence/audit/EnversFooBarAuditTest.java create mode 100644 spring-hibernate4/src/test/java/org/baeldung/persistence/audit/JPABarAuditTest.java create mode 100644 spring-hibernate4/src/test/java/org/baeldung/persistence/audit/SpringDataJPABarAuditTest.java diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml index 3b0e3b6a00..711f9b3533 100644 --- a/spring-hibernate4/pom.xml +++ b/spring-hibernate4/pom.xml @@ -15,6 +15,16 @@ spring-context ${org.springframework.version} + + org.springframework + spring-aspects + ${org.springframework.version} + + + org.springframework.security + spring-security-core + ${org.springframework.security.version} + @@ -23,21 +33,35 @@ spring-orm ${org.springframework.version} + + org.springframework.data + spring-data-jpa + ${org.springframework.data.version} + org.hibernate hibernate-core ${hibernate.version} - org.javassist - javassist - ${javassist.version} + org.hibernate + hibernate-envers + ${hibernate-envers.version} + + + javax.transaction + jta + ${jta.version} + + + javax.el + javax.el-api + ${el-api.version} mysql mysql-connector-java ${mysql-connector-java.version} - runtime @@ -77,6 +101,13 @@ ${org.springframework.version} test + + + org.springframework.security + spring-security-test + ${org.springframework.security.version} + test + junit @@ -85,12 +116,6 @@ test - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - org.hamcrest hamcrest-library @@ -162,7 +187,28 @@ - + @@ -171,19 +217,22 @@ 4.2.2.RELEASE 4.0.2.RELEASE - 3.20.0-GA - + 1.9.2.RELEASE + 4.3.11.Final + ${hibernate.version} 5.1.36 7.0.42 + 1.1 + 2.2.4 1.7.12 1.1.3 - + - 5.2.1.Final + 4.3.2.Final 18.0 @@ -204,6 +253,7 @@ 2.18.1 2.7 1.4.15 + diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarAuditableDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarAuditableDao.java new file mode 100644 index 0000000000..060922942b --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarAuditableDao.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.model.Bar; + +public interface IBarAuditableDao extends IBarDao, IAuditOperations { + // +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarCrudRepository.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarCrudRepository.java new file mode 100644 index 0000000000..70fffd9d80 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarCrudRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.persistence.dao; + +import java.io.Serializable; + +import org.baeldung.persistence.model.Bar; +import org.springframework.data.repository.CrudRepository; + +public interface IBarCrudRepository extends CrudRepository { + // +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarDao.java new file mode 100644 index 0000000000..02814b39b8 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IBarDao.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Bar; + +public interface IBarDao extends IOperations { + // +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IFooAuditableDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IFooAuditableDao.java new file mode 100644 index 0000000000..ee0cc1fb8a --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/IFooAuditableDao.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.model.Foo; + +public interface IFooAuditableDao extends IFooDao, IAuditOperations { + // +} \ No newline at end of file diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractDao.java new file mode 100644 index 0000000000..6a1790ad3e --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractDao.java @@ -0,0 +1,14 @@ +package org.baeldung.persistence.dao.common; + +import java.io.Serializable; + +import com.google.common.base.Preconditions; + +public abstract class AbstractDao implements IOperations { + + protected Class clazz; + + protected final void setClazz(final Class clazzToSet) { + clazz = Preconditions.checkNotNull(clazzToSet); + } +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java new file mode 100644 index 0000000000..f0886c612e --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateAuditableDao.java @@ -0,0 +1,37 @@ +package org.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +import org.hibernate.envers.AuditReader; +import org.hibernate.envers.AuditReaderFactory; +import org.hibernate.envers.query.AuditQuery; + +@SuppressWarnings("unchecked") +public class AbstractHibernateAuditableDao extends AbstractHibernateDao implements IAuditOperations { + + @Override + public List getEntitiesAtRevision(final Number revision) { + final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); + final AuditQuery query = auditReader.createQuery().forEntitiesAtRevision(clazz, revision); + final List resultList = query.getResultList(); + return resultList; + } + + @Override + public List getEntitiesModifiedAtRevision(final Number revision) { + final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); + final AuditQuery query = auditReader.createQuery().forEntitiesModifiedAtRevision(clazz, revision); + final List resultList = query.getResultList(); + return resultList; + } + + @Override + public List getRevisions() { + final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession()); + final AuditQuery query = auditReader.createQuery().forRevisionsOfEntity(clazz, true, true); + final List resultList = query.getResultList(); + return resultList; + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateDao.java index 65e57afcb3..dd22d94503 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateDao.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractHibernateDao.java @@ -10,55 +10,49 @@ import org.springframework.beans.factory.annotation.Autowired; import com.google.common.base.Preconditions; @SuppressWarnings("unchecked") -public abstract class AbstractHibernateDao implements IOperations { - private Class clazz; +public abstract class AbstractHibernateDao extends AbstractDao implements IOperations { @Autowired - private SessionFactory sessionFactory; + protected SessionFactory sessionFactory; // API - protected final void setClazz(final Class clazzToSet) { - clazz = Preconditions.checkNotNull(clazzToSet); - } - @Override - public final T findOne(final long id) { + public T findOne(final long id) { return (T) getCurrentSession().get(clazz, id); } @Override - public final List findAll() { + public List findAll() { return getCurrentSession().createQuery("from " + clazz.getName()).list(); } @Override - public final void create(final T entity) { + public void create(final T entity) { Preconditions.checkNotNull(entity); - // getCurrentSession().persist(entity); getCurrentSession().saveOrUpdate(entity); } @Override - public final T update(final T entity) { + public T update(final T entity) { Preconditions.checkNotNull(entity); return (T) getCurrentSession().merge(entity); } @Override - public final void delete(final T entity) { + public void delete(final T entity) { Preconditions.checkNotNull(entity); getCurrentSession().delete(entity); } @Override - public final void deleteById(final long entityId) { + public void deleteById(final long entityId) { final T entity = findOne(entityId); Preconditions.checkState(entity != null); delete(entity); } - protected final Session getCurrentSession() { + protected Session getCurrentSession() { return sessionFactory.getCurrentSession(); } diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractJpaDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractJpaDao.java new file mode 100644 index 0000000000..7e08151bea --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/AbstractJpaDao.java @@ -0,0 +1,56 @@ +package org.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +public class AbstractJpaDao extends AbstractDao implements IOperations { + + @PersistenceContext + private EntityManager em; + + // API + + @Override + public T findOne(final long id) { + return em.find(clazz, Long.valueOf(id).intValue()); + } + + @Override + public List findAll() { + final CriteriaBuilder cb = em.getCriteriaBuilder(); + final CriteriaQuery cq = cb.createQuery(clazz); + final Root rootEntry = cq.from(clazz); + final CriteriaQuery all = cq.select(rootEntry); + final TypedQuery allQuery = em.createQuery(all); + return allQuery.getResultList(); + } + + @Override + public void create(final T entity) { + em.persist(entity); + } + + @Override + public T update(final T entity) { + em.merge(entity); + return entity; + } + + @Override + public void delete(final T entity) { + em.remove(entity); + } + + @Override + public void deleteById(final long entityId) { + delete(findOne(entityId)); + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/IAuditOperations.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/IAuditOperations.java new file mode 100644 index 0000000000..bcc1059dbe --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/common/IAuditOperations.java @@ -0,0 +1,14 @@ +package org.baeldung.persistence.dao.common; + +import java.io.Serializable; +import java.util.List; + +public interface IAuditOperations { + + List getEntitiesAtRevision(Number revision); + + List getEntitiesModifiedAtRevision(Number revision); + + List getRevisions(); + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarAuditableDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarAuditableDao.java new file mode 100644 index 0000000000..bddd98bcfb --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarAuditableDao.java @@ -0,0 +1,28 @@ +package org.baeldung.persistence.dao.impl; + +import java.util.List; + +import org.baeldung.persistence.dao.IBarAuditableDao; +import org.baeldung.persistence.dao.common.AbstractHibernateAuditableDao; +import org.baeldung.persistence.model.Bar; + +public class BarAuditableDao extends AbstractHibernateAuditableDao implements IBarAuditableDao { + + public BarAuditableDao() { + super(); + + setClazz(Bar.class); + } + + // API + + @Override + public List getRevisions() { + final List resultList = super.getRevisions(); + for (final Bar bar : resultList) { + bar.getFooSet().size(); // force FooSet initialization + } + return resultList; + } + +} \ No newline at end of file diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarDao.java new file mode 100644 index 0000000000..ba48581edb --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarDao.java @@ -0,0 +1,19 @@ +package org.baeldung.persistence.dao.impl; + +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.common.AbstractHibernateDao; +import org.baeldung.persistence.model.Bar; +import org.springframework.stereotype.Repository; + +@Repository +public class BarDao extends AbstractHibernateDao implements IBarDao { + + public BarDao() { + super(); + + setClazz(Bar.class); + } + + // API + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarJpaDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarJpaDao.java new file mode 100644 index 0000000000..cd167dd64f --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/BarJpaDao.java @@ -0,0 +1,19 @@ +package org.baeldung.persistence.dao.impl; + +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.common.AbstractJpaDao; +import org.baeldung.persistence.model.Bar; +import org.springframework.stereotype.Repository; + +@Repository +public class BarJpaDao extends AbstractJpaDao implements IBarDao { + + public BarJpaDao() { + super(); + + setClazz(Bar.class); + } + + // API + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooAuditableDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooAuditableDao.java new file mode 100644 index 0000000000..ee9cc639b5 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooAuditableDao.java @@ -0,0 +1,17 @@ +package org.baeldung.persistence.dao.impl; + +import org.baeldung.persistence.dao.IFooAuditableDao; +import org.baeldung.persistence.dao.common.AbstractHibernateAuditableDao; +import org.baeldung.persistence.model.Foo; + +public class FooAuditableDao extends AbstractHibernateAuditableDao implements IFooAuditableDao { + + public FooAuditableDao() { + super(); + + setClazz(Foo.class); + } + + // API + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java index eb3a66126c..b8360160da 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/dao/impl/FooDao.java @@ -6,7 +6,7 @@ import org.baeldung.persistence.model.Foo; import org.springframework.stereotype.Repository; @Repository -public class FooDao extends AbstractHibernateDaoimplements IFooDao { +public class FooDao extends AbstractHibernateDao implements IFooDao { public FooDao() { super(); diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Bar.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Bar.java index 410ad79b02..1d4ec69741 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Bar.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Bar.java @@ -1,26 +1,66 @@ package org.baeldung.persistence.model; import java.io.Serializable; +import java.util.Date; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.EntityListeners; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; +import javax.persistence.PrePersist; +import javax.persistence.PreRemove; +import javax.persistence.PreUpdate; import org.hibernate.annotations.OrderBy; +import org.hibernate.envers.Audited; +import org.jboss.logging.Logger; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; import com.google.common.collect.Sets; @Entity @NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") +@Audited +@EntityListeners(AuditingEntityListener.class) public class Bar implements Serializable { + private static Logger logger = Logger.getLogger(Bar.class); + + public enum OPERATION { + INSERT, UPDATE, DELETE; + private String value; + + OPERATION() { + value = toString(); + } + + public String getValue() { + return value; + } + + public static OPERATION parse(final String value) { + OPERATION operation = null; + for (final OPERATION op : OPERATION.values()) { + if (op.getValue().equals(value)) { + operation = op; + break; + } + } + return operation; + } + }; + @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") @@ -31,8 +71,31 @@ public class Bar implements Serializable { @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @OrderBy(clause = "NAME DESC") + // @NotAudited private Set fooSet = Sets.newHashSet(); + @Column(name = "operation") + private String operation; + + @Column(name = "timestamp") + private long timestamp; + + @Column(name = "created_date") + @CreatedDate + private long createdDate; + + @Column(name = "modified_date") + @LastModifiedDate + private long modifiedDate; + + @Column(name = "created_by") + @CreatedBy + private String createdBy; + + @Column(name = "modified_by") + @LastModifiedBy + private String modifiedBy; + public Bar() { super(); } @@ -69,7 +132,57 @@ public class Bar implements Serializable { this.name = name; } - // + public OPERATION getOperation() { + return OPERATION.parse(operation); + } + + public void setOperation(final OPERATION operation) { + this.operation = operation.getValue(); + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(final long timestamp) { + this.timestamp = timestamp; + } + + public long getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(final long createdDate) { + this.createdDate = createdDate; + } + + public long getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(final long modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(final String createdBy) { + this.createdBy = createdBy; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(final String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + public void setOperation(final String operation) { + this.operation = operation; + } @Override public int hashCode() { @@ -103,4 +216,27 @@ public class Bar implements Serializable { return builder.toString(); } + @PrePersist + public void onPrePersist() { + logger.info("@PrePersist"); + audit(OPERATION.INSERT); + } + + @PreUpdate + public void onPreUpdate() { + logger.info("@PreUpdate"); + audit(OPERATION.UPDATE); + } + + @PreRemove + public void onPreRemove() { + logger.info("@PreRemove"); + audit(OPERATION.DELETE); + } + + private void audit(final OPERATION operation) { + setOperation(operation); + setTimestamp((new Date()).getTime()); + } + } diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Foo.java index 974535e058..9a96594cfe 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Foo.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/model/Foo.java @@ -12,7 +12,11 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import org.hibernate.envers.Audited; + @Entity +@Audited +// @Proxy(lazy = false) public class Foo implements Serializable { @Id diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarAuditableService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarAuditableService.java new file mode 100644 index 0000000000..b481dfefeb --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarAuditableService.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.service; + +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.model.Bar; + +public interface IBarAuditableService extends IBarService, IAuditOperations { + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarService.java new file mode 100644 index 0000000000..145a0d54db --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IBarService.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.service; + +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Bar; + +public interface IBarService extends IOperations { + // +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IFooAuditableService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IFooAuditableService.java new file mode 100644 index 0000000000..2bd9ccb208 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/IFooAuditableService.java @@ -0,0 +1,8 @@ +package org.baeldung.persistence.service; + +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.model.Foo; + +public interface IFooAuditableService extends IFooService, IAuditOperations { + // +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateAuditableService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateAuditableService.java new file mode 100644 index 0000000000..f9b6703607 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateAuditableService.java @@ -0,0 +1,30 @@ +package org.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.dao.common.IOperations; +import org.springframework.transaction.annotation.Transactional; + +@Transactional(value = "hibernateTransactionManager") +public abstract class AbstractHibernateAuditableService extends AbstractHibernateService implements IOperations, IAuditOperations { + + @Override + public List getEntitiesAtRevision(final Number revision) { + return getAuditableDao().getEntitiesAtRevision(revision); + } + + @Override + public List getEntitiesModifiedAtRevision(final Number revision) { + return getAuditableDao().getEntitiesModifiedAtRevision(revision); + } + + @Override + public List getRevisions() { + return getAuditableDao().getRevisions(); + } + + abstract protected IAuditOperations getAuditableDao(); + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateService.java new file mode 100644 index 0000000000..3539a56896 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractHibernateService.java @@ -0,0 +1,42 @@ +package org.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import org.baeldung.persistence.dao.common.IOperations; +import org.springframework.transaction.annotation.Transactional; + +@Transactional(value = "hibernateTransactionManager") +public abstract class AbstractHibernateService extends AbstractService implements IOperations { + + @Override + public T findOne(final long id) { + return super.findOne(id); + } + + @Override + public List findAll() { + return super.findAll(); + } + + @Override + public void create(final T entity) { + super.create(entity); + } + + @Override + public T update(final T entity) { + return super.update(entity); + } + + @Override + public void delete(final T entity) { + super.delete(entity); + } + + @Override + public void deleteById(final long entityId) { + super.deleteById(entityId); + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractJpaService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractJpaService.java new file mode 100644 index 0000000000..2b41edda12 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractJpaService.java @@ -0,0 +1,42 @@ +package org.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import org.baeldung.persistence.dao.common.IOperations; +import org.springframework.transaction.annotation.Transactional; + +@Transactional(value = "jpaTransactionManager") +public abstract class AbstractJpaService extends AbstractService implements IOperations { + + @Override + public T findOne(final long id) { + return super.findOne(id); + } + + @Override + public List findAll() { + return super.findAll(); + } + + @Override + public void create(final T entity) { + super.create(entity); + } + + @Override + public T update(final T entity) { + return super.update(entity); + } + + @Override + public void delete(final T entity) { + super.delete(entity); + } + + @Override + public void deleteById(final long entityId) { + super.deleteById(entityId); + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractService.java index 3b32bc3ebb..530bc5e956 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractService.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractService.java @@ -4,9 +4,7 @@ import java.io.Serializable; import java.util.List; import org.baeldung.persistence.dao.common.IOperations; -import org.springframework.transaction.annotation.Transactional; -@Transactional public abstract class AbstractService implements IOperations { @Override diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractSpringDataJpaService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractSpringDataJpaService.java new file mode 100644 index 0000000000..dfb73204c2 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/common/AbstractSpringDataJpaService.java @@ -0,0 +1,46 @@ +package org.baeldung.persistence.service.common; + +import java.io.Serializable; +import java.util.List; + +import org.baeldung.persistence.dao.common.IOperations; +import org.springframework.data.repository.CrudRepository; +import org.springframework.transaction.annotation.Transactional; + +import com.google.common.collect.Lists; + +@Transactional(value = "jpaTransactionManager") +public abstract class AbstractSpringDataJpaService implements IOperations { + + @Override + public T findOne(final long id) { + return getDao().findOne(Long.valueOf(id)); + } + + @Override + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public void create(final T entity) { + getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().delete(Long.valueOf(entityId)); + } + + protected abstract CrudRepository getDao(); +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarAuditableService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarAuditableService.java new file mode 100644 index 0000000000..9124a41a56 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarAuditableService.java @@ -0,0 +1,41 @@ +package org.baeldung.persistence.service.impl; + +import org.baeldung.persistence.dao.IBarAuditableDao; +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.service.IBarAuditableService; +import org.baeldung.persistence.service.common.AbstractHibernateAuditableService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class BarAuditableService extends AbstractHibernateAuditableService implements IBarAuditableService { + + @Autowired + @Qualifier("barHibernateDao") + private IBarDao dao; + + @Autowired + @Qualifier("barHibernateAuditableDao") + private IBarAuditableDao auditDao; + + public BarAuditableService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + + @Override + protected IAuditOperations getAuditableDao() { + return auditDao; + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarJpaService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarJpaService.java new file mode 100644 index 0000000000..d78fbdd7c4 --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarJpaService.java @@ -0,0 +1,30 @@ +package org.baeldung.persistence.service.impl; + +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.persistence.service.common.AbstractJpaService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class BarJpaService extends AbstractJpaService implements IBarService { + + @Autowired + @Qualifier("barJpaDao") + private IBarDao dao; + + public BarJpaService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} \ No newline at end of file diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarService.java new file mode 100644 index 0000000000..7fdd1b026d --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarService.java @@ -0,0 +1,30 @@ +package org.baeldung.persistence.service.impl; + +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.persistence.service.common.AbstractHibernateService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class BarService extends AbstractHibernateService implements IBarService { + + @Autowired + @Qualifier("barHibernateDao") + private IBarDao dao; + + public BarService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarSpringDataJpaService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarSpringDataJpaService.java new file mode 100644 index 0000000000..65f665495a --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/BarSpringDataJpaService.java @@ -0,0 +1,26 @@ +package org.baeldung.persistence.service.impl; + +import java.io.Serializable; + +import org.baeldung.persistence.dao.IBarCrudRepository; +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.persistence.service.common.AbstractSpringDataJpaService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.repository.CrudRepository; + +public class BarSpringDataJpaService extends AbstractSpringDataJpaService implements IBarService { + + @Autowired + private IBarCrudRepository dao; + + public BarSpringDataJpaService() { + super(); + } + + @Override + protected CrudRepository getDao() { + return dao; + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ChildService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ChildService.java index 71b1bc697e..17f5c36e48 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ChildService.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ChildService.java @@ -4,12 +4,12 @@ import org.baeldung.persistence.dao.IChildDao; import org.baeldung.persistence.dao.common.IOperations; import org.baeldung.persistence.model.Child; import org.baeldung.persistence.service.IChildService; -import org.baeldung.persistence.service.common.AbstractService; +import org.baeldung.persistence.service.common.AbstractHibernateService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class ChildService extends AbstractServiceimplements IChildService { +public class ChildService extends AbstractHibernateServiceimplements IChildService { @Autowired private IChildDao dao; diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooAuditableService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooAuditableService.java new file mode 100644 index 0000000000..bef9ba5fad --- /dev/null +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooAuditableService.java @@ -0,0 +1,41 @@ +package org.baeldung.persistence.service.impl; + +import org.baeldung.persistence.dao.IFooAuditableDao; +import org.baeldung.persistence.dao.IFooDao; +import org.baeldung.persistence.dao.common.IAuditOperations; +import org.baeldung.persistence.dao.common.IOperations; +import org.baeldung.persistence.model.Foo; +import org.baeldung.persistence.service.IFooAuditableService; +import org.baeldung.persistence.service.common.AbstractHibernateAuditableService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +@Service +public class FooAuditableService extends AbstractHibernateAuditableService implements IFooAuditableService { + + @Autowired + @Qualifier("fooHibernateDao") + private IFooDao dao; + + @Autowired + @Qualifier("fooHibernateAuditableDao") + private IFooAuditableDao auditDao; + + public FooAuditableService() { + super(); + } + + // API + + @Override + protected IOperations getDao() { + return dao; + } + + @Override + protected IAuditOperations getAuditableDao() { + return auditDao; + } + +} diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooService.java index 8a89153dd0..65b5cdec5c 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooService.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/FooService.java @@ -4,14 +4,16 @@ import org.baeldung.persistence.dao.IFooDao; import org.baeldung.persistence.dao.common.IOperations; import org.baeldung.persistence.model.Foo; import org.baeldung.persistence.service.IFooService; -import org.baeldung.persistence.service.common.AbstractService; +import org.baeldung.persistence.service.common.AbstractHibernateService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service -public class FooService extends AbstractServiceimplements IFooService { +public class FooService extends AbstractHibernateServiceimplements IFooService { @Autowired + @Qualifier("fooHibernateDao") private IFooDao dao; public FooService() { diff --git a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ParentService.java b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ParentService.java index 1f9b602350..b78ae53264 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ParentService.java +++ b/spring-hibernate4/src/main/java/org/baeldung/persistence/service/impl/ParentService.java @@ -4,12 +4,12 @@ import org.baeldung.persistence.dao.IParentDao; import org.baeldung.persistence.dao.common.IOperations; import org.baeldung.persistence.model.Parent; import org.baeldung.persistence.service.IParentService; -import org.baeldung.persistence.service.common.AbstractService; +import org.baeldung.persistence.service.common.AbstractHibernateService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class ParentService extends AbstractServiceimplements IParentService { +public class ParentService extends AbstractHibernateServiceimplements IParentService { @Autowired private IParentDao dao; diff --git a/spring-hibernate4/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-hibernate4/src/main/java/org/baeldung/spring/PersistenceConfig.java index 000c67d625..ae7ecf3439 100644 --- a/spring-hibernate4/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ b/spring-hibernate4/src/main/java/org/baeldung/spring/PersistenceConfig.java @@ -5,7 +5,24 @@ import java.util.Properties; import javax.sql.DataSource; import org.apache.tomcat.dbcp.dbcp.BasicDataSource; -import org.hibernate.SessionFactory; +import org.baeldung.persistence.dao.IBarAuditableDao; +import org.baeldung.persistence.dao.IBarDao; +import org.baeldung.persistence.dao.IFooAuditableDao; +import org.baeldung.persistence.dao.IFooDao; +import org.baeldung.persistence.dao.impl.BarAuditableDao; +import org.baeldung.persistence.dao.impl.BarDao; +import org.baeldung.persistence.dao.impl.BarJpaDao; +import org.baeldung.persistence.dao.impl.FooAuditableDao; +import org.baeldung.persistence.dao.impl.FooDao; +import org.baeldung.persistence.service.IBarAuditableService; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.persistence.service.IFooAuditableService; +import org.baeldung.persistence.service.IFooService; +import org.baeldung.persistence.service.impl.BarAuditableService; +import org.baeldung.persistence.service.impl.BarJpaService; +import org.baeldung.persistence.service.impl.BarSpringDataJpaService; +import org.baeldung.persistence.service.impl.FooAuditableService; +import org.baeldung.persistence.service.impl.FooService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -13,14 +30,23 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement +@EnableJpaRepositories(basePackages = { "org.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") +@EnableJpaAuditing @PropertySource({ "classpath:persistence-mysql.properties" }) @ComponentScan({ "org.baeldung.persistence" }) public class PersistenceConfig { @@ -42,6 +68,19 @@ public class PersistenceConfig { return sessionFactory; } + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); + emf.setDataSource(restDataSource()); + emf.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + emf.setJpaVendorAdapter(vendorAdapter); + emf.setJpaProperties(hibernateProperties()); + + return emf; + } + @Bean public DataSource restDataSource() { final BasicDataSource dataSource = new BasicDataSource(); @@ -54,12 +93,17 @@ public class PersistenceConfig { } @Bean - @Autowired - public HibernateTransactionManager transactionManager(final SessionFactory sessionFactory) { - final HibernateTransactionManager txManager = new HibernateTransactionManager(); - txManager.setSessionFactory(sessionFactory); + public PlatformTransactionManager hibernateTransactionManager() { + final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory().getObject()); + return transactionManager; + } - return txManager; + @Bean + public PlatformTransactionManager jpaTransactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); + return transactionManager; } @Bean @@ -67,7 +111,57 @@ public class PersistenceConfig { return new PersistenceExceptionTranslationPostProcessor(); } - final Properties hibernateProperties() { + @Bean + public IBarService barJpaService() { + return new BarJpaService(); + } + + @Bean + public IBarService barSpringDataJpaService() { + return new BarSpringDataJpaService(); + } + + @Bean + public IFooService fooHibernateService() { + return new FooService(); + } + + @Bean + public IBarAuditableService barHibernateAuditableService() { + return new BarAuditableService(); + } + + @Bean + public IFooAuditableService fooHibernateAuditableService() { + return new FooAuditableService(); + } + + @Bean + public IBarDao barJpaDao() { + return new BarJpaDao(); + } + + @Bean + public IBarDao barHibernateDao() { + return new BarDao(); + } + + @Bean + public IBarAuditableDao barHibernateAuditableDao() { + return new BarAuditableDao(); + } + + @Bean + public IFooDao fooHibernateDao() { + return new FooDao(); + } + + @Bean + public IFooAuditableDao fooHibernateAuditableDao() { + return new FooAuditableDao(); + } + + private final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); @@ -76,6 +170,9 @@ public class PersistenceConfig { // hibernateProperties.setProperty("hibernate.format_sql", "true"); // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + // Envers properties + hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); + return hibernateProperties; } diff --git a/spring-hibernate4/src/main/resources/persistence-mysql.properties b/spring-hibernate4/src/main/resources/persistence-mysql.properties index 8263b0d9ac..f6b6ab6fca 100644 --- a/spring-hibernate4/src/main/resources/persistence-mysql.properties +++ b/spring-hibernate4/src/main/resources/persistence-mysql.properties @@ -8,3 +8,6 @@ jdbc.pass=tutorialmy5ql hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop + +# envers.X +envers.audit_table_suffix=_audit_log diff --git a/spring-hibernate4/src/main/resources/webSecurityConfig.xml b/spring-hibernate4/src/main/resources/webSecurityConfig.xml index 88af78dabc..d9423d31e7 100644 --- a/spring-hibernate4/src/main/resources/webSecurityConfig.xml +++ b/spring-hibernate4/src/main/resources/webSecurityConfig.xml @@ -5,7 +5,8 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" > - + + diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/AuditTestSuite.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/AuditTestSuite.java new file mode 100644 index 0000000000..d3a0ab9cb6 --- /dev/null +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/AuditTestSuite.java @@ -0,0 +1,14 @@ +package org.baeldung.persistence.audit; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ // @formatter:off + EnversFooBarAuditTest.class, + JPABarAuditTest.class, + SpringDataJPABarAuditTest.class +}) // @formatter:on +public class AuditTestSuite { + // +} \ No newline at end of file diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/EnversFooBarAuditTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/EnversFooBarAuditTest.java new file mode 100644 index 0000000000..7720253237 --- /dev/null +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/EnversFooBarAuditTest.java @@ -0,0 +1,142 @@ +package org.baeldung.persistence.audit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.List; + +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.model.Foo; +import org.baeldung.persistence.service.IBarAuditableService; +import org.baeldung.persistence.service.IFooAuditableService; +import org.baeldung.spring.PersistenceConfig; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class EnversFooBarAuditTest { + + private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + @Autowired + @Qualifier("fooHibernateAuditableService") + private IFooAuditableService fooService; + + @Autowired + @Qualifier("barHibernateAuditableService") + private IBarAuditableService barService; + + @Autowired + private SessionFactory sessionFactory; + + private Session session; + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + makeRevisions(); + session = sessionFactory.openSession(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + session.close(); + } + + private void makeRevisions() { + final Bar bar = rev1(); + rev2(bar); + rev3(bar); + rev4(bar); + } + + // REV #1: insert BAR & FOO1 + private Bar rev1() { + final Bar bar = new Bar("BAR"); + final Foo foo1 = new Foo("FOO1"); + foo1.setBar(bar); + fooService.create(foo1); + return bar; + } + + // REV #2: insert FOO2 & update BAR + private void rev2(final Bar bar) { + final Foo foo2 = new Foo("FOO2"); + foo2.setBar(bar); + fooService.create(foo2); + } + + // REV #3: update BAR + private void rev3(final Bar bar) { + + bar.setName("BAR1"); + barService.update(bar); + } + + // REV #4: insert FOO3 & update BAR + private void rev4(final Bar bar) { + + final Foo foo3 = new Foo("FOO3"); + foo3.setBar(bar); + fooService.create(foo3); + } + + @Test + public final void whenFooBarsModified_thenFooBarsAudited() { + + List barRevisionList; + List fooRevisionList; + + // test Bar revisions + + barRevisionList = barService.getRevisions(); + + assertNotNull(barRevisionList); + assertEquals(4, barRevisionList.size()); + + assertEquals("BAR", barRevisionList.get(0).getName()); + assertEquals("BAR", barRevisionList.get(1).getName()); + assertEquals("BAR1", barRevisionList.get(2).getName()); + assertEquals("BAR1", barRevisionList.get(3).getName()); + + assertEquals(1, barRevisionList.get(0).getFooSet().size()); + assertEquals(2, barRevisionList.get(1).getFooSet().size()); + assertEquals(2, barRevisionList.get(2).getFooSet().size()); + assertEquals(3, barRevisionList.get(3).getFooSet().size()); + + // test Foo revisions + + fooRevisionList = fooService.getRevisions(); + assertNotNull(fooRevisionList); + assertEquals(3, fooRevisionList.size()); + assertEquals("FOO1", fooRevisionList.get(0).getName()); + assertEquals("FOO2", fooRevisionList.get(1).getName()); + assertEquals("FOO3", fooRevisionList.get(2).getName()); + } + +} diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/JPABarAuditTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/JPABarAuditTest.java new file mode 100644 index 0000000000..3f1353ba8c --- /dev/null +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/JPABarAuditTest.java @@ -0,0 +1,106 @@ +package org.baeldung.persistence.audit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.model.Bar.OPERATION; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.spring.PersistenceConfig; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class JPABarAuditTest { + + private static Logger logger = LoggerFactory.getLogger(JPABarAuditTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + + @Autowired + @Qualifier("barJpaService") + private IBarService barService; + + @Autowired + private EntityManagerFactory entityManagerFactory; + + private EntityManager em; + + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + em = entityManagerFactory.createEntityManager(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + em.close(); + } + + + @Test + public final void whenBarsModified_thenBarsAudited() { + + // insert BAR1 + Bar bar1 = new Bar("BAR1"); + barService.create(bar1); + + // update BAR1 + bar1.setName("BAR1a"); + barService.update(bar1); + + // insert BAR2 + Bar bar2 = new Bar("BAR2"); + barService.create(bar2); + + // update BAR1 + bar1.setName("BAR1b"); + barService.update(bar1); + + + // get BAR1 and BAR2 from the DB and check the audit values + // detach instances from persistence context to make sure we fire db + em.detach(bar1); + em.detach(bar2); + bar1 = barService.findOne(bar1.getId()); + bar2 = barService.findOne(bar2.getId()); + + assertNotNull(bar1); + assertNotNull(bar2); + assertEquals(OPERATION.UPDATE, bar1.getOperation()); + assertEquals(OPERATION.INSERT, bar2.getOperation()); + assertTrue(bar1.getTimestamp() > bar2.getTimestamp()); + + barService.deleteById(bar1.getId()); + barService.deleteById(bar2.getId()); + + } + +} \ No newline at end of file diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/SpringDataJPABarAuditTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/SpringDataJPABarAuditTest.java new file mode 100644 index 0000000000..bddaac4011 --- /dev/null +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/audit/SpringDataJPABarAuditTest.java @@ -0,0 +1,76 @@ +package org.baeldung.persistence.audit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.baeldung.persistence.model.Bar; +import org.baeldung.persistence.service.IBarService; +import org.baeldung.spring.PersistenceConfig; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringDataJPABarAuditTest { + + private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + @Autowired + @Qualifier("barSpringDataJpaService") + private IBarService barService; + + @Autowired + private EntityManagerFactory entityManagerFactory; + + private EntityManager em; + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + em = entityManagerFactory.createEntityManager(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + em.close(); + } + + @Test + @WithMockUser(username = "tutorialuser") + public final void whenBarsModified_thenBarsAudited() { + Bar bar = new Bar("BAR1"); + barService.create(bar); + assertEquals(bar.getCreatedDate(), bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + bar.setName("BAR2"); + bar = barService.update(bar); + assertTrue(bar.getCreatedDate() < bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + } +} diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java index 07c6ba3382..37781aeb22 100644 --- a/spring-hibernate4/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java @@ -8,6 +8,7 @@ import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.InvalidDataAccessApiUsageException; @@ -20,6 +21,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; public class FooServicePersistenceIntegrationTest { @Autowired + @Qualifier("fooHibernateService") private IFooService service; // tests From f3feab88f3f872ba3b785a9323728a2b9656c6df Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Thu, 3 Dec 2015 13:46:25 +0300 Subject: [PATCH 02/65] Create AOP examples - Use different types of advice - Use various types of pointcut expressions --- .../java/org/baeldung/aop/LoggingAspect.java | 34 ++++++++++ .../org/baeldung/aop/PerformanceAspect.java | 2 +- .../org/baeldung/aop/PublishingAspect.java | 36 ++++++++++ .../main/java/org/baeldung/dao/FooDao.java | 6 ++ .../org/baeldung/events/FooCreationEvent.java | 10 +++ .../events/FooCreationEventListener.java | 17 +++++ .../src/main/java/org/baeldung/model/Foo.java | 19 ++++++ .../main/resources/org/baeldung/aop/beans.xml | 19 ++++++ .../java/org/baeldung/aop/AopLoggingTest.java | 67 +++++++++++++++++++ .../org/baeldung/aop/AopPublishingTest.java | 67 +++++++++++++++++++ .../aop/AopXmlConfigPerformanceTest.java | 67 +++++++++++++++++++ .../java/org/baeldung/config/TestConfig.java | 2 +- 12 files changed, 344 insertions(+), 2 deletions(-) create mode 100644 spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java create mode 100644 spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java create mode 100644 spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java create mode 100644 spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java create mode 100644 spring-mvc-java/src/main/java/org/baeldung/model/Foo.java create mode 100644 spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml create mode 100644 spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java create mode 100644 spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java create mode 100644 spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java b/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java new file mode 100644 index 0000000000..9317677fe2 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java @@ -0,0 +1,34 @@ +package org.baeldung.aop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.logging.Logger; + +@Component +@Aspect +public class LoggingAspect { + + private static Logger logger = Logger.getLogger(LoggingAspect.class.getName()); + + private ThreadLocal sdf = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat("[yyyy-mm-dd hh:mm:ss:SSS]"); + } + }; + + @Pointcut("@target(org.springframework.stereotype.Repository)") + public void repositoryMethods() {} + + @Before("repositoryMethods()") + public void logMethodCall(JoinPoint jp) throws Throwable { + String methodName = jp.getSignature().getName(); + logger.info(sdf.get().format(new Date()) + methodName); + } +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java b/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java index 12d6bc4e69..57f5bc5edd 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java @@ -16,7 +16,7 @@ public class PerformanceAspect { private static Logger logger = Logger.getLogger(PerformanceAspect.class.getName()); @Pointcut("within(@org.springframework.stereotype.Repository *)") - public void repositoryClassMethods() {}; + public void repositoryClassMethods() {} @Around("repositoryClassMethods()") public Object measureMethodExecutionTime(ProceedingJoinPoint pjp) throws Throwable { diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java b/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java new file mode 100644 index 0000000000..20a10f4f6a --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java @@ -0,0 +1,36 @@ +package org.baeldung.aop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.baeldung.events.FooCreationEvent; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Component; + +@Component +@Aspect +public class PublishingAspect { + + private ApplicationEventPublisher eventPublisher; + + @Autowired + public void setEventPublisher(ApplicationEventPublisher eventPublisher) { + this.eventPublisher = eventPublisher; + } + + @Pointcut("@target(org.springframework.stereotype.Repository)") + public void repositoryMethods() {} + + @Pointcut("execution(* *..create*(Long,..))") + public void firstLongParamMethods() {} + + @Pointcut("repositoryMethods() && firstLongParamMethods()") + public void entityCreationMethods() {} + + @AfterReturning(value = "entityCreationMethods()", returning = "entity") + public void logMethodCall(JoinPoint jp, Object entity) throws Throwable { + eventPublisher.publishEvent(new FooCreationEvent(entity)); + } +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java b/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java index fbd7f4c717..e0da61c547 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java +++ b/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java @@ -1,10 +1,16 @@ package org.baeldung.dao; +import org.baeldung.model.Foo; import org.springframework.stereotype.Repository; @Repository public class FooDao { + public String findById(Long id) { return "Bazz"; } + + public Foo create(Long id, String name) { + return new Foo(id, name); + } } diff --git a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java b/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java new file mode 100644 index 0000000000..af11f3a4be --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java @@ -0,0 +1,10 @@ +package org.baeldung.events; + +import org.springframework.context.ApplicationEvent; + +public class FooCreationEvent extends ApplicationEvent { + + public FooCreationEvent(Object source) { + super(source); + } +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java b/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java new file mode 100644 index 0000000000..35dcfd2bc3 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java @@ -0,0 +1,17 @@ +package org.baeldung.events; + +import org.springframework.context.ApplicationListener; +import org.springframework.stereotype.Component; + +import java.util.logging.Logger; + +@Component +public class FooCreationEventListener implements ApplicationListener { + + private static Logger logger = Logger.getLogger(FooCreationEventListener.class.getName()); + + @Override + public void onApplicationEvent(FooCreationEvent event) { + logger.info("Created foo instance: " + event.getSource().toString()); + } +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java b/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java new file mode 100644 index 0000000000..17510f4836 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java @@ -0,0 +1,19 @@ +package org.baeldung.model; + +public class Foo { + private Long id; + private String name; + + public Foo(Long id, String name) { + this.id = id; + this.name = name; + } + + @Override + public String toString() { + return "Foo{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } +} diff --git a/spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml b/spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml new file mode 100644 index 0000000000..17c63e39e4 --- /dev/null +++ b/spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java b/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java new file mode 100644 index 0000000000..7aff17c424 --- /dev/null +++ b/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java @@ -0,0 +1,67 @@ +package org.baeldung.aop; + +import org.baeldung.config.TestConfig; +import org.baeldung.dao.FooDao; +import org.junit.Before; +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.support.AnnotationConfigContextLoader; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +public class AopLoggingTest { + + @Before + public void setUp() { + logEventHandler = new Handler() { + @Override + public void publish(LogRecord record) { + messages.add(record.getMessage()); + } + + @Override + public void flush() { + } + + @Override + public void close() throws SecurityException { + } + }; + + messages = new ArrayList<>(); + } + + @Autowired + private FooDao dao; + + private Handler logEventHandler; + + private List messages; + + @Test + public void givenLoggingAspect_whenCallDaoMethod_thenBeforeAdviceIsCalled() { + Logger logger = Logger.getLogger(LoggingAspect.class.getName()); + logger.addHandler(logEventHandler); + + dao.findById(1L); + assertThat(messages, hasSize(1)); + + String logMessage = messages.get(0); + Pattern pattern = Pattern.compile("^\\[\\d{4}\\-\\d{2}\\-\\d{2} \\d{2}:\\d{2}:\\d{2}:\\d{3}\\]findById$"); + assertTrue(pattern.matcher(logMessage).matches()); + } +} diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java b/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java new file mode 100644 index 0000000000..561eec06ec --- /dev/null +++ b/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java @@ -0,0 +1,67 @@ +package org.baeldung.aop; + +import org.baeldung.config.TestConfig; +import org.baeldung.dao.FooDao; +import org.baeldung.events.FooCreationEventListener; +import org.baeldung.model.Foo; +import org.junit.Before; +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.support.AnnotationConfigContextLoader; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +public class AopPublishingTest { + + @Before + public void setUp() { + logEventHandler = new Handler() { + @Override + public void publish(LogRecord record) { + messages.add(record.getMessage()); + } + + @Override + public void flush() { + } + + @Override + public void close() throws SecurityException { + } + }; + + messages = new ArrayList<>(); + } + + @Autowired + private FooDao dao; + + private Handler logEventHandler; + + private List messages; + + @Test + public void givenPublishingAspect_whenCallCreate_thenCreationEventIsPublished() { + Logger logger = Logger.getLogger(FooCreationEventListener.class.getName()); + logger.addHandler(logEventHandler); + + dao.create(1L, "Bar"); + + String logMessage = messages.get(0); + Pattern pattern = Pattern.compile("Created foo instance: " + + Pattern.quote(new Foo(1L, "Bar").toString())); + assertTrue(pattern.matcher(logMessage).matches()); + } +} diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java b/spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java new file mode 100644 index 0000000000..7ef25d743c --- /dev/null +++ b/spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java @@ -0,0 +1,67 @@ +package org.baeldung.aop; + +import org.baeldung.dao.FooDao; +import org.junit.Before; +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.ArrayList; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/org/baeldung/aop/beans.xml") +public class AopXmlConfigPerformanceTest { + + @Before + public void setUp() { + logEventHandler = new Handler() { + @Override + public void publish(LogRecord record) { + messages.add(record.getMessage()); + } + + @Override + public void flush() { + } + + @Override + public void close() throws SecurityException { + } + }; + + messages = new ArrayList<>(); + } + + @Autowired + private FooDao dao; + + private Handler logEventHandler; + + private List messages; + + @Test + public void givenPerformanceAspect_whenCallDaoMethod_thenPerformanceMeasurementAdviceIsCalled() { + Logger logger = Logger.getLogger(PerformanceAspect.class.getName()); + logger.addHandler(logEventHandler); + + final String entity = dao.findById(1L); + assertThat(entity, notNullValue()); + assertThat(messages, hasSize(1)); + + String logMessage = messages.get(0); + Pattern pattern = Pattern.compile("Execution of findById took \\d+ ms"); + assertTrue(pattern.matcher(logMessage).matches()); + } +} diff --git a/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java b/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java index 60786a108c..0d103f1029 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java +++ b/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java @@ -5,7 +5,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration -@ComponentScan(basePackages = {"org.baeldung.dao", "org.baeldung.aop"}) +@ComponentScan(basePackages = {"org.baeldung.dao", "org.baeldung.aop", "org.baeldung.events"}) @EnableAspectJAutoProxy public class TestConfig { } From f47b735f83b12f37d80cf62836c2f1cc74c181cb Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Sun, 6 Dec 2015 18:44:56 +0300 Subject: [PATCH 03/65] Add more pointcut expressions examples - Add examples for '@arg' and '@annotation' PCDs --- .../java/org/baeldung/aop/LoggingAspect.java | 19 ++++++++++++++- .../org/baeldung/aop/annotations/Entity.java | 11 +++++++++ .../baeldung/aop/annotations/Loggable.java | 11 +++++++++ .../main/java/org/baeldung/dao/FooDao.java | 6 +++++ .../src/main/java/org/baeldung/model/Foo.java | 3 +++ .../java/org/baeldung/aop/AopLoggingTest.java | 23 +++++++++++++++---- 6 files changed, 68 insertions(+), 5 deletions(-) create mode 100644 spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java create mode 100644 spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java b/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java index 9317677fe2..72ac610abd 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java @@ -26,9 +26,26 @@ public class LoggingAspect { @Pointcut("@target(org.springframework.stereotype.Repository)") public void repositoryMethods() {} + @Pointcut("@annotation(org.baeldung.aop.annotations.Loggable)") + public void loggableMethods() {} + + @Pointcut("@args(org.baeldung.aop.annotations.Entity)") + public void methodsAcceptingEntities() {} + @Before("repositoryMethods()") - public void logMethodCall(JoinPoint jp) throws Throwable { + public void logMethodCall(JoinPoint jp) { String methodName = jp.getSignature().getName(); logger.info(sdf.get().format(new Date()) + methodName); } + + @Before("loggableMethods()") + public void logMethod(JoinPoint jp) { + String methodName = jp.getSignature().getName(); + logger.info("Executing method: " + methodName); + } + + @Before("methodsAcceptingEntities()") + public void logMethodAcceptionEntityAnnotatedBean(JoinPoint jp) { + logger.info("Accepting beans with @Entity annotation: " + jp.getArgs()[0]); + } } diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java b/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java new file mode 100644 index 0000000000..f964c3979e --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java @@ -0,0 +1,11 @@ +package org.baeldung.aop.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface Entity { +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java b/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java new file mode 100644 index 0000000000..ef2863957f --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java @@ -0,0 +1,11 @@ +package org.baeldung.aop.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Loggable { +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java b/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java index e0da61c547..f204440b2d 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java +++ b/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java @@ -1,5 +1,6 @@ package org.baeldung.dao; +import org.baeldung.aop.annotations.Loggable; import org.baeldung.model.Foo; import org.springframework.stereotype.Repository; @@ -10,7 +11,12 @@ public class FooDao { return "Bazz"; } + @Loggable public Foo create(Long id, String name) { return new Foo(id, name); } + + public Foo merge(Foo foo) { + return foo; + } } diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java b/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java index 17510f4836..0b1a553afc 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java +++ b/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java @@ -1,5 +1,8 @@ package org.baeldung.model; +import org.baeldung.aop.annotations.Entity; + +@Entity public class Foo { private Long id; private String name; diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java b/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java index 7aff17c424..4c8fcd50a8 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java +++ b/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java @@ -2,6 +2,7 @@ package org.baeldung.aop; import org.baeldung.config.TestConfig; import org.baeldung.dao.FooDao; +import org.baeldung.model.Foo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,6 +19,7 @@ import java.util.logging.Logger; import java.util.regex.Pattern; import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.core.IsCollectionContaining.hasItem; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -27,6 +29,8 @@ public class AopLoggingTest { @Before public void setUp() { + messages = new ArrayList<>(); + logEventHandler = new Handler() { @Override public void publish(LogRecord record) { @@ -42,7 +46,8 @@ public class AopLoggingTest { } }; - messages = new ArrayList<>(); + Logger logger = Logger.getLogger(LoggingAspect.class.getName()); + logger.addHandler(logEventHandler); } @Autowired @@ -54,9 +59,6 @@ public class AopLoggingTest { @Test public void givenLoggingAspect_whenCallDaoMethod_thenBeforeAdviceIsCalled() { - Logger logger = Logger.getLogger(LoggingAspect.class.getName()); - logger.addHandler(logEventHandler); - dao.findById(1L); assertThat(messages, hasSize(1)); @@ -64,4 +66,17 @@ public class AopLoggingTest { Pattern pattern = Pattern.compile("^\\[\\d{4}\\-\\d{2}\\-\\d{2} \\d{2}:\\d{2}:\\d{2}:\\d{3}\\]findById$"); assertTrue(pattern.matcher(logMessage).matches()); } + + @Test + public void givenLoggingAspect_whenCallLoggableAnnotatedMethod_thenMethodIsLogged() { + dao.create(42L, "baz"); + assertThat(messages, hasItem("Executing method: create")); + } + + @Test + public void givenLoggingAspect_whenCallMethodAcceptingAnnotatedArgument_thenArgumentIsLogged() { + Foo foo = new Foo(42L, "baz"); + dao.merge(foo); + assertThat(messages, hasItem("Accepting beans with @Entity annotation: " + foo)); + } } From b45706cc6013200f8872a495e67eeb05d9c5bb72 Mon Sep 17 00:00:00 2001 From: sameira Date: Wed, 9 Dec 2015 16:11:46 +0530 Subject: [PATCH 04/65] adding Cassandra Templates and CQL Queries tutorial code samples --- .../repository/CQLQueriesIntegrationTest.java | 115 +++++++++++++++ .../CassandraTemplateIntegrationTest.java | 138 ++++++++++++++++++ 2 files changed, 253 insertions(+) create mode 100644 spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java create mode 100644 spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java new file mode 100644 index 0000000000..1835df31f9 --- /dev/null +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java @@ -0,0 +1,115 @@ +package org.baeldung.spring.data.cassandra.repository; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.querybuilder.Insert; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.thrift.transport.TTransportException; +import org.baeldung.spring.data.cassandra.config.CassandraConfig; +import org.baeldung.spring.data.cassandra.model.Book; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.*; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.data.cassandra.core.CassandraOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + +import static junit.framework.TestCase.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class CQLQueriesIntegrationTest { + + private static final Log LOGGER = LogFactory.getLog(CQLQueriesIntegrationTest.class); + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private CassandraAdminOperations adminTemplate; + + @Autowired + private CassandraOperations cassandraTemplate; + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + LOGGER.info("Server Started at 127.0.0.1:9142... "); + Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + Thread.sleep(1000); + LOGGER.info("KeySpace created and activated."); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSavingBook_thenAvailableOnRetrieval_usingQueryBuilder() { + UUID uuid = UUIDs.timeBased(); + Insert insert = QueryBuilder.insertInto(DATA_TABLE_NAME).value("isbn", uuid).value("title", "Head First Java").value("publisher", "OReilly Media").value("tags", ImmutableSet.of("Software")); + cassandraTemplate.execute(insert); + Select select = QueryBuilder.select().from("book").limit(10); + Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + assertEquals(uuid, retrievedBook.getId()); + } + + @Test + public void whenSavingBook_thenAvailableOnRetrieval_usingCQLStatements() { + UUID uuid = UUIDs.timeBased(); + String insertCql = "insert into book (isbn, title, publisher, tags) values " + "(" + uuid + ", 'Head First Java', 'OReilly Media', {'Software'})"; + cassandraTemplate.execute(insertCql); + Select select = QueryBuilder.select().from("book").limit(10); + Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + assertEquals(uuid, retrievedBook.getId()); + } + + @Test + public void whenSavingBook_thenAvailableOnRetrieval_usingPreparedStatements() { + UUID uuid = UUIDs.timeBased(); + String insertPreparedCql = "insert into book (isbn, title, publisher, tags) values (?, ?, ?, ?)"; + List bookList = new ArrayList<>(); + List> bookListOfList = new ArrayList<>(); + bookList.add(uuid); + bookList.add("Head First Java"); + bookList.add("OReilly Media"); + bookList.add(ImmutableSet.of("Software")); + bookList.add(bookList); + cassandraTemplate.ingest(insertPreparedCql, bookListOfList); + Select select = QueryBuilder.select().from("book").limit(10); + Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + assertEquals(uuid, retrievedBook.getId()); + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java new file mode 100644 index 0000000000..69b965f8c5 --- /dev/null +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java @@ -0,0 +1,138 @@ +package org.baeldung.spring.data.cassandra.repository; + +import static junit.framework.TestCase.assertNull; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; + +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.thrift.transport.TTransportException; +import org.baeldung.spring.data.cassandra.config.CassandraConfig; +import org.baeldung.spring.data.cassandra.model.Book; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.data.cassandra.core.CassandraOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class CassandraTemplateIntegrationTest { + + private static final Log LOGGER = LogFactory.getLog(CassandraTemplateIntegrationTest.class); + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private CassandraAdminOperations adminTemplate; + + @Autowired + private CassandraOperations cassandraTemplate; + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + LOGGER.info("Server Started at 127.0.0.1:9142... "); + Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + Thread.sleep(5000); + LOGGER.info("KeySpace created and activated."); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSavingBook_thenAvailableOnRetrieval() { + Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + cassandraTemplate.insert(javaBook); + Select select = QueryBuilder.select().from("book").where(QueryBuilder.eq("title", "Head First Java")).and(QueryBuilder.eq("publisher", "O'Reilly Media")).limit(10); + Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + assertEquals(javaBook.getId(), retrievedBook.getId()); + } + + @Test + public void whenSavingBooks_thenAllAvailableOnRetrieval() { + Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + cassandraTemplate.insert(javaBook); + cassandraTemplate.insert(dPatternBook); + + Select select = QueryBuilder.select().from("book").limit(10); + List retrievedBooks = cassandraTemplate.select(select, Book.class); + assertThat(retrievedBooks.size(), is(2)); + assertEquals(javaBook.getId(), retrievedBooks.get(0).getId()); + assertEquals(dPatternBook.getId(), retrievedBooks.get(1).getId()); + } + + @Test + public void whenUpdatingBook_thenShouldUpdatedOnRetrieval() { + Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + cassandraTemplate.insert(javaBook); + Select select = QueryBuilder.select().from("book").limit(10); + Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + retrievedBook.setTags(ImmutableSet.of("Computer", "Software", "Java")); + cassandraTemplate.update(retrievedBook); + Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); + assertEquals(retrievedBook.getTags(), retrievedUpdatedBook.getTags()); + } + + @Test + public void whenDeletingExistingBooks_thenNotAvailableOnRetrieval() { + Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + Book insertedBook = cassandraTemplate.insert(javaBook); + cassandraTemplate.deleteAll(Book.class); + Select select = QueryBuilder.select().from("book").limit(10); + Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); + assertNull(retrievedUpdatedBook); + } + + @Test + public void whenAddingBooks_thenCountShouldBeCorrectOnRetrieval() { + Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + cassandraTemplate.insert(javaBook); + cassandraTemplate.insert(dPatternBook); + long bookCount = cassandraTemplate.count(Book.class); + assertEquals(2, bookCount); + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} From 908883db12e70b77bf9c93d516fcfdb63826377e Mon Sep 17 00:00:00 2001 From: sameira Date: Wed, 9 Dec 2015 16:20:30 +0530 Subject: [PATCH 05/65] Adding test cases for Cassandra Templates and CQL Queries --- .../repository/CQLQueriesIntegrationTest.java | 4 +- .../CassandraTemplateIntegrationTest.java | 37 ++++++++----------- 2 files changed, 18 insertions(+), 23 deletions(-) diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java index 1835df31f9..fd60b9a7f9 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java @@ -57,7 +57,7 @@ public class CQLQueriesIntegrationTest { Session session = cluster.connect(); session.execute(KEYSPACE_CREATION_QUERY); session.execute(KEYSPACE_ACTIVATE_QUERY); - Thread.sleep(1000); + Thread.sleep(2000); LOGGER.info("KeySpace created and activated."); } @@ -96,7 +96,7 @@ public class CQLQueriesIntegrationTest { bookList.add("Head First Java"); bookList.add("OReilly Media"); bookList.add(ImmutableSet.of("Software")); - bookList.add(bookList); + bookListOfList.add(bookList); cassandraTemplate.ingest(insertPreparedCql, bookListOfList); Select select = QueryBuilder.select().from("book").limit(10); Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java index 69b965f8c5..fae24e8f21 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java @@ -1,14 +1,11 @@ package org.baeldung.spring.data.cassandra.repository; -import static junit.framework.TestCase.assertNull; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; - +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -16,11 +13,7 @@ import org.apache.thrift.transport.TTransportException; import org.baeldung.spring.data.cassandra.config.CassandraConfig; import org.baeldung.spring.data.cassandra.model.Book; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cassandra.core.cql.CqlIdentifier; @@ -29,12 +22,14 @@ import org.springframework.data.cassandra.core.CassandraOperations; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.querybuilder.QueryBuilder; -import com.datastax.driver.core.querybuilder.Select; -import com.datastax.driver.core.utils.UUIDs; -import com.google.common.collect.ImmutableSet; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; + +import static junit.framework.TestCase.assertNull; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CassandraConfig.class) @@ -62,7 +57,7 @@ public class CassandraTemplateIntegrationTest { Session session = cluster.connect(); session.execute(KEYSPACE_CREATION_QUERY); session.execute(KEYSPACE_ACTIVATE_QUERY); - Thread.sleep(5000); + Thread.sleep(2000); LOGGER.info("KeySpace created and activated."); } From 94a6063b4865f54f5cd18765ca8d034b15bb1e38 Mon Sep 17 00:00:00 2001 From: sameira Date: Wed, 9 Dec 2015 17:15:15 +0530 Subject: [PATCH 06/65] Updated data insertion using an array list --- .../repository/CassandraTemplateIntegrationTest.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java index fae24e8f21..3108658c0e 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java @@ -23,6 +23,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -79,8 +80,10 @@ public class CassandraTemplateIntegrationTest { public void whenSavingBooks_thenAllAvailableOnRetrieval() { Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - cassandraTemplate.insert(javaBook); - cassandraTemplate.insert(dPatternBook); + List bookList = new ArrayList<>(); + bookList.add(javaBook); + bookList.add(dPatternBook); + cassandraTemplate.insert(bookList); Select select = QueryBuilder.select().from("book").limit(10); List retrievedBooks = cassandraTemplate.select(select, Book.class); From 0104d187af2227623fff98a1a2f07c55638d1caa Mon Sep 17 00:00:00 2001 From: gmaipady Date: Wed, 9 Dec 2015 17:42:35 +0530 Subject: [PATCH 07/65] Added spring-thymeleaf initial version --- spring-thymeleaf/.classpath | 32 +++++ spring-thymeleaf/.project | 42 ++++++ spring-thymeleaf/pom.xml | 128 ++++++++++++++++++ .../thymeleaf/controller/HomeController.java | 27 ++++ .../controller/StudentController.java | 65 +++++++++ .../thymeleaf/formatter/NameFormatter.java | 30 ++++ .../org/baeldung/thymeleaf/model/Student.java | 40 ++++++ .../src/main/resources/logback.xml | 20 +++ .../main/resources/messages_en_US.properties | 4 + .../WEB-INF/appServlet/servlet-context.xml | 53 ++++++++ .../src/main/webapp/WEB-INF/root-context.xml | 8 ++ .../main/webapp/WEB-INF/views/addStudent.html | 30 ++++ .../src/main/webapp/WEB-INF/views/home.html | 15 ++ .../webapp/WEB-INF/views/listStudents.html | 24 ++++ .../src/main/webapp/WEB-INF/web.xml | 34 +++++ 15 files changed, 552 insertions(+) create mode 100644 spring-thymeleaf/.classpath create mode 100644 spring-thymeleaf/.project create mode 100644 spring-thymeleaf/pom.xml create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java create mode 100644 spring-thymeleaf/src/main/resources/logback.xml create mode 100644 spring-thymeleaf/src/main/resources/messages_en_US.properties create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/web.xml diff --git a/spring-thymeleaf/.classpath b/spring-thymeleaf/.classpath new file mode 100644 index 0000000000..28e4a52cd4 --- /dev/null +++ b/spring-thymeleaf/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-thymeleaf/.project b/spring-thymeleaf/.project new file mode 100644 index 0000000000..3c898c7e84 --- /dev/null +++ b/spring-thymeleaf/.project @@ -0,0 +1,42 @@ + + + spring-thymeleaf + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml new file mode 100644 index 0000000000..770f67d59c --- /dev/null +++ b/spring-thymeleaf/pom.xml @@ -0,0 +1,128 @@ + + 4.0.0 + org.baeldung + spring-thymeleaf + 0.1-SNAPSHOT + war + + 1.7 + + 4.1.8.RELEASE + 3.0.1 + + 1.7.12 + 1.1.3 + + 2.1.4.RELEASE + + 1.1.0.Final + 5.1.2.Final + + 3.3 + 2.6 + 2.18.1 + + + + + org.springframework + spring-context + ${org.springframework-version} + + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + ${org.springframework-version} + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + javax.servlet + javax.servlet-api + ${javax.servlet-version} + provided + + + + javax.validation + validation-api + ${javax.validation-version} + + + org.hibernate + hibernate-validator + ${org.hibernate-version} + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java-version} + ${java-version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + + diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java new file mode 100644 index 0000000000..505dc8303b --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java @@ -0,0 +1,27 @@ +package org.baeldung.thymeleaf.controller; + +import java.text.DateFormat; +import java.util.Date; +import java.util.Locale; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * Handles requests for the application home page. + * + */ +@Controller +public class HomeController { + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String getHome(Model model) { + + DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.getDefault()); + model.addAttribute("serverTime", dateFormat.format(new Date())); + return "home"; + } + +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java new file mode 100644 index 0000000000..fb7f52f853 --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java @@ -0,0 +1,65 @@ +package org.baeldung.thymeleaf.controller; + +import java.util.ArrayList; +import java.util.List; + +import javax.validation.Valid; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +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.baeldung.thymeleaf.model.Student; + +/** + * Handles requests for the student model. + * + */ +@Controller +public class StudentController { + + @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) + public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { + if (!errors.hasErrors()) { + // get mock objects + List students = buildStudents(); + // add current student + students.add(student); + model.addAttribute("students", students); + } + return ((errors.hasErrors()) ? "addStudent" : "listStudents"); + } + + @RequestMapping(value = "/addStudent", method = RequestMethod.GET) + public String addStudent(Model model) { + model.addAttribute("student", new Student()); + return "addStudent"; + } + + @RequestMapping(value = "/listStudents", method = RequestMethod.GET) + public String listStudent(Model model) { + + model.addAttribute("students", buildStudents()); + + return "listStudents"; + } + + private List buildStudents() { + List students = new ArrayList(); + + Student student1 = new Student(); + student1.setId(1001); + student1.setName("John Smith"); + students.add(student1); + + Student student2 = new Student(); + student2.setId(1002); + student2.setName("Jane Williams"); + students.add(student2); + + return students; + } +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java new file mode 100644 index 0000000000..9c07ef8d14 --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java @@ -0,0 +1,30 @@ +package org.baeldung.thymeleaf.formatter; + +import java.text.ParseException; +import java.util.Locale; + +import org.springframework.format.Formatter; +import org.thymeleaf.util.StringUtils; + +/** + * + * Name formatter class that implements the Spring Formatter interface. + * Formats a name(String) and return the value with spaces replaced by commas. + * + */ +public class NameFormatter implements Formatter { + + @Override + public String print(String input, Locale locale) { + return formatName(input, locale); + } + + @Override + public String parse(String input, Locale locale) throws ParseException { + return formatName(input, locale); + } + + private String formatName(String input, Locale locale) { + return StringUtils.replace(input, " ", ","); + } +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java new file mode 100644 index 0000000000..d34af3961e --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java @@ -0,0 +1,40 @@ +package org.baeldung.thymeleaf.model; + +import java.io.Serializable; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +/** + * + * Simple student POJO with two fields - id and name + * + */ +public class Student implements Serializable { + + private static final long serialVersionUID = -8582553475226281591L; + + @NotNull(message = "Student ID is required.") + @Min(value = 1000, message = "Student ID must be atleast 4 digits.") + private Integer id; + + @NotNull(message = "Student Name is required.") + private String name; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-thymeleaf/src/main/resources/logback.xml b/spring-thymeleaf/src/main/resources/logback.xml new file mode 100644 index 0000000000..1146dade63 --- /dev/null +++ b/spring-thymeleaf/src/main/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-thymeleaf/src/main/resources/messages_en_US.properties b/spring-thymeleaf/src/main/resources/messages_en_US.properties new file mode 100644 index 0000000000..0cfe16cd84 --- /dev/null +++ b/spring-thymeleaf/src/main/resources/messages_en_US.properties @@ -0,0 +1,4 @@ +msg.id=ID +msg.name=Name +welcome.message=Welcome Student !!! + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml new file mode 100644 index 0000000000..38a4233c64 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml new file mode 100644 index 0000000000..5cb2a94d73 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html new file mode 100644 index 0000000000..9358c991e9 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html @@ -0,0 +1,30 @@ + + + +Add Student + + +

Add Student

+
+
    +
  • +
  • +
+ + + + + + + + + + + + +
+
+ + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html new file mode 100644 index 0000000000..7d9d5852e4 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html @@ -0,0 +1,15 @@ + + + +Home + + +

+ +

+

+ Current time is +

+ + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html new file mode 100644 index 0000000000..e35082be50 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html @@ -0,0 +1,24 @@ + + + +Student List + + +

Student List

+ + + + + + + + + + + + + +
+ + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..275a482c6f --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,34 @@ + + + + + + contextConfigLocation + /WEB-INF/root-context.xml + + + + + org.springframework.web.context.ContextLoaderListener + + + + + appServlet + org.springframework.web.servlet.DispatcherServlet + + contextConfigLocation + /WEB-INF/appServlet/servlet-context.xml + + 1 + + + + appServlet + / + + \ No newline at end of file From 8db1047c2a1364ae3b96567318821ead3ea7aae9 Mon Sep 17 00:00:00 2001 From: gmaipady Date: Wed, 9 Dec 2015 18:13:30 +0530 Subject: [PATCH 08/65] Updated README file --- spring-thymeleaf/README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 spring-thymeleaf/README.md diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md new file mode 100644 index 0000000000..ef86ae055a --- /dev/null +++ b/spring-thymeleaf/README.md @@ -0,0 +1,17 @@ +========= + +## Spring Thymeleaf Example Project + + +### Relevant Articles: + + +### Build the Project +``` +mvn clean install +``` + +Access sample pages using the URLs: +http://localhost:8080/spring-thymeleaf/ +http://localhost:8080/spring-thymeleaf/addStudent/ +http://localhost:8080/spring-thymeleaf/listStudents/ From c2576ca3f4323acaf59b8d095b8e62054fec3d35 Mon Sep 17 00:00:00 2001 From: Devendra Desale Date: Fri, 11 Dec 2015 15:16:48 +0800 Subject: [PATCH 09/65] Adding spring batch project --- spring-batch-intro/.classpath | 27 ++++++++ spring-batch-intro/.project | 23 +++++++ spring-batch-intro/pom.xml | 45 ++++++++++++++ .../org/baeldung/spring_batch_intro/App.java | 28 +++++++++ .../spring_batch_intro/model/Transaction.java | 54 ++++++++++++++++ .../service/CustomItemProcessor.java | 14 +++++ .../service/RecordFieldSetMapper.java | 33 ++++++++++ .../src/main/resources/input/record.csv | 3 + .../src/main/resources/spring-batch-intro.xml | 61 +++++++++++++++++++ .../src/main/resources/spring.xml | 44 +++++++++++++ spring-batch-intro/xml/output.xml | 1 + 11 files changed, 333 insertions(+) create mode 100644 spring-batch-intro/.classpath create mode 100644 spring-batch-intro/.project create mode 100644 spring-batch-intro/pom.xml create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java create mode 100644 spring-batch-intro/src/main/resources/input/record.csv create mode 100644 spring-batch-intro/src/main/resources/spring-batch-intro.xml create mode 100644 spring-batch-intro/src/main/resources/spring.xml create mode 100644 spring-batch-intro/xml/output.xml diff --git a/spring-batch-intro/.classpath b/spring-batch-intro/.classpath new file mode 100644 index 0000000000..395dbde027 --- /dev/null +++ b/spring-batch-intro/.classpath @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-batch-intro/.project b/spring-batch-intro/.project new file mode 100644 index 0000000000..032f8a9541 --- /dev/null +++ b/spring-batch-intro/.project @@ -0,0 +1,23 @@ + + + spring-batch-intro + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/spring-batch-intro/pom.xml b/spring-batch-intro/pom.xml new file mode 100644 index 0000000000..c68608d4ae --- /dev/null +++ b/spring-batch-intro/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + + org.baeldung + spring-batch-intro + 0.1-SNAPSHOT + jar + + spring-batch-intro + http://maven.apache.org + + + UTF-8 + 4.0.2.RELEASE + 3.0.5.RELEASE + 3.8.11.2 + + + + + + org.xerial + sqlite-jdbc + ${sqlite.version} + + + org.springframework + spring-oxm + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + + org.springframework.batch + spring-batch-core + ${spring.batch.version} + + + + diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java new file mode 100644 index 0000000000..7e6b080851 --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java @@ -0,0 +1,28 @@ +package org.baeldung.spring_batch_intro; + +import org.springframework.batch.core.Job; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.JobParameters; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class App { + public static void main(String[] args) { + + ApplicationContext context = new ClassPathXmlApplicationContext( + "/spring-batch-intro.xml"); + + JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); + Job job = (Job) context.getBean("firstBatchJob"); + System.out.println("Starting the batch job"); + try { + JobExecution execution = jobLauncher.run(job, new JobParameters()); + System.out.println("Job Status : " + execution.getStatus()); + System.out.println("Job completed"); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Job failed"); + } + } +} \ No newline at end of file diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java new file mode 100644 index 0000000000..815af78cd4 --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java @@ -0,0 +1,54 @@ +package org.baeldung.spring_batch_intro.model; + +import java.util.Date; + +import javax.xml.bind.annotation.XmlRootElement; + +@SuppressWarnings("restriction") +@XmlRootElement(name = "transactionRecord") +public class Transaction { + private String username; + private int userId; + private Date transactionDate; + private double amount; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public Date getTransactionDate() { + return transactionDate; + } + + public void setTransactionDate(Date transactionDate) { + this.transactionDate = transactionDate; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } + + @Override + public String toString() { + return "Transaction [username=" + username + ", userId=" + userId + + ", transactionDate=" + transactionDate + ", amount=" + amount + + "]"; + } + +} diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java new file mode 100644 index 0000000000..be1127c5e7 --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java @@ -0,0 +1,14 @@ +package org.baeldung.spring_batch_intro.service; + + +import org.baeldung.spring_batch_intro.model.Transaction; +import org.springframework.batch.item.ItemProcessor; + +public class CustomItemProcessor implements ItemProcessor { + + public Transaction process(Transaction item) throws Exception { + + System.out.println("Processing..." + item); + return item; + } +} \ No newline at end of file diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java new file mode 100644 index 0000000000..2b8f897e2a --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java @@ -0,0 +1,33 @@ +package org.baeldung.spring_batch_intro.service; + +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import org.baeldung.spring_batch_intro.model.Transaction; +import org.springframework.batch.item.file.mapping.FieldSetMapper; +import org.springframework.batch.item.file.transform.FieldSet; +import org.springframework.validation.BindException; + +public class RecordFieldSetMapper implements FieldSetMapper { + + public Transaction mapFieldSet(FieldSet fieldSet) throws BindException { + + SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); + Transaction transaction = new Transaction(); + + transaction.setUsername(fieldSet.readString("username")); + transaction.setUserId(fieldSet.readInt(1)); + transaction.setAmount(fieldSet.readDouble(3)); + //Converting the date + String dateString = fieldSet.readString(2); + try { + transaction.setTransactionDate(dateFormat.parse(dateString)); + } catch (ParseException e) { + e.printStackTrace(); + } + + return transaction; + + } + +} diff --git a/spring-batch-intro/src/main/resources/input/record.csv b/spring-batch-intro/src/main/resources/input/record.csv new file mode 100644 index 0000000000..3a1437eed5 --- /dev/null +++ b/spring-batch-intro/src/main/resources/input/record.csv @@ -0,0 +1,3 @@ +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch-intro/src/main/resources/spring-batch-intro.xml b/spring-batch-intro/src/main/resources/spring-batch-intro.xml new file mode 100644 index 0000000000..06918d8754 --- /dev/null +++ b/spring-batch-intro/src/main/resources/spring-batch-intro.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.baeldung.spring_batch_intro.model.Transaction + + + + + + + + + + + + + + diff --git a/spring-batch-intro/src/main/resources/spring.xml b/spring-batch-intro/src/main/resources/spring.xml new file mode 100644 index 0000000000..d286662002 --- /dev/null +++ b/spring-batch-intro/src/main/resources/spring.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-batch-intro/xml/output.xml b/spring-batch-intro/xml/output.xml new file mode 100644 index 0000000000..9e57fa38f2 --- /dev/null +++ b/spring-batch-intro/xml/output.xml @@ -0,0 +1 @@ +10000.02015-10-31T00:00:00+08:001234devendra12321.02015-12-03T00:00:00+08:002134john23411.02015-02-02T00:00:00+08:002134robin \ No newline at end of file From cd3f3d7551b866a261111cca6694b41a96d63c6d Mon Sep 17 00:00:00 2001 From: Devendra Desale Date: Sun, 13 Dec 2015 22:12:09 +0800 Subject: [PATCH 10/65] adding java based spring batch configuration --- spring-batch-intro/pom.xml | 75 ++++++------- .../org/baeldung/spring_batch_intro/App.java | 42 ++++--- .../spring_batch_intro/SpringBatchConfig.java | 92 +++++++++++++++ .../spring_batch_intro/SpringConfig.java | 75 +++++++++++++ .../spring_batch_intro/model/Transaction.java | 68 ++++++------ .../service/CustomItemProcessor.java | 13 +-- .../service/RecordFieldSetMapper.java | 34 +++--- .../src/main/resources/spring-batch-intro.xml | 105 +++++++++--------- .../src/main/resources/spring.xml | 67 +++++------ 9 files changed, 376 insertions(+), 195 deletions(-) create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java create mode 100644 spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java diff --git a/spring-batch-intro/pom.xml b/spring-batch-intro/pom.xml index c68608d4ae..28d48c594e 100644 --- a/spring-batch-intro/pom.xml +++ b/spring-batch-intro/pom.xml @@ -1,45 +1,44 @@ - 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 - spring-batch-intro - 0.1-SNAPSHOT - jar + org.baeldung + spring-batch-intro + 0.1-SNAPSHOT + jar - spring-batch-intro - http://maven.apache.org + spring-batch-intro + http://maven.apache.org - - UTF-8 - 4.0.2.RELEASE - 3.0.5.RELEASE - 3.8.11.2 - + + UTF-8 + 4.2.0.RELEASE + 3.0.5.RELEASE + 3.8.11.2 + - - - - org.xerial - sqlite-jdbc - ${sqlite.version} - - - org.springframework - spring-oxm - ${spring.version} - - - org.springframework - spring-jdbc - ${spring.version} - - - - org.springframework.batch - spring-batch-core - ${spring.batch.version} - - + + + + org.xerial + sqlite-jdbc + ${sqlite.version} + + + org.springframework + spring-oxm + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + org.springframework.batch + spring-batch-core + ${spring.batch.version} + + diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java index 7e6b080851..a2f8f38e0f 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java @@ -1,28 +1,38 @@ package org.baeldung.spring_batch_intro; +import javax.swing.Spring; + import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { - public static void main(String[] args) { + public static void main(String[] args) { + // Spring Java config + AnnotationConfigApplicationContext context = new + AnnotationConfigApplicationContext(); + context.register(SpringConfig.class); + context.register(SpringBatchConfig.class); + context.refresh(); - ApplicationContext context = new ClassPathXmlApplicationContext( - "/spring-batch-intro.xml"); - - JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); - Job job = (Job) context.getBean("firstBatchJob"); - System.out.println("Starting the batch job"); - try { - JobExecution execution = jobLauncher.run(job, new JobParameters()); - System.out.println("Job Status : " + execution.getStatus()); - System.out.println("Job completed"); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Job failed"); - } - } + // Spring xml config +// ApplicationContext context = new ClassPathXmlApplicationContext( +// "spring-batch-intro.xml"); + + JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); + Job job = (Job) context.getBean("firstBatchJob"); + System.out.println("Starting the batch job"); + try { + JobExecution execution = jobLauncher.run(job, new JobParameters()); + System.out.println("Job Status : " + execution.getStatus()); + System.out.println("Job completed"); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Job failed"); + } + } } \ No newline at end of file diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java new file mode 100644 index 0000000000..c892e24fd8 --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java @@ -0,0 +1,92 @@ +package org.baeldung.spring_batch_intro; + +import java.net.MalformedURLException; +import java.text.ParseException; + +import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.spring_batch_intro.service.CustomItemProcessor; +import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.item.ItemProcessor; +import org.springframework.batch.item.ItemReader; +import org.springframework.batch.item.ItemWriter; +import org.springframework.batch.item.UnexpectedInputException; +import org.springframework.batch.item.file.FlatFileItemReader; +import org.springframework.batch.item.file.mapping.DefaultLineMapper; +import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; +import org.springframework.batch.item.xml.StaxEventItemWriter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.core.io.Resource; +import org.springframework.oxm.Marshaller; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; + +public class SpringBatchConfig { + @Autowired + private JobBuilderFactory jobs; + + @Autowired + private StepBuilderFactory steps; + + @Value("input/record.csv") + private Resource inputCsv; + + @Value("file:xml/output.xml") + private Resource outputXml; + + @Bean + public ItemReader itemReader() + throws UnexpectedInputException, ParseException, Exception { + FlatFileItemReader reader = new FlatFileItemReader(); + DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); + String[] tokens = { "username", "userid", "transactiondate", "amount" }; + tokenizer.setNames(tokens); + reader.setResource(inputCsv); + DefaultLineMapper lineMapper = new DefaultLineMapper(); + lineMapper.setLineTokenizer(tokenizer); + lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); + reader.setLineMapper(lineMapper); + return reader; + } + + @Bean + public ItemProcessor itemProcessor() { + return new CustomItemProcessor(); + } + + @Bean + public ItemWriter itemWriter(Marshaller marshaller) + throws MalformedURLException { + StaxEventItemWriter itemWriter = new StaxEventItemWriter(); + itemWriter.setMarshaller(marshaller); + itemWriter.setRootTagName("transactionRecord"); + itemWriter.setResource(outputXml); + return itemWriter; + } + + @Bean + public Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + marshaller.setClassesToBeBound(new Class[] { Transaction.class }); + return marshaller; + } + + @Bean + protected Step step1(ItemReader reader, + ItemProcessor processor, + ItemWriter writer) { + return steps.get("step1"). chunk(10) + .reader(reader).processor(processor).writer(writer).build(); + } + + @Bean(name = "firstBatchJob") + public Job job(@Qualifier("step1") Step step1) { + return jobs.get("firstBatchJob").start(step1).build(); + } + +} diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java new file mode 100644 index 0000000000..79676fbe4e --- /dev/null +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java @@ -0,0 +1,75 @@ +package org.baeldung.spring_batch_intro; + +import java.net.MalformedURLException; + +import javax.sql.DataSource; + +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.batch.core.launch.support.SimpleJobLauncher; +import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; +import org.springframework.batch.support.transaction.ResourcelessTransactionManager; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.init.DataSourceInitializer; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.transaction.PlatformTransactionManager; + +@Configuration +@EnableBatchProcessing +public class SpringConfig { + + @Value("org/springframework/batch/core/schema-drop-sqlite.sql") + private Resource dropReopsitoryTables; + + @Value("org/springframework/batch/core/schema-sqlite.sql") + private Resource dataReopsitorySchema; + + @Bean + public DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.sqlite.JDBC"); + dataSource.setUrl("jdbc:sqlite:repository.sqlite"); + return dataSource; + } + + @Bean + public DataSourceInitializer dataSourceInitializer(DataSource dataSource) + throws MalformedURLException { + ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); + + databasePopulator.addScript(dropReopsitoryTables); + databasePopulator.addScript(dataReopsitorySchema); + databasePopulator.setIgnoreFailedDrops(true); + + DataSourceInitializer initializer = new DataSourceInitializer(); + initializer.setDataSource(dataSource); + initializer.setDatabasePopulator(databasePopulator); + + return initializer; + } + + private JobRepository getJobRepository() throws Exception { + JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); + factory.setDataSource(dataSource()); + factory.setTransactionManager(getTransactionManager()); + factory.afterPropertiesSet(); + return (JobRepository) factory.getObject(); + } + + private PlatformTransactionManager getTransactionManager() { + return new ResourcelessTransactionManager(); + } + + public JobLauncher getJobLauncher() throws Exception { + SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); + jobLauncher.setJobRepository(getJobRepository()); + jobLauncher.afterPropertiesSet(); + return jobLauncher; + } + +} \ No newline at end of file diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java index 815af78cd4..0108dcf501 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java @@ -7,48 +7,48 @@ import javax.xml.bind.annotation.XmlRootElement; @SuppressWarnings("restriction") @XmlRootElement(name = "transactionRecord") public class Transaction { - private String username; - private int userId; - private Date transactionDate; - private double amount; + private String username; + private int userId; + private Date transactionDate; + private double amount; - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public int getUserId() { - return userId; - } + public int getUserId() { + return userId; + } - public void setUserId(int userId) { - this.userId = userId; - } + public void setUserId(int userId) { + this.userId = userId; + } - public Date getTransactionDate() { - return transactionDate; - } + public Date getTransactionDate() { + return transactionDate; + } - public void setTransactionDate(Date transactionDate) { - this.transactionDate = transactionDate; - } + public void setTransactionDate(Date transactionDate) { + this.transactionDate = transactionDate; + } - public double getAmount() { - return amount; - } + public double getAmount() { + return amount; + } - public void setAmount(double amount) { - this.amount = amount; - } + public void setAmount(double amount) { + this.amount = amount; + } - @Override - public String toString() { - return "Transaction [username=" + username + ", userId=" + userId - + ", transactionDate=" + transactionDate + ", amount=" + amount - + "]"; - } + @Override + public String toString() { + return "Transaction [username=" + username + ", userId=" + userId + + ", transactionDate=" + transactionDate + ", amount=" + amount + + "]"; + } } diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java index be1127c5e7..487dbb5efb 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java @@ -1,14 +1,13 @@ package org.baeldung.spring_batch_intro.service; - import org.baeldung.spring_batch_intro.model.Transaction; import org.springframework.batch.item.ItemProcessor; -public class CustomItemProcessor implements ItemProcessor { +public class CustomItemProcessor implements + ItemProcessor { - public Transaction process(Transaction item) throws Exception { - - System.out.println("Processing..." + item); - return item; - } + public Transaction process(Transaction item) throws Exception { + System.out.println("Processing..." + item); + return item; + } } \ No newline at end of file diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java index 2b8f897e2a..0955b57c76 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java @@ -10,24 +10,24 @@ import org.springframework.validation.BindException; public class RecordFieldSetMapper implements FieldSetMapper { - public Transaction mapFieldSet(FieldSet fieldSet) throws BindException { - - SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); - Transaction transaction = new Transaction(); - - transaction.setUsername(fieldSet.readString("username")); - transaction.setUserId(fieldSet.readInt(1)); - transaction.setAmount(fieldSet.readDouble(3)); - //Converting the date - String dateString = fieldSet.readString(2); - try { - transaction.setTransactionDate(dateFormat.parse(dateString)); - } catch (ParseException e) { - e.printStackTrace(); - } + public Transaction mapFieldSet(FieldSet fieldSet) throws BindException { - return transaction; + SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); + Transaction transaction = new Transaction(); - } + transaction.setUsername(fieldSet.readString("username")); + transaction.setUserId(fieldSet.readInt(1)); + transaction.setAmount(fieldSet.readDouble(3)); + // Converting the date + String dateString = fieldSet.readString(2); + try { + transaction.setTransactionDate(dateFormat.parse(dateString)); + } catch (ParseException e) { + e.printStackTrace(); + } + + return transaction; + + } } diff --git a/spring-batch-intro/src/main/resources/spring-batch-intro.xml b/spring-batch-intro/src/main/resources/spring-batch-intro.xml index 06918d8754..6daa0358d9 100644 --- a/spring-batch-intro/src/main/resources/spring-batch-intro.xml +++ b/spring-batch-intro/src/main/resources/spring-batch-intro.xml @@ -1,61 +1,66 @@ - - - - - + - + - - - - - - - - - + - - - - - - - - - - - - + - - - - org.baeldung.spring_batch_intro.model.Transaction - - - + + + + + + + + + - - - - - - - - - + + + + + + + + + + + + + + + + + org.baeldung.spring_batch_intro.model.Transaction + + + + + + + + + + + + + + diff --git a/spring-batch-intro/src/main/resources/spring.xml b/spring-batch-intro/src/main/resources/spring.xml index d286662002..dea261c5e6 100644 --- a/spring-batch-intro/src/main/resources/spring.xml +++ b/spring-batch-intro/src/main/resources/spring.xml @@ -1,44 +1,45 @@ + http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd"> - - - - - - - + + + + + + + - - - - - + + + + + - - + + - - - - - - + + + + + + - + - - - + + + \ No newline at end of file From a6e0acdb0138cd5419dfa9a640f37d8e7bd56857 Mon Sep 17 00:00:00 2001 From: Devendra Desale Date: Mon, 14 Dec 2015 14:35:09 +0800 Subject: [PATCH 11/65] updating generic Exception and linewrappings. --- .../org/baeldung/spring_batch_intro/App.java | 16 +++++++--------- .../spring_batch_intro/SpringBatchConfig.java | 10 +++++----- .../spring_batch_intro/SpringConfig.java | 6 +++++- .../spring_batch_intro/model/Transaction.java | 6 ++++-- .../service/CustomItemProcessor.java | 4 ++-- .../service/RecordFieldSetMapper.java | 6 ++++-- .../src/main/resources/spring-batch-intro.xml | 2 -- 7 files changed, 27 insertions(+), 23 deletions(-) diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java index a2f8f38e0f..db963fff20 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java @@ -1,7 +1,5 @@ package org.baeldung.spring_batch_intro; -import javax.swing.Spring; - import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; @@ -10,18 +8,18 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; + public class App { public static void main(String[] args) { // Spring Java config - AnnotationConfigApplicationContext context = new - AnnotationConfigApplicationContext(); - context.register(SpringConfig.class); - context.register(SpringBatchConfig.class); - context.refresh(); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.register(SpringConfig.class); + context.register(SpringBatchConfig.class); + context.refresh(); // Spring xml config -// ApplicationContext context = new ClassPathXmlApplicationContext( -// "spring-batch-intro.xml"); + // ApplicationContext context = new ClassPathXmlApplicationContext( + // "spring-batch-intro.xml"); JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); Job job = (Job) context.getBean("firstBatchJob"); diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java index c892e24fd8..f0e3b364b6 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java @@ -41,7 +41,7 @@ public class SpringBatchConfig { @Bean public ItemReader itemReader() - throws UnexpectedInputException, ParseException, Exception { + throws UnexpectedInputException, ParseException { FlatFileItemReader reader = new FlatFileItemReader(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); String[] tokens = { "username", "userid", "transactiondate", "amount" }; @@ -61,7 +61,7 @@ public class SpringBatchConfig { @Bean public ItemWriter itemWriter(Marshaller marshaller) - throws MalformedURLException { + throws MalformedURLException { StaxEventItemWriter itemWriter = new StaxEventItemWriter(); itemWriter.setMarshaller(marshaller); itemWriter.setRootTagName("transactionRecord"); @@ -78,10 +78,10 @@ public class SpringBatchConfig { @Bean protected Step step1(ItemReader reader, - ItemProcessor processor, - ItemWriter writer) { + ItemProcessor processor, + ItemWriter writer) { return steps.get("step1"). chunk(10) - .reader(reader).processor(processor).writer(writer).build(); + .reader(reader).processor(processor).writer(writer).build(); } @Bean(name = "firstBatchJob") diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java index 79676fbe4e..91366d8721 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java @@ -39,7 +39,7 @@ public class SpringConfig { @Bean public DataSourceInitializer dataSourceInitializer(DataSource dataSource) - throws MalformedURLException { + throws MalformedURLException { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(dropReopsitoryTables); @@ -57,6 +57,8 @@ public class SpringConfig { JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(dataSource()); factory.setTransactionManager(getTransactionManager()); + // JobRepositoryFactoryBean's methods Throws Generic Exception, + // it would have been better to have a specific one factory.afterPropertiesSet(); return (JobRepository) factory.getObject(); } @@ -67,6 +69,8 @@ public class SpringConfig { public JobLauncher getJobLauncher() throws Exception { SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); + // SimpleJobLauncher's methods Throws Generic Exception, + // it would have been better to have a specific one jobLauncher.setJobRepository(getJobRepository()); jobLauncher.afterPropertiesSet(); return jobLauncher; diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java index 0108dcf501..6e80298ff0 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java @@ -12,6 +12,8 @@ public class Transaction { private Date transactionDate; private double amount; + /* getters and setters for the attributes */ + public String getUsername() { return username; } @@ -47,8 +49,8 @@ public class Transaction { @Override public String toString() { return "Transaction [username=" + username + ", userId=" + userId - + ", transactionDate=" + transactionDate + ", amount=" + amount - + "]"; + + ", transactionDate=" + transactionDate + ", amount=" + amount + + "]"; } } diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java index 487dbb5efb..baabe79409 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java @@ -4,9 +4,9 @@ import org.baeldung.spring_batch_intro.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class CustomItemProcessor implements - ItemProcessor { + ItemProcessor { - public Transaction process(Transaction item) throws Exception { + public Transaction process(Transaction item) { System.out.println("Processing..." + item); return item; } diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java index 0955b57c76..94f9e7d94e 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java @@ -14,9 +14,11 @@ public class RecordFieldSetMapper implements FieldSetMapper { SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); Transaction transaction = new Transaction(); - + // you can either use the indices or custom names + // I personally prefer the custom names easy for debugging and + // validating the pipelines transaction.setUsername(fieldSet.readString("username")); - transaction.setUserId(fieldSet.readInt(1)); + transaction.setUserId(fieldSet.readInt("userid")); transaction.setAmount(fieldSet.readDouble(3)); // Converting the date String dateString = fieldSet.readString(2); diff --git a/spring-batch-intro/src/main/resources/spring-batch-intro.xml b/spring-batch-intro/src/main/resources/spring-batch-intro.xml index 6daa0358d9..3b1f11521f 100644 --- a/spring-batch-intro/src/main/resources/spring-batch-intro.xml +++ b/spring-batch-intro/src/main/resources/spring-batch-intro.xml @@ -8,8 +8,6 @@ - - From 692d52c0dac2367993bdccacc8107206c379e50f Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 14 Dec 2015 17:05:11 +0200 Subject: [PATCH 12/65] fix error message --- .../CustomAuthenticationFailureHandler.java | 44 +++++++++++++++++++ .../baeldung/spring/SecSecurityConfig.java | 5 +++ .../src/main/webapp/WEB-INF/view/login.jsp | 36 ++++----------- 3 files changed, 57 insertions(+), 28 deletions(-) create mode 100644 spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java new file mode 100644 index 0000000000..8ae1ccf8bc --- /dev/null +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java @@ -0,0 +1,44 @@ +package org.baeldung.security; + +import java.io.IOException; +import java.util.Locale; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.LocaleResolver; + +@Component +public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { + + @Autowired + private MessageSource messages; + + @Autowired + private LocaleResolver localeResolver; + + @Override + public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException exception) throws IOException, ServletException { + setDefaultFailureUrl("/login.html?error=true"); + + super.onAuthenticationFailure(request, response, exception); + + final Locale locale = localeResolver.resolveLocale(request); + + if (exception.getMessage().equalsIgnoreCase("User is disabled")) { + request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", messages.getMessage("auth.message.disabled", null, locale)); + } else if (exception.getMessage().equalsIgnoreCase("User account has expired")) { + request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", messages.getMessage("auth.message.expired", null, locale)); + } else if (exception.getMessage().equalsIgnoreCase("blocked")) { + request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", messages.getMessage("auth.message.blocked", null, locale)); + } else { + request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", messages.getMessage("message.badCredentials", null, locale)); + } + } +} \ No newline at end of file diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 814ed92b33..4863187bba 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -13,6 +13,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; @Configuration @@ -26,6 +27,9 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationSuccessHandler myAuthenticationSuccessHandler; + @Autowired + private AuthenticationFailureHandler authenticationFailureHandler; + public SecSecurityConfig() { super(); } @@ -59,6 +63,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .defaultSuccessUrl("/homepage.html") .failureUrl("/login.html?error=true") .successHandler(myAuthenticationSuccessHandler) + .failureHandler(authenticationFailureHandler) .usernameParameter("j_username") .passwordParameter("j_password") .permitAll() diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp index d1be07060a..949b8164de 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp @@ -7,34 +7,7 @@ <%@ page session="true"%> - - - -
- -
-
- -
- -
-
- -
- -
-
- -
- - -
-
-
-
+ @@ -72,6 +45,13 @@ ${param.message} + + +
+${SPRING_SECURITY_LAST_EXCEPTION} +
+
+

From 6a6c546c0c9fab76d66152cd0436b7c6a197d8fb Mon Sep 17 00:00:00 2001 From: gmaipady Date: Tue, 15 Dec 2015 15:52:52 +0530 Subject: [PATCH 13/65] Minor changes --- .../controller/StudentController.java | 71 ++++++++++--------- .../org/baeldung/thymeleaf/model/Student.java | 58 ++++++++++----- .../main/resources/messages_en_US.properties | 5 ++ .../WEB-INF/appServlet/servlet-context.xml | 6 +- .../main/webapp/WEB-INF/views/addStudent.html | 17 ++++- .../src/main/webapp/WEB-INF/views/home.html | 16 +++-- .../webapp/WEB-INF/views/listStudents.html | 20 ++++-- 7 files changed, 128 insertions(+), 65 deletions(-) diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java index fb7f52f853..3bef22cdae 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java @@ -21,45 +21,50 @@ import org.baeldung.thymeleaf.model.Student; @Controller public class StudentController { - @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) - public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { - if (!errors.hasErrors()) { - // get mock objects - List students = buildStudents(); - // add current student - students.add(student); - model.addAttribute("students", students); - } - return ((errors.hasErrors()) ? "addStudent" : "listStudents"); - } + @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) + public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { + if (!errors.hasErrors()) { + // get mock objects + List students = buildStudents(); + // add current student + students.add(student); + model.addAttribute("students", students); + } + return ((errors.hasErrors()) ? "addStudent" : "listStudents"); + } - @RequestMapping(value = "/addStudent", method = RequestMethod.GET) - public String addStudent(Model model) { - model.addAttribute("student", new Student()); - return "addStudent"; - } + @RequestMapping(value = "/addStudent", method = RequestMethod.GET) + public String addStudent(Model model) { + model.addAttribute("student", new Student()); + return "addStudent"; + } - @RequestMapping(value = "/listStudents", method = RequestMethod.GET) - public String listStudent(Model model) { + @RequestMapping(value = "/listStudents", method = RequestMethod.GET) + public String listStudent(Model model) { - model.addAttribute("students", buildStudents()); + model.addAttribute("students", buildStudents()); - return "listStudents"; - } + return "listStudents"; + } - private List buildStudents() { - List students = new ArrayList(); + private List buildStudents() { + List students = new ArrayList(); - Student student1 = new Student(); - student1.setId(1001); - student1.setName("John Smith"); - students.add(student1); + Student student1 = new Student(); + student1.setId(1001); + student1.setName("John Smith"); + student1.setGender('M'); + student1.setPercentage(Float.valueOf("80.45")); - Student student2 = new Student(); - student2.setId(1002); - student2.setName("Jane Williams"); - students.add(student2); + students.add(student1); - return students; - } + Student student2 = new Student(); + student2.setId(1002); + student2.setName("Jane Williams"); + student2.setGender('F'); + student2.setPercentage(Float.valueOf("60.25")); + + students.add(student2); + return students; + } } diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java index d34af3961e..d4d8ea1d6c 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java @@ -7,34 +7,54 @@ import javax.validation.constraints.NotNull; /** * - * Simple student POJO with two fields - id and name + * Simple student POJO with few fields * */ public class Student implements Serializable { - private static final long serialVersionUID = -8582553475226281591L; + private static final long serialVersionUID = -8582553475226281591L; - @NotNull(message = "Student ID is required.") - @Min(value = 1000, message = "Student ID must be atleast 4 digits.") - private Integer id; + @NotNull(message = "Student ID is required.") + @Min(value = 1000, message = "Student ID must be atleast 4 digits.") + private Integer id; - @NotNull(message = "Student Name is required.") - private String name; + @NotNull(message = "Student name is required.") + private String name; - public Integer getId() { - return id; - } + @NotNull(message = "Student gender is required.") + private Character gender; - public void setId(Integer id) { - this.id = id; - } + private Float percentage; - public String getName() { - return name; - } + public Integer getId() { + return id; + } - public void setName(String name) { - this.name = name; - } + public void setId(Integer id) { + this.id = id; + } + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Character getGender() { + return gender; + } + + public void setGender(Character gender) { + this.gender = gender; + } + + public Float getPercentage() { + return percentage; + } + + public void setPercentage(Float percentage) { + this.percentage = percentage; + } } diff --git a/spring-thymeleaf/src/main/resources/messages_en_US.properties b/spring-thymeleaf/src/main/resources/messages_en_US.properties index 0cfe16cd84..33295968e0 100644 --- a/spring-thymeleaf/src/main/resources/messages_en_US.properties +++ b/spring-thymeleaf/src/main/resources/messages_en_US.properties @@ -1,4 +1,9 @@ msg.id=ID msg.name=Name +msg.gender=Gender +msg.percent=Percentage welcome.message=Welcome Student !!! +msg.AddStudent=Add Student +msg.ListStudents=List Students +msg.Home=Home diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml index 38a4233c64..ef42557429 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml @@ -26,7 +26,7 @@ - + - org.springframework spring-web @@ -21,64 +18,53 @@ spring-webmvc ${org.springframework.version} - - javax.servlet javax.servlet-api 3.0.1 provided - javax.servlet jstl 1.2 runtime - org.springframework spring-aop ${org.springframework.version} - org.aspectj aspectjrt ${aspectj.version} - org.aspectj aspectjweaver ${aspectj.version} - org.slf4j slf4j-api ${org.slf4j.version} - org.slf4j slf4j-log4j12 ${org.slf4j.version} - - junit junit-dep ${junit.version} test - org.hamcrest hamcrest-core @@ -91,23 +77,30 @@ ${org.hamcrest.version} test - org.mockito mockito-core ${mockito.version} test - org.springframework spring-test ${org.springframework.version} test - + + + org.thymeleaf + thymeleaf-spring4 + ${thymeleaf.version} + + + org.thymeleaf + thymeleaf + ${thymeleaf.version} + - spring-mvc-java @@ -116,9 +109,7 @@ true - - org.apache.maven.plugins maven-compiler-plugin @@ -128,7 +119,10 @@ 1.8 - + + maven-resources-plugin + 2.7 + org.apache.maven.plugins maven-war-plugin @@ -137,7 +131,6 @@ false - org.apache.maven.plugins maven-surefire-plugin @@ -151,7 +144,6 @@ - org.codehaus.cargo cargo-maven2-plugin @@ -172,50 +164,46 @@ - + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + / + + - - 4.2.2.RELEASE 4.0.2.RELEASE - + 2.1.4.RELEASE 4.3.11.Final 5.1.36 - 1.7.12 1.1.3 - 5.2.1.Final - 18.0 3.4 - 1.3 4.11 1.10.19 - 4.4.1 4.5 - 2.4.1 - 3.3 2.6 2.18.1 2.7 1.4.15 - 1.8.7 - \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java b/spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java new file mode 100644 index 0000000000..3203296a17 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java @@ -0,0 +1,31 @@ +package org.baeldung.controller; + +import org.baeldung.model.UserDetails; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/") +public class UserController { + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String showForm(final Model model) { + final UserDetails user = new UserDetails(); + user.setFirstname("John"); + user.setLastname("Roy"); + user.setEmailId("John.Roy@gmail.com"); + model.addAttribute("user", user); + return "index"; + } + + @RequestMapping(value = "/processForm", method = RequestMethod.POST) + public String processForm(@ModelAttribute(value = "user") final UserDetails user, final Model model) { + // Insert userDetails into DB + model.addAttribute("name", user.getFirstname() + " " + user.getLastname()); + return "hello"; + } + +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java b/spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java new file mode 100644 index 0000000000..e6d1ad6b74 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java @@ -0,0 +1,24 @@ +package org.baeldung.dialect; + +import java.util.HashSet; +import java.util.Set; + +import org.baeldung.processor.NameProcessor; +import org.thymeleaf.dialect.AbstractDialect; +import org.thymeleaf.processor.IProcessor; + +public class CustomDialect extends AbstractDialect { + + @Override + public String getPrefix() { + return "custom"; + } + + @Override + public Set getProcessors() { + final Set processors = new HashSet(); + processors.add(new NameProcessor()); + return processors; + } + +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java b/spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java new file mode 100644 index 0000000000..d0b37fae8a --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java @@ -0,0 +1,32 @@ +package org.baeldung.model; + +public class UserDetails { + private String firstname; + private String lastname; + private String emailId; + + public String getFirstname() { + return firstname; + } + + public void setFirstname(final String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(final String lastname) { + this.lastname = lastname; + } + + public String getEmailId() { + return emailId; + } + + public void setEmailId(final String emailId) { + this.emailId = emailId; + } + +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java b/spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java new file mode 100644 index 0000000000..df9a4da7f0 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java @@ -0,0 +1,23 @@ +package org.baeldung.processor; + +import org.thymeleaf.Arguments; +import org.thymeleaf.dom.Element; +import org.thymeleaf.processor.attr.AbstractTextChildModifierAttrProcessor; + +public class NameProcessor extends AbstractTextChildModifierAttrProcessor { + + public NameProcessor() { + super("name"); + } + + @Override + protected String getText(final Arguments arguements, final Element elements, final String attributeName) { + return "Hello, " + elements.getAttributeValue(attributeName) + "!"; + } + + @Override + public int getPrecedence() { + return 1000; + } + +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java index 945c1794fb..50681e88f6 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java @@ -1,16 +1,28 @@ package org.baeldung.spring.web.config; +import java.util.HashSet; +import java.util.Set; + +import org.baeldung.dialect.CustomDialect; +import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Description; +import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; +import org.thymeleaf.dialect.IDialect; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @EnableWebMvc @Configuration +@ComponentScan("org.baeldung.controller") public class ClientWebConfig extends WebMvcConfigurerAdapter { public ClientWebConfig() { @@ -28,12 +40,49 @@ public class ClientWebConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - + /*final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); + bean.setSuffix(".jsp");*/ - return bean; + final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + + return viewResolver; } + + @Bean + @Description("Thymeleaf template resolver serving HTML 5") + public ServletContextTemplateResolver templateResolver() { + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } + + @Bean + @Description("Thymeleaf template engine with Spring integration") + public SpringTemplateEngine templateEngine() { + final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + final Set dialects = new HashSet<>(); + dialects.add(new CustomDialect()); + templateEngine.setAdditionalDialects(dialects); + return templateEngine; + } + + @Bean + @Description("Spring message resolver") + public MessageSource messageSource() { + final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + } \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/templates/footer.html b/spring-mvc-java/src/main/webapp/WEB-INF/templates/footer.html new file mode 100644 index 0000000000..f72d553303 --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/templates/footer.html @@ -0,0 +1,6 @@ + + + +
© 2013 Footer
+ + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/templates/hello.html b/spring-mvc-java/src/main/webapp/WEB-INF/templates/hello.html new file mode 100644 index 0000000000..1eddd85166 --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/templates/hello.html @@ -0,0 +1,14 @@ + + + + + + + Hi + John ! + Test +
© 2013 The Static + Templates
+ + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/templates/index.html b/spring-mvc-java/src/main/webapp/WEB-INF/templates/index.html new file mode 100644 index 0000000000..9b4159c193 --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/templates/index.html @@ -0,0 +1,36 @@ + + + + +Thymeleaf Spring Example + + + Hello John! +

+
Please confirm your details
+

+
+ + + + + + + + + + + + + + + + +
Firstname :
Lastname :
EmailId :
+
+ + \ No newline at end of file From f8197a54004b1b0c997ef705370fe52ec033baf1 Mon Sep 17 00:00:00 2001 From: vkadapa Date: Fri, 18 Dec 2015 06:46:29 +0530 Subject: [PATCH 18/65] Missed messages.properties --- spring-mvc-java/src/main/resources/messages_en.properties | 1 + 1 file changed, 1 insertion(+) create mode 100644 spring-mvc-java/src/main/resources/messages_en.properties diff --git a/spring-mvc-java/src/main/resources/messages_en.properties b/spring-mvc-java/src/main/resources/messages_en.properties new file mode 100644 index 0000000000..549024372b --- /dev/null +++ b/spring-mvc-java/src/main/resources/messages_en.properties @@ -0,0 +1 @@ +welcome.text=Hello \ No newline at end of file From 8306f357b31e3cb0db5568025e63b8d361ce9743 Mon Sep 17 00:00:00 2001 From: vkadapa Date: Fri, 18 Dec 2015 07:14:51 +0530 Subject: [PATCH 19/65] Modified code to support both thymeleaf and existing viewResolvers --- .../spring/web/config/ClientWebConfig.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java index 50681e88f6..fe31e3581e 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java @@ -15,6 +15,8 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; import org.thymeleaf.dialect.IDialect; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; @@ -39,18 +41,23 @@ public class ClientWebConfig extends WebMvcConfigurerAdapter { } @Bean - public ViewResolver viewResolver() { - /*final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp");*/ - + public ViewResolver thymeleafViewResolver() { final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); - + viewResolver.setOrder(1); return viewResolver; } + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(0); + return bean; + } + @Bean @Description("Thymeleaf template resolver serving HTML 5") public ServletContextTemplateResolver templateResolver() { From f553c8f0497ae11de1b66e0bc12af89bbb8b9cf5 Mon Sep 17 00:00:00 2001 From: vkadapa Date: Fri, 18 Dec 2015 15:51:12 +0530 Subject: [PATCH 20/65] Removed Tomcat Plugin from pom.xml, rename Userdetails to User and moved the controller to web --- spring-mvc-java/pom.xml | 8 --- .../model/{UserDetails.java => User.java} | 64 +++++++++---------- .../spring/web/config/ClientWebConfig.java | 2 - .../{ => web}/controller/UserController.java | 63 +++++++++--------- 4 files changed, 64 insertions(+), 73 deletions(-) rename spring-mvc-java/src/main/java/org/baeldung/model/{UserDetails.java => User.java} (92%) rename spring-mvc-java/src/main/java/org/baeldung/{ => web}/controller/UserController.java (54%) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index a9bbf71ba3..56054b0c47 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -164,14 +164,6 @@ - - org.apache.tomcat.maven - tomcat7-maven-plugin - 2.2 - - / - - diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java b/spring-mvc-java/src/main/java/org/baeldung/model/User.java similarity index 92% rename from spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java rename to spring-mvc-java/src/main/java/org/baeldung/model/User.java index d0b37fae8a..df549cd21d 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/model/UserDetails.java +++ b/spring-mvc-java/src/main/java/org/baeldung/model/User.java @@ -1,32 +1,32 @@ -package org.baeldung.model; - -public class UserDetails { - private String firstname; - private String lastname; - private String emailId; - - public String getFirstname() { - return firstname; - } - - public void setFirstname(final String firstname) { - this.firstname = firstname; - } - - public String getLastname() { - return lastname; - } - - public void setLastname(final String lastname) { - this.lastname = lastname; - } - - public String getEmailId() { - return emailId; - } - - public void setEmailId(final String emailId) { - this.emailId = emailId; - } - -} +package org.baeldung.model; + +public class User { + private String firstname; + private String lastname; + private String emailId; + + public String getFirstname() { + return firstname; + } + + public void setFirstname(final String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(final String lastname) { + this.lastname = lastname; + } + + public String getEmailId() { + return emailId; + } + + public void setEmailId(final String emailId) { + this.emailId = emailId; + } + +} diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java index fe31e3581e..db57b4716b 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java @@ -6,7 +6,6 @@ import java.util.Set; import org.baeldung.dialect.CustomDialect; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import org.springframework.context.support.ResourceBundleMessageSource; @@ -24,7 +23,6 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @EnableWebMvc @Configuration -@ComponentScan("org.baeldung.controller") public class ClientWebConfig extends WebMvcConfigurerAdapter { public ClientWebConfig() { diff --git a/spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java b/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java similarity index 54% rename from spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java rename to spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java index 3203296a17..731424c336 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/controller/UserController.java +++ b/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java @@ -1,31 +1,32 @@ -package org.baeldung.controller; - -import org.baeldung.model.UserDetails; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@Controller -@RequestMapping("/") -public class UserController { - - @RequestMapping(value = "/", method = RequestMethod.GET) - public String showForm(final Model model) { - final UserDetails user = new UserDetails(); - user.setFirstname("John"); - user.setLastname("Roy"); - user.setEmailId("John.Roy@gmail.com"); - model.addAttribute("user", user); - return "index"; - } - - @RequestMapping(value = "/processForm", method = RequestMethod.POST) - public String processForm(@ModelAttribute(value = "user") final UserDetails user, final Model model) { - // Insert userDetails into DB - model.addAttribute("name", user.getFirstname() + " " + user.getLastname()); - return "hello"; - } - -} +package org.baeldung.web.controller; + +import org.baeldung.model.User; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/") +public class UserController { + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String showForm(final Model model) { + final User user = new User(); + user.setFirstname("John"); + user.setLastname("Roy"); + user.setEmailId("John.Roy@gmail.com"); + model.addAttribute("user", user); + return "index"; + } + + @RequestMapping(value = "/processForm", method = RequestMethod.POST) + public String processForm(@ModelAttribute(value = "user") final User user, + final Model model) { + // Insert User into DB + model.addAttribute("name", user.getFirstname() + " " + user.getLastname()); + return "hello"; + } + +} From 1bb2d7c883b21b7c4a16edaae447e768ba5fb047 Mon Sep 17 00:00:00 2001 From: eugenp Date: Fri, 18 Dec 2015 13:14:30 +0200 Subject: [PATCH 21/65] minor cleanup --- spring-mvc-java/pom.xml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 56054b0c47..1a462fabaa 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -1,5 +1,4 @@ - + 4.0.0 org.baeldung spring-mvc-java @@ -101,6 +100,7 @@ ${thymeleaf.version} + spring-mvc-java @@ -109,6 +109,7 @@ true + org.apache.maven.plugins @@ -119,10 +120,12 @@ 1.8 + maven-resources-plugin 2.7 + org.apache.maven.plugins maven-war-plugin From 97ccb915582f2a0b92cc29fb1f258cf0e13be7cd Mon Sep 17 00:00:00 2001 From: gmaipady Date: Sun, 20 Dec 2015 21:43:31 +0530 Subject: [PATCH 22/65] Fixed minor comments --- spring-thymeleaf/README.md | 20 ++++++++++++------- spring-thymeleaf/pom.xml | 20 +++++++++++++++++++ .../org/baeldung/thymeleaf/model/Student.java | 2 +- 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index ef86ae055a..8cb1c2e982 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -7,11 +7,17 @@ ### Build the Project -``` -mvn clean install -``` -Access sample pages using the URLs: -http://localhost:8080/spring-thymeleaf/ -http://localhost:8080/spring-thymeleaf/addStudent/ -http://localhost:8080/spring-thymeleaf/listStudents/ +mvn clean install + +### Run the Project +mvn cargo:run +- **note**: starts on port '8082' + +Access the pages using the URLs: + +http://localhost:8082/spring-thymeleaf/ +http://localhost:8082/spring-thymeleaf/addStudent/ +http://localhost:8082/spring-thymeleaf/listStudents/ + +The first URL is the home page of the application. The home page has links to the other two pages. diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 770f67d59c..1a8dff671e 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -22,6 +22,7 @@ 3.3 2.6 2.18.1 + 1.4.15 @@ -123,6 +124,25 @@ + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + 8082 + + + + diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java index d4d8ea1d6c..f21169dbcf 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java @@ -15,7 +15,7 @@ public class Student implements Serializable { private static final long serialVersionUID = -8582553475226281591L; @NotNull(message = "Student ID is required.") - @Min(value = 1000, message = "Student ID must be atleast 4 digits.") + @Min(value = 1000, message = "Student ID must be at least 4 digits.") private Integer id; @NotNull(message = "Student name is required.") From 2fdedb0e98a1163bc34fb884e52df5c8a4dd28b3 Mon Sep 17 00:00:00 2001 From: sameira Date: Sun, 20 Dec 2015 21:45:36 +0530 Subject: [PATCH 23/65] Updated test cases adding increased timeouts and sleeps to enhance the stability, updated Spring Data Cassandra Version. --- spring-data-cassandra/pom.xml | 2 +- .../cassandra/repository/CQLQueriesIntegrationTest.java | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/spring-data-cassandra/pom.xml b/spring-data-cassandra/pom.xml index 13c5c18529..b2b649a422 100644 --- a/spring-data-cassandra/pom.xml +++ b/spring-data-cassandra/pom.xml @@ -11,7 +11,7 @@ UTF-8 - 1.3.1.RELEASE + 1.3.2.RELEASE 4.2.2.RELEASE 4.11 1.7.12 diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java index f4354a66e2..031b5c0b6f 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java @@ -51,7 +51,7 @@ public class CQLQueriesIntegrationTest { @BeforeClass public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { - EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + EmbeddedCassandraServerHelper.startEmbeddedCassandra(25000); Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); LOGGER.info("Server Started at 127.0.0.1:9142... "); Session session = cluster.connect(); @@ -87,7 +87,7 @@ public class CQLQueriesIntegrationTest { } @Test - public void whenSavingBook_thenAvailableOnRetrieval_usingPreparedStatements() { + public void whenSavingBook_thenAvailableOnRetrieval_usingPreparedStatements() throws InterruptedException { UUID uuid = UUIDs.timeBased(); String insertPreparedCql = "insert into book (id, title, publisher, tags) values (?, ?, ?, ?)"; List singleBookArgsList = new ArrayList<>(); @@ -98,6 +98,8 @@ public class CQLQueriesIntegrationTest { singleBookArgsList.add(ImmutableSet.of("Software")); bookList.add(singleBookArgsList); cassandraTemplate.ingest(insertPreparedCql, bookList); + //This may not be required, just added to avoid any transient issues + Thread.sleep(5000); Select select = QueryBuilder.select().from("book"); Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); assertEquals(uuid, retrievedBook.getId()); From 16599334387d364117dfac3768ed38c788a6bef1 Mon Sep 17 00:00:00 2001 From: sameira Date: Sun, 20 Dec 2015 22:24:54 +0530 Subject: [PATCH 24/65] Adding README.md --- spring-data-cassandra/README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 spring-data-cassandra/README.md diff --git a/spring-data-cassandra/README.md b/spring-data-cassandra/README.md new file mode 100644 index 0000000000..a245ff62a1 --- /dev/null +++ b/spring-data-cassandra/README.md @@ -0,0 +1,15 @@ +## Spring Data Cassandra + +### Relevant Articles: +- [Introduction to Spring Data Cassandra](http://www.baeldung.com/spring-data-cassandra-tutorial) + +### Build the Project with Tests Running +``` +mvn clean install +``` + +### Run Tests Directly +``` +mvn test +``` + From ed8ca6ab8e396988692c6021c7796989f1061204 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 21 Dec 2015 11:34:42 +0200 Subject: [PATCH 25/65] maven upgrades --- apache-fop/pom.xml | 6 +-- core-java-8/pom.xml | 4 +- core-java/pom.xml | 10 ++-- gson/pom.xml | 8 +-- guava/pom.xml | 8 +-- handling-spring-static-resources/pom.xml | 8 +-- httpclient/pom.xml | 8 +-- jackson/pom.xml | 10 ++-- mockito/pom.xml | 8 +-- rest-testing/pom.xml | 10 ++-- sandbox/pom.xml | 8 +-- spring-all/pom.xml | 16 +++--- spring-exceptions/pom.xml | 16 +++--- spring-hibernate3/pom.xml | 16 +++--- spring-hibernate4/pom.xml | 54 +++++++++---------- spring-jpa/pom.xml | 14 ++--- spring-mvc-java/pom.xml | 16 +++--- spring-mvc-no-xml/pom.xml | 8 +-- spring-mvc-xml/pom.xml | 8 +-- spring-rest/pom.xml | 18 +++---- spring-security-basic-auth/pom.xml | 16 +++--- .../pom.xml | 8 +-- spring-security-mvc-custom/pom.xml | 16 +++--- spring-security-mvc-digest-auth/pom.xml | 16 +++--- spring-security-mvc-ldap/pom.xml | 14 ++--- spring-security-mvc-login/pom.xml | 16 +++--- spring-security-mvc-session/pom.xml | 16 +++--- spring-security-rest-basic-auth/pom.xml | 22 ++++---- spring-security-rest-custom/pom.xml | 16 +++--- spring-security-rest-digest-auth/pom.xml | 24 ++++----- spring-security-rest-full/pom.xml | 18 +++---- spring-security-rest/pom.xml | 16 +++--- 32 files changed, 223 insertions(+), 229 deletions(-) diff --git a/apache-fop/pom.xml b/apache-fop/pom.xml index 13fc2257cf..95505f9374 100644 --- a/apache-fop/pom.xml +++ b/apache-fop/pom.xml @@ -37,7 +37,7 @@ junit - junit-dep + junit ${junit.version} test @@ -151,7 +151,7 @@ 5.1.34 - 2.4.4 + 2.5.5 1.7.9 @@ -166,7 +166,7 @@ 1.3 - 4.11 + 4.12 1.10.19 4.4 diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 9db2562fb4..07d3bcd146 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -98,14 +98,14 @@ - 1.7.12 + 1.7.13 1.0.13 5.1.3.Final - 18.0 + 19.0 3.4 diff --git a/core-java/pom.xml b/core-java/pom.xml index c6f2b32cd8..b439b41f22 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -79,7 +79,7 @@ junit - junit-dep + junit ${junit.version} test @@ -152,22 +152,22 @@ 5.1.35 - 2.4.4 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/gson/pom.xml b/gson/pom.xml index 500d14c40c..c0640abcbf 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -53,7 +53,7 @@ junit - junit-dep + junit ${junit.version} test @@ -124,19 +124,19 @@ 2.3 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/guava/pom.xml b/guava/pom.xml index 78c5a14e41..2b07be71bf 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -34,7 +34,7 @@ junit - junit-dep + junit ${junit.version} test @@ -102,19 +102,19 @@ 5.1.35 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml index 67591e1844..677d705932 100644 --- a/handling-spring-static-resources/pom.xml +++ b/handling-spring-static-resources/pom.xml @@ -190,22 +190,22 @@ - 2.4.4 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/httpclient/pom.xml b/httpclient/pom.xml index a6df3842fd..0098c40d52 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -89,7 +89,7 @@ junit - junit-dep + junit ${junit.version} test @@ -157,19 +157,19 @@ 5.1.35 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/jackson/pom.xml b/jackson/pom.xml index b2c2465436..9996330361 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -72,7 +72,7 @@ junit - junit-dep + junit ${junit.version} test @@ -140,22 +140,22 @@ 5.1.35 - 2.4.4 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/mockito/pom.xml b/mockito/pom.xml index a97a017c5c..a73eea7647 100644 --- a/mockito/pom.xml +++ b/mockito/pom.xml @@ -28,7 +28,7 @@ junit - junit-dep + junit ${junit.version} test @@ -96,19 +96,19 @@ 5.1.35 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/rest-testing/pom.xml b/rest-testing/pom.xml index 488a8a3cdb..b8fdc50a01 100644 --- a/rest-testing/pom.xml +++ b/rest-testing/pom.xml @@ -78,7 +78,7 @@ junit - junit-dep + junit ${junit.version} test @@ -141,22 +141,22 @@ 4.1.5.RELEASE - 2.4.4 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 5.1.3.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/sandbox/pom.xml b/sandbox/pom.xml index 55cb9f11f2..95b2df2cb3 100644 --- a/sandbox/pom.xml +++ b/sandbox/pom.xml @@ -73,7 +73,7 @@ junit - junit-dep + junit ${junit.version} test @@ -141,10 +141,10 @@ 5.1.35 - 2.4.4 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 @@ -156,7 +156,7 @@ 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 0551abe5a5..16ff340d81 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -127,7 +127,7 @@ junit - junit-dep + junit ${junit.version} test @@ -221,29 +221,29 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 3.20.0-GA 1.2 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index f4c0acec85..324b7475b3 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -105,7 +105,7 @@ junit - junit-dep + junit ${junit.version} test @@ -203,30 +203,30 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 3.20.0-GA 1.2 4.3.11.Final - 5.1.36 + 5.1.37 7.0.42 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-hibernate3/pom.xml b/spring-hibernate3/pom.xml index 29682a97c3..d88358168f 100644 --- a/spring-hibernate3/pom.xml +++ b/spring-hibernate3/pom.xml @@ -73,7 +73,7 @@ junit - junit-dep + junit ${junit.version} test @@ -162,29 +162,29 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 3.20.0-GA 3.6.10.Final - 5.1.36 + 5.1.37 7.0.47 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml index 711f9b3533..d24024f151 100644 --- a/spring-hibernate4/pom.xml +++ b/spring-hibernate4/pom.xml @@ -102,6 +102,13 @@ test + + junit + junit + ${junit.version} + test + + org.springframework.security spring-security-test @@ -109,6 +116,13 @@ test + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + junit junit-dep @@ -187,55 +201,35 @@ - + - 4.2.2.RELEASE - 4.0.2.RELEASE - 1.9.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE + 1.9.2.RELEASE + 3.20.0-GA 4.3.11.Final ${hibernate.version} - 5.1.36 + 5.1.37 7.0.42 1.1 2.2.4 - 1.7.12 + 1.7.13 1.1.3 - 4.3.2.Final + 5.2.2.Final - 18.0 + 19.0 3.4 @@ -257,4 +251,4 @@ - \ No newline at end of file + diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index f065fe1a81..63d97c337b 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -85,7 +85,7 @@ junit - junit-dep + junit ${junit.version} test @@ -174,29 +174,29 @@ - 4.2.2.RELEASE + 4.2.4.RELEASE 4.0.2.RELEASE 3.20.0-GA 4.3.11.Final - 5.1.36 + 5.1.37 1.7.2.RELEASE - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 1a462fabaa..ef6ac59dd4 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -60,7 +60,7 @@ junit - junit-dep + junit ${junit.version} test @@ -171,23 +171,23 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 2.1.4.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 4.5 diff --git a/spring-mvc-no-xml/pom.xml b/spring-mvc-no-xml/pom.xml index ecb159f82e..da71a699db 100644 --- a/spring-mvc-no-xml/pom.xml +++ b/spring-mvc-no-xml/pom.xml @@ -67,7 +67,7 @@ junit - junit-dep + junit ${junit.version} test @@ -144,15 +144,15 @@ - 4.2.2.RELEASE + 4.2.4.RELEASE - 1.7.12 + 1.7.13 1.1.3 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 378d2be339..896d744e99 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -73,7 +73,7 @@ junit - junit-dep + junit ${junit.version} test @@ -146,15 +146,15 @@ - 4.2.2.RELEASE + 4.2.4.RELEASE - 1.7.12 + 1.7.13 1.1.3 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 7bc0905542..e2cf9d7c3e 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -128,7 +128,7 @@ junit - junit-dep + junit ${junit.version} test @@ -229,27 +229,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 2.5.1 + 2.5.5 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 @@ -258,7 +258,7 @@ 2.4.1 - 1.7.12 + 1.7.13 1.1.3 diff --git a/spring-security-basic-auth/pom.xml b/spring-security-basic-auth/pom.xml index 72914dd0d5..6abefbd7ec 100644 --- a/spring-security-basic-auth/pom.xml +++ b/spring-security-basic-auth/pom.xml @@ -130,7 +130,7 @@ junit - junit-dep + junit ${junit.version} test @@ -225,27 +225,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-login-and-registration/pom.xml b/spring-security-login-and-registration/pom.xml index df7e639660..ffa8be484b 100644 --- a/spring-security-login-and-registration/pom.xml +++ b/spring-security-login-and-registration/pom.xml @@ -235,10 +235,10 @@ 1.7 4.1.6.RELEASE - 4.0.2.RELEASE + 4.0.3.RELEASE - 1.7.12 + 1.7.13 1.1.3 @@ -251,10 +251,10 @@ 1.8.0.RELEASE - 18.0 + 19.0 - 1.4.16 + 1.4.17 3.3 2.6 2.18.1 diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index d6ac323104..2e2d434fb2 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -135,7 +135,7 @@ junit - junit-dep + junit ${junit.version} test @@ -230,27 +230,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.5 diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index f7ca086881..2dce2835f5 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -130,7 +130,7 @@ junit - junit-dep + junit ${junit.version} test @@ -225,27 +225,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index a11bc4c374..00165bd740 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -87,27 +87,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index 1f824f5003..3d76fcb22f 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -127,7 +127,7 @@ junit - junit-dep + junit ${junit.version} test @@ -222,27 +222,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index f6cd575d57..c9a919e684 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -135,7 +135,7 @@ junit - junit-dep + junit ${junit.version} test @@ -230,27 +230,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.5 diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index a6d5b36381..1fbeeaa9a9 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -189,7 +189,7 @@ junit - junit-dep + junit ${junit.version} test @@ -287,40 +287,40 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 4.4.3 + 4.4.4 4.5.1 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 - 2.6.0 + 2.8.0 3.3 2.6 2.19 - 1.4.16 + 1.4.17 diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index cfe3afbc54..20984ba6dd 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -140,7 +140,7 @@ junit - junit-dep + junit ${junit.version} test @@ -258,27 +258,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-rest-digest-auth/pom.xml b/spring-security-rest-digest-auth/pom.xml index 1bc107dda2..d20220ac36 100644 --- a/spring-security-rest-digest-auth/pom.xml +++ b/spring-security-rest-digest-auth/pom.xml @@ -177,7 +177,7 @@ junit - junit-dep + junit ${junit.version} test @@ -274,43 +274,43 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 4.4.3 + 4.4.4 4.5.1 - 1.7.12 + 1.7.13 1.1.3 - 2.5.1 + 2.5.5 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 - 2.6.0 + 2.8.0 3.3 2.6 2.19 - 1.4.16 + 1.4.17 diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index 04ade99195..bed716897b 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -242,7 +242,7 @@ junit - junit-dep + junit ${junit.version} test @@ -426,32 +426,32 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 1.7.2.RELEASE - 2.5.1 + 2.5.5 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 4.4.1 diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 4fd64b5289..42381bf607 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -142,7 +142,7 @@ junit - junit-dep + junit ${junit.version} test @@ -250,27 +250,27 @@ - 4.2.2.RELEASE - 4.0.2.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 4.3.11.Final - 5.1.36 + 5.1.37 - 1.7.12 + 1.7.13 1.1.3 - 5.2.1.Final + 5.2.2.Final - 18.0 + 19.0 3.4 1.3 - 4.11 + 4.12 1.10.19 From cb083e23c87b815fc8346147fc1ead90c269c412 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 21 Dec 2015 11:37:37 +0200 Subject: [PATCH 26/65] new set test --- .../org/baeldung/guava/GuavaCollectionTypesTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java index 26d3fa90ca..2eb5141f8d 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java @@ -148,6 +148,15 @@ public class GuavaCollectionTypesTest { assertThat(intersection, containsInAnyOrder('b', 'c')); } + @Test + public void whenCalculatingSetSymetricDifference_thenCorrect() { + final Set first = ImmutableSet.of('a', 'b', 'c'); + final Set second = ImmutableSet.of('b', 'c', 'd'); + + final Set intersection = Sets.symmetricDifference(first, second); + assertThat(intersection, containsInAnyOrder('a', 'd')); + } + @Test public void whenCalculatingPowerSet_thenCorrect() { final Set chars = ImmutableSet.of('a', 'b'); From 8c7962a3f7674a0b3aa9703ae7b12b4b3fda03bc Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 21 Dec 2015 11:53:17 +0200 Subject: [PATCH 27/65] fixes - spelling and security work --- .../org/baeldung/guava/GuavaCollectionTypesTest.java | 2 +- .../org/baeldung/security/MyUserDetailsService.java | 10 +++------- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java index 2eb5141f8d..9c38afbcc2 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java @@ -149,7 +149,7 @@ public class GuavaCollectionTypesTest { } @Test - public void whenCalculatingSetSymetricDifference_thenCorrect() { + public void whenCalculatingSetSymmetricDifference_thenCorrect() { final Set first = ImmutableSet.of('a', 'b', 'c'); final Set second = ImmutableSet.of('b', 'c', 'd'); diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java index 567fa7717d..d4b77878be 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -1,13 +1,11 @@ package org.baeldung.security; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; import javax.servlet.http.HttpServletRequest; -import org.baeldung.persistence.dao.RoleRepository; import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.model.Privilege; import org.baeldung.persistence.model.Role; @@ -28,9 +26,6 @@ public class MyUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; - @Autowired - private RoleRepository roleRepository; - @Autowired private LoginAttemptService loginAttemptService; @@ -53,7 +48,7 @@ public class MyUserDetailsService implements UserDetailsService { try { final User user = userRepository.findByEmail(email); if (user == null) { - return new org.springframework.security.core.userdetails.User(" ", " ", true, true, true, true, getAuthorities(Arrays.asList(roleRepository.findByName("ROLE_USER")))); + throw new UsernameNotFoundException("No user found with username: " + email); } return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, getAuthorities(user.getRoles())); @@ -90,8 +85,9 @@ public class MyUserDetailsService implements UserDetailsService { private String getClientIP() { final String xfHeader = request.getHeader("X-Forwarded-For"); - if (xfHeader == null) + if (xfHeader == null) { return request.getRemoteAddr(); + } return xfHeader.split(",")[0]; } } From dc104022acbb9e2bc1f2716f0702cd85663eaf25 Mon Sep 17 00:00:00 2001 From: oborkovskyi Date: Mon, 21 Dec 2015 13:40:09 +0200 Subject: [PATCH 28/65] Removed extra files --- guava18/.classpath | 36 ------------------- ...e.wst.jsdt.core.javascriptValidator.launch | 7 ---- guava18/.gitignore | 13 ------- guava18/.project | 36 ------------------- guava18/.springBeans | 14 -------- 5 files changed, 106 deletions(-) delete mode 100644 guava18/.classpath delete mode 100644 guava18/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch delete mode 100644 guava18/.gitignore delete mode 100644 guava18/.project delete mode 100644 guava18/.springBeans diff --git a/guava18/.classpath b/guava18/.classpath deleted file mode 100644 index 8ebf6d9c31..0000000000 --- a/guava18/.classpath +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/guava18/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/guava18/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/guava18/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/guava18/.gitignore b/guava18/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/guava18/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.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/guava18/.project b/guava18/.project deleted file mode 100644 index 829dc83809..0000000000 --- a/guava18/.project +++ /dev/null @@ -1,36 +0,0 @@ - - - guava - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - - diff --git a/guava18/.springBeans b/guava18/.springBeans deleted file mode 100644 index a79097f40d..0000000000 --- a/guava18/.springBeans +++ /dev/null @@ -1,14 +0,0 @@ - - - 1 - - - - - - - src/main/webapp/WEB-INF/api-servlet.xml - - - - From c244ea7c6b5610997ebed45a11ba180772c0096a Mon Sep 17 00:00:00 2001 From: oborkovskyi Date: Mon, 21 Dec 2015 13:52:26 +0200 Subject: [PATCH 29/65] Splitted test to grouped by methods used tests. --- .../baeldung/guava/FluentIterableTest.java | 80 ++++++++ .../baeldung/guava/GuavaMiscUtilsTest.java | 41 ++++ .../java/com/baeldung/guava/GuavaTest.java | 177 ------------------ .../com/baeldung/guava/MoreExecutorsTest.java | 51 +++++ .../com/baeldung/guava/MoreObjectsTest.java | 33 ++++ 5 files changed, 205 insertions(+), 177 deletions(-) create mode 100644 guava18/src/test/java/com/baeldung/guava/FluentIterableTest.java create mode 100644 guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java delete mode 100644 guava18/src/test/java/com/baeldung/guava/GuavaTest.java create mode 100644 guava18/src/test/java/com/baeldung/guava/MoreExecutorsTest.java create mode 100644 guava18/src/test/java/com/baeldung/guava/MoreObjectsTest.java diff --git a/guava18/src/test/java/com/baeldung/guava/FluentIterableTest.java b/guava18/src/test/java/com/baeldung/guava/FluentIterableTest.java new file mode 100644 index 0000000000..82552fca8f --- /dev/null +++ b/guava18/src/test/java/com/baeldung/guava/FluentIterableTest.java @@ -0,0 +1,80 @@ +package com.baeldung.guava; + +import com.baeldung.guava.entity.User; +import com.google.common.base.Functions; +import com.google.common.base.Joiner; +import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.CoreMatchers.equalTo; + +public class FluentIterableTest { + + private static final int ADULT_AGE = 18; + + @Test + public void whenFilteringByAge_shouldFilterOnlyAdultUsers() throws Exception { + List users = new ArrayList<>(); + users.add(new User(1L, "John", 45)); + users.add(new User(2L, "Michael", 27)); + users.add(new User(3L, "Max", 16)); + users.add(new User(4L, "Bob", 10)); + users.add(new User(5L, "Bill", 65)); + + Predicate byAge = input -> input.getAge() > ADULT_AGE; + + List results = FluentIterable.from(users) + .filter(byAge) + .transform(Functions.toStringFunction()) + .toList(); + + Assert.assertThat(results.size(), equalTo(3)); + } + + @Test + public void whenCreatingFluentIterableFromArray_shouldContainAllUsers() throws Exception { + User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; + FluentIterable users = FluentIterable.of(usersArray); + + Assert.assertThat(users.size(), equalTo(2)); + } + + @Test + public void whenAppendingElementsToFluentIterable_shouldContainAllUsers() throws Exception { + User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; + + FluentIterable users = FluentIterable.of(usersArray).append( + new User(3L, "Bob", 23), + new User(4L, "Bill", 17) + ); + + Assert.assertThat(users.size(), equalTo(4)); + } + + @Test + public void whenAppendingListToFluentIterable_shouldContainAllUsers() throws Exception { + User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; + + List usersList = new ArrayList<>(); + usersList.add(new User(3L, "David", 32)); + + FluentIterable users = FluentIterable.of(usersArray).append(usersList); + + Assert.assertThat(users.size(), equalTo(3)); + } + + @Test + public void whenJoiningFluentIterableElements_shouldOutputAllUsers() throws Exception { + User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; + + FluentIterable users = FluentIterable.of(usersArray); + + Assert.assertThat(users.join(Joiner.on("; ")), + equalTo("User{id=1, name=John, age=45}; User{id=2, name=Max, age=15}")); + } +} \ No newline at end of file diff --git a/guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java new file mode 100644 index 0000000000..db82ea6da8 --- /dev/null +++ b/guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java @@ -0,0 +1,41 @@ +package com.baeldung.guava; + +import com.google.common.hash.HashCode; +import com.google.common.hash.Hashing; +import com.google.common.net.InetAddresses; +import org.junit.Assert; +import org.junit.Test; + +import java.net.InetAddress; +import java.util.concurrent.ConcurrentHashMap; + +import static org.hamcrest.CoreMatchers.equalTo; + +public class GuavaMiscUtilsTest { + @Test + public void whenHashingData_shouldReturnCorrectHashCode() throws Exception { + int receivedData = 123; + + HashCode hashCode = Hashing.crc32c().hashInt(receivedData); + Assert.assertThat(hashCode.toString(), equalTo("495be649")); + } + + @Test + public void whenDecrementingIpAddress_shouldReturnOneLessIpAddress() throws Exception { + InetAddress address = InetAddress.getByName("127.0.0.5"); + InetAddress decrementedAddress = InetAddresses.decrement(address); + + Assert.assertThat(decrementedAddress.toString(), equalTo("/127.0.0.4")); + } + + @Test + public void whenExecutingRunnableInThread_shouldLogThreadExecution() throws Exception { + ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); + Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); + + Thread t = new Thread(logThreadRun); + t.run(); + + Assert.assertTrue(threadExecutions.get("main")); + } +} diff --git a/guava18/src/test/java/com/baeldung/guava/GuavaTest.java b/guava18/src/test/java/com/baeldung/guava/GuavaTest.java deleted file mode 100644 index 5d1d1c074a..0000000000 --- a/guava18/src/test/java/com/baeldung/guava/GuavaTest.java +++ /dev/null @@ -1,177 +0,0 @@ -import com.baeldung.guava.entity.Administrator; -import com.baeldung.guava.entity.Player; -import com.baeldung.guava.entity.User; -import com.google.common.base.Functions; -import com.google.common.base.Joiner; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; -import com.google.common.hash.HashCode; -import com.google.common.hash.Hashing; -import com.google.common.net.InetAddresses; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; -import org.junit.Assert; -import org.junit.Test; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.*; - -import static org.hamcrest.CoreMatchers.equalTo; - -public class GuavaTest { - - private static final int ADULT_AGE = 18; - - @Test - public void whenToString_shouldIncludeAllFields() throws Exception { - User user = new User(12L, "John Doe", 25); - - Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}")); - } - - @Test - public void whenPlayerToString_shouldCallParentToString() throws Exception { - User user = new Player(12L, "John Doe", 25); - - Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}")); - } - - @Test - public void whenAdministratorToString_shouldExecuteAdministratorToString() throws Exception { - User user = new Administrator(12L, "John Doe", 25); - - Assert.assertThat(user.toString(), equalTo("Administrator{id=12, name=John Doe, age=25}")); - } - - @Test - public void whenFilteringByAge_shouldFilterOnlyAdultUsers() throws Exception { - List users = new ArrayList<>(); - users.add(new User(1L, "John", 45)); - users.add(new User(2L, "Michael", 27)); - users.add(new User(3L, "Max", 16)); - users.add(new User(4L, "Bob", 10)); - users.add(new User(5L, "Bill", 65)); - - Predicate byAge = input -> input.getAge() > ADULT_AGE; - - List results = FluentIterable.from(users) - .filter(byAge) - .transform(Functions.toStringFunction()) - .toList(); - - Assert.assertThat(results.size(), equalTo(3)); - } - - @Test - public void whenCreatingFluentIterableFromArray_shouldContainAllUsers() throws Exception { - User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)} ; - FluentIterable users = FluentIterable.of(usersArray); - - Assert.assertThat(users.size(), equalTo(2)); - } - - @Test - public void whenAppendingElementsToFluentIterable_shouldContainAllUsers() throws Exception { - User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; - - FluentIterable users = FluentIterable.of(usersArray).append( - new User(3L, "Bob", 23), - new User(4L, "Bill", 17) - ); - - Assert.assertThat(users.size(), equalTo(4)); - } - - @Test - public void whenAppendingListToFluentIterable_shouldContainAllUsers() throws Exception { - User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; - - List usersList = new ArrayList<>(); - usersList.add(new User(3L, "David", 32)); - - FluentIterable users = FluentIterable.of(usersArray).append(usersList); - - Assert.assertThat(users.size(), equalTo(3)); - } - - @Test - public void whenJoiningFluentIterableElements_shouldOutputAllUsers() throws Exception { - User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)}; - - FluentIterable users = FluentIterable.of(usersArray); - - Assert.assertThat(users.join(Joiner.on("; ")), - equalTo("User{id=1, name=John, age=45}; User{id=2, name=Max, age=15}")); - } - - @Test - public void whenHashingData_shouldReturnCorrectHashCode() throws Exception { - int receivedData = 123; - - HashCode hashCode = Hashing.crc32c().hashInt(receivedData); - Assert.assertThat(hashCode.toString(), equalTo("495be649")); - } - - @Test - public void whenDecrementingIpAddress_shouldReturnOneLessIpAddress() throws Exception { - InetAddress address = InetAddress.getByName("127.0.0.5"); - InetAddress decrementedAddress = InetAddresses.decrement(address); - - Assert.assertThat(decrementedAddress.toString(), equalTo("/127.0.0.4")); - - } - - @Test - public void whenExecutingRunnableInThread_shouldLogThreadExecution() throws Exception { - ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); - Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); - - Thread t = new Thread(logThreadRun); - t.run(); - - Assert.assertTrue(threadExecutions.get("main")); - } - - @Test - public void whenExecutingRunnableInThreadPool_shouldLogAllThreadsExecutions() throws Exception { - ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); - - Runnable logThreadRun= () -> threadExecutions.put(Thread.currentThread().getName(), true); - - ExecutorService executorService = Executors.newFixedThreadPool(2); - executorService.submit(logThreadRun); - executorService.submit(logThreadRun); - executorService.shutdown(); - - executorService.awaitTermination(100, TimeUnit.MILLISECONDS); - - Assert.assertTrue(threadExecutions.get("pool-1-thread-1")); - Assert.assertTrue(threadExecutions.get("pool-1-thread-2")); - } - - @Test - public void whenExecutingRunnableInDirectExecutor_shouldLogThreadExecution() throws Exception { - ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); - - Runnable logThreadRun= () -> threadExecutions.put(Thread.currentThread().getName(), true); - - Executor executor = MoreExecutors.directExecutor(); - executor.execute(logThreadRun); - - Assert.assertTrue(threadExecutions.get("main")); - } - - @Test - public void whenExecutingRunnableInListeningExecutor_shouldLogThreadExecution() throws Exception { - ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); - - Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); - - ListeningExecutorService executor = MoreExecutors.newDirectExecutorService(); - executor.execute(logThreadRun); - - Assert.assertTrue(threadExecutions.get("main")); - } -} \ No newline at end of file diff --git a/guava18/src/test/java/com/baeldung/guava/MoreExecutorsTest.java b/guava18/src/test/java/com/baeldung/guava/MoreExecutorsTest.java new file mode 100644 index 0000000000..ec173499f1 --- /dev/null +++ b/guava18/src/test/java/com/baeldung/guava/MoreExecutorsTest.java @@ -0,0 +1,51 @@ +package com.baeldung.guava; + +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import org.junit.Assert; +import org.junit.Test; + +import java.util.concurrent.*; + +public class MoreExecutorsTest { + @Test + public void whenExecutingRunnableInThreadPool_shouldLogAllThreadsExecutions() throws Exception { + ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); + + Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); + + ExecutorService executorService = Executors.newFixedThreadPool(2); + executorService.submit(logThreadRun); + executorService.submit(logThreadRun); + executorService.shutdown(); + + executorService.awaitTermination(100, TimeUnit.MILLISECONDS); + + Assert.assertTrue(threadExecutions.get("pool-1-thread-1")); + Assert.assertTrue(threadExecutions.get("pool-1-thread-2")); + } + + @Test + public void whenExecutingRunnableInDirectExecutor_shouldLogThreadExecution() throws Exception { + ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); + + Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); + + Executor executor = MoreExecutors.directExecutor(); + executor.execute(logThreadRun); + + Assert.assertTrue(threadExecutions.get("main")); + } + + @Test + public void whenExecutingRunnableInListeningExecutor_shouldLogThreadExecution() throws Exception { + ConcurrentHashMap threadExecutions = new ConcurrentHashMap<>(); + + Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true); + + ListeningExecutorService executor = MoreExecutors.newDirectExecutorService(); + executor.execute(logThreadRun); + + Assert.assertTrue(threadExecutions.get("main")); + } +} diff --git a/guava18/src/test/java/com/baeldung/guava/MoreObjectsTest.java b/guava18/src/test/java/com/baeldung/guava/MoreObjectsTest.java new file mode 100644 index 0000000000..5e46b5aba9 --- /dev/null +++ b/guava18/src/test/java/com/baeldung/guava/MoreObjectsTest.java @@ -0,0 +1,33 @@ +package com.baeldung.guava; + +import com.baeldung.guava.entity.Administrator; +import com.baeldung.guava.entity.Player; +import com.baeldung.guava.entity.User; +import org.junit.Assert; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.equalTo; + +public class MoreObjectsTest { + + @Test + public void whenToString_shouldIncludeAllFields() throws Exception { + User user = new User(12L, "John Doe", 25); + + Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}")); + } + + @Test + public void whenPlayerToString_shouldCallParentToString() throws Exception { + User user = new Player(12L, "John Doe", 25); + + Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}")); + } + + @Test + public void whenAdministratorToString_shouldExecuteAdministratorToString() throws Exception { + User user = new Administrator(12L, "John Doe", 25); + + Assert.assertThat(user.toString(), equalTo("Administrator{id=12, name=John Doe, age=25}")); + } +} From 6dcd2ff8e5a7a46bb7818690e16f59d01526530f Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 22 Dec 2015 17:43:44 +0200 Subject: [PATCH 30/65] add some gson deserialization examples --- .../baeldung/gson/deserialization/Foo.java | 26 ++++++++++++------ .../deserialization/FooInstanceCreator.java | 14 ++++++++++ .../gson/deserialization/FooWithInner.java | 24 +++++++++++++++++ .../test/GsonDeserializationTest.java | 27 +++++++++++++++++++ 4 files changed, 83 insertions(+), 8 deletions(-) create mode 100644 gson/src/test/java/org/baeldung/gson/deserialization/FooInstanceCreator.java create mode 100644 gson/src/test/java/org/baeldung/gson/deserialization/FooWithInner.java diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java b/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java index 64720f63f9..84f8aaef13 100644 --- a/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java +++ b/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java @@ -9,6 +9,10 @@ public class Foo { this.stringValue = stringValue; } + public Foo(final String stringValue) { + this.stringValue = stringValue; + } + public Foo() { super(); } @@ -19,27 +23,33 @@ public class Foo { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + intValue; - result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode()); + result = (prime * result) + intValue; + result = (prime * result) + ((stringValue == null) ? 0 : stringValue.hashCode()); return result; } @Override public boolean equals(final Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } final Foo other = (Foo) obj; - if (intValue != other.intValue) + if (intValue != other.intValue) { return false; + } if (stringValue == null) { - if (other.stringValue != null) + if (other.stringValue != null) { return false; - } else if (!stringValue.equals(other.stringValue)) + } + } else if (!stringValue.equals(other.stringValue)) { return false; + } return true; } diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/FooInstanceCreator.java b/gson/src/test/java/org/baeldung/gson/deserialization/FooInstanceCreator.java new file mode 100644 index 0000000000..4df3986ec3 --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/deserialization/FooInstanceCreator.java @@ -0,0 +1,14 @@ +package org.baeldung.gson.deserialization; + +import java.lang.reflect.Type; + +import com.google.gson.InstanceCreator; + +public class FooInstanceCreator implements InstanceCreator { + + @Override + public Foo createInstance(Type type) { + return new Foo("sample"); + } + +} diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/FooWithInner.java b/gson/src/test/java/org/baeldung/gson/deserialization/FooWithInner.java new file mode 100644 index 0000000000..705e534e77 --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/deserialization/FooWithInner.java @@ -0,0 +1,24 @@ +package org.baeldung.gson.deserialization; + +public class FooWithInner { + public int intValue; + public String stringValue; + public InnerFoo innerFoo; + + public FooWithInner(int intValue, String stringValue, String name) { + super(); + this.intValue = intValue; + this.stringValue = stringValue; + this.innerFoo = new InnerFoo(name); + } + + public class InnerFoo { + public String name; + + public InnerFoo(String name) { + super(); + this.name = name; + } + + } +} diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java b/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java index 342b3096d7..072a25e749 100644 --- a/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java +++ b/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java @@ -12,6 +12,8 @@ import java.util.Collection; import org.baeldung.gson.deserialization.Foo; import org.baeldung.gson.deserialization.FooDeserializerFromJsonWithDifferentFields; +import org.baeldung.gson.deserialization.FooInstanceCreator; +import org.baeldung.gson.deserialization.FooWithInner; import org.baeldung.gson.deserialization.GenericFoo; import org.junit.Test; @@ -108,4 +110,29 @@ public class GsonDeserializationTest { assertEquals(targetObject.stringValue, "seven"); } + // new examples + + @Test + public void whenDeserializingToNestedObjects_thenCorrect() { + final String json = "{\"intValue\":1,\"stringValue\":\"one\",\"innerFoo\":{\"name\":\"inner\"}}"; + + final FooWithInner targetObject = new Gson().fromJson(json, FooWithInner.class); + + assertEquals(targetObject.intValue, 1); + assertEquals(targetObject.stringValue, "one"); + assertEquals(targetObject.innerFoo.name, "inner"); + } + + @Test + public void whenDeserializingUsingInstanceCreator_thenCorrect() { + final String json = "{\"intValue\":1}"; + + final GsonBuilder gsonBldr = new GsonBuilder(); + gsonBldr.registerTypeAdapter(Foo.class, new FooInstanceCreator()); + final Foo targetObject = gsonBldr.create().fromJson(json, Foo.class); + + assertEquals(targetObject.intValue, 1); + assertEquals(targetObject.stringValue, "sample"); + } + } From 17d5f4a920cb62fb895cce7f0c525bdacdac36df Mon Sep 17 00:00:00 2001 From: Devendra Desale Date: Wed, 23 Dec 2015 14:17:31 +0530 Subject: [PATCH 31/65] updated header to csv --- .../org/baeldung/spring_batch_intro/App.java | 2 +- .../spring_batch_intro/SpringBatchConfig.java | 1 + .../src/main/resources/input/record.csv | 1 + .../src/main/resources/spring-batch-intro.xml | 31 +++++++------------ spring-batch-intro/xml/output.xml | 2 +- 5 files changed, 16 insertions(+), 21 deletions(-) diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java index db963fff20..d6af37595c 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java @@ -27,7 +27,7 @@ public class App { try { JobExecution execution = jobLauncher.run(job, new JobParameters()); System.out.println("Job Status : " + execution.getStatus()); - System.out.println("Job completed"); + System.out.println("Job succeeded"); } catch (Exception e) { e.printStackTrace(); System.out.println("Job failed"); diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java index f0e3b364b6..a024cbc04e 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java +++ b/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java @@ -50,6 +50,7 @@ public class SpringBatchConfig { DefaultLineMapper lineMapper = new DefaultLineMapper(); lineMapper.setLineTokenizer(tokenizer); lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); + reader.setLinesToSkip(1); reader.setLineMapper(lineMapper); return reader; } diff --git a/spring-batch-intro/src/main/resources/input/record.csv b/spring-batch-intro/src/main/resources/input/record.csv index 3a1437eed5..e554becb2a 100644 --- a/spring-batch-intro/src/main/resources/input/record.csv +++ b/spring-batch-intro/src/main/resources/input/record.csv @@ -1,3 +1,4 @@ +username, user_id, transaction_date, transaction_amount devendra, 1234, 31/10/2015, 10000 john, 2134, 3/12/2015, 12321 robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch-intro/src/main/resources/spring-batch-intro.xml b/spring-batch-intro/src/main/resources/spring-batch-intro.xml index 3b1f11521f..93606d232f 100644 --- a/spring-batch-intro/src/main/resources/spring-batch-intro.xml +++ b/spring-batch-intro/src/main/resources/spring-batch-intro.xml @@ -1,18 +1,15 @@ - + http://www.springframework.org/schema/batch/spring-batch-3.0.xsd + http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans-4.2.xsd +"> - - + - @@ -20,23 +17,21 @@ + value="username,userid,transaction_date,transaction_amount" /> - + - + - + @@ -45,13 +40,11 @@ - org.baeldung.spring_batch_intro.model.Transaction - + org.baeldung.spring_batch_intro.model.Transaction - diff --git a/spring-batch-intro/xml/output.xml b/spring-batch-intro/xml/output.xml index 9e57fa38f2..acf4969341 100644 --- a/spring-batch-intro/xml/output.xml +++ b/spring-batch-intro/xml/output.xml @@ -1 +1 @@ -10000.02015-10-31T00:00:00+08:001234devendra12321.02015-12-03T00:00:00+08:002134john23411.02015-02-02T00:00:00+08:002134robin \ No newline at end of file +10000.02015-10-31T00:00:00+05:301234devendra12321.02015-12-03T00:00:00+05:302134john23411.02015-02-02T00:00:00+05:302134robin \ No newline at end of file From ff053d279d09ff90ef2a5e186c463705167af50e Mon Sep 17 00:00:00 2001 From: eugenp Date: Thu, 24 Dec 2015 11:39:47 +0200 Subject: [PATCH 32/65] minor cleanup --- spring-data-cassandra/.classpath | 31 +++++++ spring-data-cassandra/.project | 29 ++++++ .../cassandra/config/CassandraConfig.java | 6 +- .../spring/data/cassandra/model/Book.java | 22 +++-- .../cassandra/repository/BookRepository.java | 2 + .../BookRepositoryIntegrationTest.java | 63 +++++++------ .../repository/CQLQueriesIntegrationTest.java | 73 ++++++++------- .../CassandraTemplateIntegrationTest.java | 88 ++++++++++--------- spring-data-mongodb/.classpath | 37 ++++++++ spring-data-mongodb/.project | 29 ++++++ spring-mvc-java/pom.xml | 4 +- 11 files changed, 269 insertions(+), 115 deletions(-) create mode 100644 spring-data-cassandra/.classpath create mode 100644 spring-data-cassandra/.project create mode 100644 spring-data-mongodb/.classpath create mode 100644 spring-data-mongodb/.project diff --git a/spring-data-cassandra/.classpath b/spring-data-cassandra/.classpath new file mode 100644 index 0000000000..698778fef3 --- /dev/null +++ b/spring-data-cassandra/.classpath @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-data-cassandra/.project b/spring-data-cassandra/.project new file mode 100644 index 0000000000..239fa4f002 --- /dev/null +++ b/spring-data-cassandra/.project @@ -0,0 +1,29 @@ + + + spring-data-cassandra + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java index 5f2c4c6d47..2edd5551a5 100644 --- a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java +++ b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/config/CassandraConfig.java @@ -17,8 +17,8 @@ import org.springframework.data.cassandra.repository.config.EnableCassandraRepos @PropertySource(value = { "classpath:cassandra.properties" }) @EnableCassandraRepositories(basePackages = "org.baeldung.spring.data.cassandra.repository") public class CassandraConfig extends AbstractCassandraConfiguration { - private static final Log LOGGER = LogFactory.getLog(CassandraConfig.class); + @Autowired private Environment environment; @@ -27,15 +27,17 @@ public class CassandraConfig extends AbstractCassandraConfiguration { return environment.getProperty("cassandra.keyspace"); } + @Override @Bean public CassandraClusterFactoryBean cluster() { - CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean(); + final CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean(); cluster.setContactPoints(environment.getProperty("cassandra.contactpoints")); cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port"))); LOGGER.info("Cluster created with contact points [" + environment.getProperty("cassandra.contactpoints") + "] " + "& port [" + Integer.parseInt(environment.getProperty("cassandra.port")) + "]."); return cluster; } + @Override @Bean public CassandraMappingContext cassandraMapping() throws ClassNotFoundException { return new BasicCassandraMappingContext(); diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java index 6c099d99bc..a8ec81d6b5 100644 --- a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java +++ b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/model/Book.java @@ -1,28 +1,31 @@ package org.baeldung.spring.data.cassandra.model; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + import org.springframework.cassandra.core.Ordering; import org.springframework.cassandra.core.PrimaryKeyType; import org.springframework.data.cassandra.mapping.Column; import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; import org.springframework.data.cassandra.mapping.Table; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - @Table public class Book { + @PrimaryKeyColumn(name = "id", ordinal = 0, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING) private UUID id; + @PrimaryKeyColumn(name = "title", ordinal = 1, type = PrimaryKeyType.PARTITIONED) private String title; @PrimaryKeyColumn(name = "publisher", ordinal = 2, type = PrimaryKeyType.PARTITIONED) private String publisher; + @Column private Set tags = new HashSet<>(); - public Book(UUID id, String title, String publisher, Set tags) { + public Book(final UUID id, final String title, final String publisher, final Set tags) { this.id = id; this.title = title; this.publisher = publisher; @@ -45,19 +48,20 @@ public class Book { return tags; } - public void setId(UUID id) { + public void setId(final UUID id) { this.id = id; } - public void setTitle(String title) { + public void setTitle(final String title) { this.title = title; } - public void setPublisher(String publisher) { + public void setPublisher(final String publisher) { this.publisher = publisher; } - public void setTags(Set tags) { + public void setTags(final Set tags) { this.tags = tags; } + } diff --git a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java index e37ae78b59..66d656ac3a 100644 --- a/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java +++ b/spring-data-cassandra/src/main/java/org/baeldung/spring/data/cassandra/repository/BookRepository.java @@ -7,6 +7,8 @@ import org.springframework.stereotype.Repository; @Repository public interface BookRepository extends CassandraRepository { + @Query("select * from book where title = ?0 and publisher=?1") Iterable findByTitleAndPublisher(String title, String publisher); + } diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java index e5a7237145..8cbcdc3195 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/BookRepositoryIntegrationTest.java @@ -1,9 +1,11 @@ package org.baeldung.spring.data.cassandra.repository; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.utils.UUIDs; -import com.google.common.collect.ImmutableSet; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.io.IOException; +import java.util.HashMap; + import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -11,7 +13,11 @@ import org.apache.thrift.transport.TTransportException; import org.baeldung.spring.data.cassandra.config.CassandraConfig; import org.baeldung.spring.data.cassandra.model.Book; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cassandra.core.cql.CqlIdentifier; @@ -19,16 +25,14 @@ import org.springframework.data.cassandra.core.CassandraAdminOperations; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.IOException; -import java.util.HashMap; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CassandraConfig.class) public class BookRepositoryIntegrationTest { - private static final Log LOGGER = LogFactory.getLog(BookRepositoryIntegrationTest.class); public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; @@ -43,13 +47,14 @@ public class BookRepositoryIntegrationTest { @Autowired private CassandraAdminOperations adminTemplate; + // + @BeforeClass public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { EmbeddedCassandraServerHelper.startEmbeddedCassandra(); - Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1") - .withPort(9142).build(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); LOGGER.info("Server Started at 127.0.0.1:9142... "); - Session session = cluster.connect(); + final Session session = cluster.connect(); session.execute(KEYSPACE_CREATION_QUERY); session.execute(KEYSPACE_ACTIVATE_QUERY); LOGGER.info("KeySpace created and activated."); @@ -63,54 +68,54 @@ public class BookRepositoryIntegrationTest { @Test public void whenSavingBook_thenAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", - "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); bookRepository.save(ImmutableSet.of(javaBook)); - Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); assertEquals(javaBook.getId(), books.iterator().next().getId()); } @Test public void whenUpdatingBooks_thenAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); bookRepository.save(ImmutableSet.of(javaBook)); - Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); javaBook.setTitle("Head First Java Second Edition"); bookRepository.save(ImmutableSet.of(javaBook)); - Iterable updateBooks = bookRepository.findByTitleAndPublisher("Head First Java Second Edition", "O'Reilly Media"); + final Iterable updateBooks = bookRepository.findByTitleAndPublisher("Head First Java Second Edition", "O'Reilly Media"); assertEquals(javaBook.getTitle(), updateBooks.iterator().next().getTitle()); } @Test(expected = java.util.NoSuchElementException.class) public void whenDeletingExistingBooks_thenNotAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); bookRepository.save(ImmutableSet.of(javaBook)); bookRepository.delete(javaBook); - Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); assertNotEquals(javaBook.getId(), books.iterator().next().getId()); } @Test public void whenSavingBooks_thenAllShouldAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", - "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", - "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); bookRepository.save(ImmutableSet.of(javaBook)); bookRepository.save(ImmutableSet.of(dPatternBook)); - Iterable books = bookRepository.findAll(); + final Iterable books = bookRepository.findAll(); int bookCount = 0; - for (Book book : books) bookCount++; + for (final Book book : books) { + bookCount++; + } assertEquals(bookCount, 2); } @After public void dropTable() { - adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); } @AfterClass public static void stopCassandraEmbedded() { EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); } + } diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java index 031b5c0b6f..584d5f868b 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java @@ -1,12 +1,13 @@ package org.baeldung.spring.data.cassandra.repository; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.querybuilder.Insert; -import com.datastax.driver.core.querybuilder.QueryBuilder; -import com.datastax.driver.core.querybuilder.Select; -import com.datastax.driver.core.utils.UUIDs; -import com.google.common.collect.ImmutableSet; +import static junit.framework.TestCase.assertEquals; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -14,7 +15,11 @@ import org.apache.thrift.transport.TTransportException; import org.baeldung.spring.data.cassandra.config.CassandraConfig; import org.baeldung.spring.data.cassandra.model.Book; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cassandra.core.cql.CqlIdentifier; @@ -23,18 +28,17 @@ import org.springframework.data.cassandra.core.CassandraOperations; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; - -import static junit.framework.TestCase.assertEquals; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.querybuilder.Insert; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CassandraConfig.class) public class CQLQueriesIntegrationTest { - private static final Log LOGGER = LogFactory.getLog(CQLQueriesIntegrationTest.class); public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; @@ -49,12 +53,14 @@ public class CQLQueriesIntegrationTest { @Autowired private CassandraOperations cassandraTemplate; + // + @BeforeClass public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { EmbeddedCassandraServerHelper.startEmbeddedCassandra(25000); - Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); LOGGER.info("Server Started at 127.0.0.1:9142... "); - Session session = cluster.connect(); + final Session session = cluster.connect(); session.execute(KEYSPACE_CREATION_QUERY); session.execute(KEYSPACE_ACTIVATE_QUERY); LOGGER.info("KeySpace created and activated."); @@ -68,40 +74,40 @@ public class CQLQueriesIntegrationTest { @Test public void whenSavingBook_thenAvailableOnRetrieval_usingQueryBuilder() { - UUID uuid = UUIDs.timeBased(); - Insert insert = QueryBuilder.insertInto(DATA_TABLE_NAME).value("id", uuid).value("title", "Head First Java").value("publisher", "OReilly Media").value("tags", ImmutableSet.of("Software")); + final UUID uuid = UUIDs.timeBased(); + final Insert insert = QueryBuilder.insertInto(DATA_TABLE_NAME).value("id", uuid).value("title", "Head First Java").value("publisher", "OReilly Media").value("tags", ImmutableSet.of("Software")); cassandraTemplate.execute(insert); - Select select = QueryBuilder.select().from("book").limit(10); - Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); assertEquals(uuid, retrievedBook.getId()); } @Test public void whenSavingBook_thenAvailableOnRetrieval_usingCQLStatements() { - UUID uuid = UUIDs.timeBased(); - String insertCql = "insert into book (id, title, publisher, tags) values " + "(" + uuid + ", 'Head First Java', 'OReilly Media', {'Software'})"; + final UUID uuid = UUIDs.timeBased(); + final String insertCql = "insert into book (id, title, publisher, tags) values " + "(" + uuid + ", 'Head First Java', 'OReilly Media', {'Software'})"; cassandraTemplate.execute(insertCql); - Select select = QueryBuilder.select().from("book").limit(10); - Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); assertEquals(uuid, retrievedBook.getId()); } @Test public void whenSavingBook_thenAvailableOnRetrieval_usingPreparedStatements() throws InterruptedException { - UUID uuid = UUIDs.timeBased(); - String insertPreparedCql = "insert into book (id, title, publisher, tags) values (?, ?, ?, ?)"; - List singleBookArgsList = new ArrayList<>(); - List> bookList = new ArrayList<>(); + final UUID uuid = UUIDs.timeBased(); + final String insertPreparedCql = "insert into book (id, title, publisher, tags) values (?, ?, ?, ?)"; + final List singleBookArgsList = new ArrayList<>(); + final List> bookList = new ArrayList<>(); singleBookArgsList.add(uuid); singleBookArgsList.add("Head First Java"); singleBookArgsList.add("OReilly Media"); singleBookArgsList.add(ImmutableSet.of("Software")); bookList.add(singleBookArgsList); cassandraTemplate.ingest(insertPreparedCql, bookList); - //This may not be required, just added to avoid any transient issues + // This may not be required, just added to avoid any transient issues Thread.sleep(5000); - Select select = QueryBuilder.select().from("book"); - Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book"); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); assertEquals(uuid, retrievedBook.getId()); } @@ -114,4 +120,5 @@ public class CQLQueriesIntegrationTest { public static void stopCassandraEmbedded() { EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); } + } diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java index 35de508641..e331ac3cd4 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CassandraTemplateIntegrationTest.java @@ -1,11 +1,15 @@ package org.baeldung.spring.data.cassandra.repository; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.querybuilder.QueryBuilder; -import com.datastax.driver.core.querybuilder.Select; -import com.datastax.driver.core.utils.UUIDs; -import com.google.common.collect.ImmutableSet; +import static junit.framework.TestCase.assertNull; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -13,7 +17,11 @@ import org.apache.thrift.transport.TTransportException; import org.baeldung.spring.data.cassandra.config.CassandraConfig; import org.baeldung.spring.data.cassandra.model.Book; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cassandra.core.cql.CqlIdentifier; @@ -22,20 +30,16 @@ import org.springframework.data.cassandra.core.CassandraOperations; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import static junit.framework.TestCase.assertNull; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CassandraConfig.class) public class CassandraTemplateIntegrationTest { - private static final Log LOGGER = LogFactory.getLog(CassandraTemplateIntegrationTest.class); public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; @@ -50,12 +54,14 @@ public class CassandraTemplateIntegrationTest { @Autowired private CassandraOperations cassandraTemplate; + // + @BeforeClass public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { EmbeddedCassandraServerHelper.startEmbeddedCassandra(); - Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); LOGGER.info("Server Started at 127.0.0.1:9142... "); - Session session = cluster.connect(); + final Session session = cluster.connect(); session.execute(KEYSPACE_CREATION_QUERY); session.execute(KEYSPACE_ACTIVATE_QUERY); LOGGER.info("KeySpace created and activated."); @@ -69,24 +75,24 @@ public class CassandraTemplateIntegrationTest { @Test public void whenSavingBook_thenAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); cassandraTemplate.insert(javaBook); - Select select = QueryBuilder.select().from("book").where(QueryBuilder.eq("title", "Head First Java")).and(QueryBuilder.eq("publisher", "O'Reilly Media")).limit(10); - Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").where(QueryBuilder.eq("title", "Head First Java")).and(QueryBuilder.eq("publisher", "O'Reilly Media")).limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); assertEquals(javaBook.getId(), retrievedBook.getId()); } @Test public void whenSavingBooks_thenAllAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - List bookList = new ArrayList<>(); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final List bookList = new ArrayList<>(); bookList.add(javaBook); bookList.add(dPatternBook); cassandraTemplate.insert(bookList); - Select select = QueryBuilder.select().from("book").limit(10); - List retrievedBooks = cassandraTemplate.select(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final List retrievedBooks = cassandraTemplate.select(select, Book.class); assertThat(retrievedBooks.size(), is(2)); assertEquals(javaBook.getId(), retrievedBooks.get(0).getId()); assertEquals(dPatternBook.getId(), retrievedBooks.get(1).getId()); @@ -94,45 +100,45 @@ public class CassandraTemplateIntegrationTest { @Test public void whenUpdatingBook_thenShouldUpdatedOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); cassandraTemplate.insert(javaBook); - Select select = QueryBuilder.select().from("book").limit(10); - Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); retrievedBook.setTags(ImmutableSet.of("Java", "Programming")); cassandraTemplate.update(retrievedBook); - Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); + final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); assertEquals(retrievedBook.getTags(), retrievedUpdatedBook.getTags()); } @Test public void whenDeletingASelectedBook_thenNotAvailableOnRetrieval() throws InterruptedException { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "OReilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "OReilly Media", ImmutableSet.of("Computer", "Software")); cassandraTemplate.insert(javaBook); cassandraTemplate.delete(javaBook); - Select select = QueryBuilder.select().from("book").limit(10); - Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); assertNull(retrievedUpdatedBook); } @Test public void whenDeletingAllBooks_thenNotAvailableOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); cassandraTemplate.insert(javaBook); cassandraTemplate.insert(dPatternBook); cassandraTemplate.deleteAll(Book.class); - Select select = QueryBuilder.select().from("book").limit(10); - Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); assertNull(retrievedUpdatedBook); } @Test public void whenAddingBooks_thenCountShouldBeCorrectOnRetrieval() { - Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); - Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); cassandraTemplate.insert(javaBook); cassandraTemplate.insert(dPatternBook); - long bookCount = cassandraTemplate.count(Book.class); + final long bookCount = cassandraTemplate.count(Book.class); assertEquals(2, bookCount); } diff --git a/spring-data-mongodb/.classpath b/spring-data-mongodb/.classpath new file mode 100644 index 0000000000..baf7c98131 --- /dev/null +++ b/spring-data-mongodb/.classpath @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-data-mongodb/.project b/spring-data-mongodb/.project new file mode 100644 index 0000000000..e3d7687573 --- /dev/null +++ b/spring-data-mongodb/.project @@ -0,0 +1,29 @@ + + + spring-data-mongodb + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index ef6ac59dd4..d9a578cb8c 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -169,6 +169,7 @@ + 4.2.4.RELEASE @@ -197,8 +198,9 @@ 2.6 2.18.1 2.7 - 1.4.15 + 1.4.17 1.8.7 + \ No newline at end of file From ea91739bfa3685bdd0c98e1a90c9d2389be42f37 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 24 Dec 2015 14:15:21 +0200 Subject: [PATCH 33/65] update xml configuration --- .../baeldung/spring/SecSecurityConfig.java | 1 + .../resources/webSecurityConfig-basic.xml | 41 +++++++++++++++++++ .../src/main/resources/webSecurityConfig.xml | 16 ++++++-- 3 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 spring-security-login-and-registration/src/main/resources/webSecurityConfig-basic.xml diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 4863187bba..677ad514e5 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -18,6 +18,7 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand @Configuration @ComponentScan(basePackages = { "org.baeldung.security" }) +// @ImportResource({ "classpath:webSecurityConfig.xml" }) @EnableWebSecurity public class SecSecurityConfig extends WebSecurityConfigurerAdapter { diff --git a/spring-security-login-and-registration/src/main/resources/webSecurityConfig-basic.xml b/spring-security-login-and-registration/src/main/resources/webSecurityConfig-basic.xml new file mode 100644 index 0000000000..bf85a09b62 --- /dev/null +++ b/spring-security-login-and-registration/src/main/resources/webSecurityConfig-basic.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml b/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml index 677b0864c4..3141b19142 100644 --- a/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml +++ b/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml @@ -1,9 +1,10 @@ @@ -36,5 +37,14 @@ + + + + + + + + + \ No newline at end of file From 85dc59632e7cf951f8129171ce0ee5f4bc62678e Mon Sep 17 00:00:00 2001 From: dasvipin5585 Date: Fri, 25 Dec 2015 23:02:13 +0530 Subject: [PATCH 34/65] Java - Try with resources code commit --- .../java8/JavaTryWithResourcesTest.java | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java diff --git a/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java b/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java new file mode 100644 index 0000000000..ae56099e0d --- /dev/null +++ b/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java @@ -0,0 +1,94 @@ +package org.baeldung.java8; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.Scanner; + +import org.junit.Assert; +import org.junit.Test; + +public class JavaTryWithResourcesTest { + + private static final String TEST_STRING_HELLO_WORLD = "Hello World"; + private Date resource1Date, resource2Date; + + /* + * Example for using Try_with_resources + */ + @Test + public void whenWritingToStringWriter_thenCorrectlyWritten() { + + StringWriter sw = new StringWriter(); + try (PrintWriter pw = new PrintWriter(sw, true)) { + pw.print(TEST_STRING_HELLO_WORLD); + } + + Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD); + } + + /* + * Example for using multiple resources + */ + @Test + public void givenStringToScanner_whenWritingToStringWriter_thenCorrectlyWritten() { + + StringWriter sw = new StringWriter(); + try (Scanner sc = new Scanner(TEST_STRING_HELLO_WORLD); PrintWriter pw = new PrintWriter(sw, true)) { + while (sc.hasNext()) { + pw.print(sc.nextLine()); + } + } + + Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD); + } + + /* + * Example to show order in which the resources are closed + */ + @Test + public void whenFirstAutoClosableResourceIsinitializedFirst_thenFirstAutoClosableResourceIsReleasedFirst() throws Exception { + + try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) { + af.doSomething(); + as.doSomething(); + } + Assert.assertTrue(resource1Date.after(resource2Date)); + } + + class AutoCloseableResourcesFirst implements AutoCloseable { + + public AutoCloseableResourcesFirst() { + System.out.println("Constructor -> AutoCloseableResources_First"); + } + + public void doSomething() { + System.out.println("Something -> AutoCloseableResources_First"); + } + + @Override + public void close() throws Exception { + System.out.println("Closed AutoCloseableResources_First"); + resource1Date = new Date(); + + } + } + + class AutoCloseableResourcesSecond implements AutoCloseable { + + public AutoCloseableResourcesSecond() { + System.out.println("Constructor -> AutoCloseableResources_Second"); + } + + public void doSomething() { + System.out.println("Something -> AutoCloseableResources_Second"); + } + + @Override + public void close() throws Exception { + System.out.println("Closed AutoCloseableResources_Second"); + resource2Date = new Date(); + Thread.sleep(10000); + } + } +} From 1edcb35d2cbd88f011459adbc48b4856783e3cf5 Mon Sep 17 00:00:00 2001 From: eugenp Date: Fri, 25 Dec 2015 20:45:45 +0200 Subject: [PATCH 35/65] general cleanup work --- .../java8/JavaTryWithResourcesTest.java | 24 +++++++------------ ...st.java => CqlQueriesIntegrationTest.java} | 4 ++-- 2 files changed, 10 insertions(+), 18 deletions(-) rename spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/{CQLQueriesIntegrationTest.java => CqlQueriesIntegrationTest.java} (98%) diff --git a/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java b/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java index ae56099e0d..a59682c535 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java +++ b/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java @@ -13,13 +13,12 @@ public class JavaTryWithResourcesTest { private static final String TEST_STRING_HELLO_WORLD = "Hello World"; private Date resource1Date, resource2Date; - /* - * Example for using Try_with_resources - */ + // tests + + /* Example for using Try_with_resources */ @Test public void whenWritingToStringWriter_thenCorrectlyWritten() { - - StringWriter sw = new StringWriter(); + final StringWriter sw = new StringWriter(); try (PrintWriter pw = new PrintWriter(sw, true)) { pw.print(TEST_STRING_HELLO_WORLD); } @@ -27,13 +26,11 @@ public class JavaTryWithResourcesTest { Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD); } - /* - * Example for using multiple resources - */ + /* Example for using multiple resources */ @Test public void givenStringToScanner_whenWritingToStringWriter_thenCorrectlyWritten() { - StringWriter sw = new StringWriter(); + final StringWriter sw = new StringWriter(); try (Scanner sc = new Scanner(TEST_STRING_HELLO_WORLD); PrintWriter pw = new PrintWriter(sw, true)) { while (sc.hasNext()) { pw.print(sc.nextLine()); @@ -43,12 +40,9 @@ public class JavaTryWithResourcesTest { Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD); } - /* - * Example to show order in which the resources are closed - */ + /* Example to show order in which the resources are closed */ @Test public void whenFirstAutoClosableResourceIsinitializedFirst_thenFirstAutoClosableResourceIsReleasedFirst() throws Exception { - try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) { af.doSomething(); as.doSomething(); @@ -57,7 +51,6 @@ public class JavaTryWithResourcesTest { } class AutoCloseableResourcesFirst implements AutoCloseable { - public AutoCloseableResourcesFirst() { System.out.println("Constructor -> AutoCloseableResources_First"); } @@ -70,12 +63,10 @@ public class JavaTryWithResourcesTest { public void close() throws Exception { System.out.println("Closed AutoCloseableResources_First"); resource1Date = new Date(); - } } class AutoCloseableResourcesSecond implements AutoCloseable { - public AutoCloseableResourcesSecond() { System.out.println("Constructor -> AutoCloseableResources_Second"); } @@ -91,4 +82,5 @@ public class JavaTryWithResourcesTest { Thread.sleep(10000); } } + } diff --git a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java similarity index 98% rename from spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java rename to spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java index 584d5f868b..f7e42ae23b 100644 --- a/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CQLQueriesIntegrationTest.java +++ b/spring-data-cassandra/src/test/java/org/baeldung/spring/data/cassandra/repository/CqlQueriesIntegrationTest.java @@ -38,8 +38,8 @@ import com.google.common.collect.ImmutableSet; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CassandraConfig.class) -public class CQLQueriesIntegrationTest { - private static final Log LOGGER = LogFactory.getLog(CQLQueriesIntegrationTest.class); +public class CqlQueriesIntegrationTest { + private static final Log LOGGER = LogFactory.getLog(CqlQueriesIntegrationTest.class); public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; From 3a4426e7ca5161b0f9526f752749844c13d33cf3 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 27 Dec 2015 23:55:25 +0200 Subject: [PATCH 36/65] testing work --- spring-hibernate4/pom.xml | 5 +++++ spring-jpa/pom.xml | 5 +++++ .../baeldung/persistence/service/FooServiceSortingTests.java | 4 ---- .../{JPAMultipleDBTest.java => JpaMultipleDBTest.java} | 5 ++++- .../baeldung/persistence/service/PersistenceTestSuite.java | 1 + 5 files changed, 15 insertions(+), 5 deletions(-) rename spring-jpa/src/test/java/org/baeldung/persistence/service/{JPAMultipleDBTest.java => JpaMultipleDBTest.java} (98%) diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml index d24024f151..f3c2806353 100644 --- a/spring-hibernate4/pom.xml +++ b/spring-hibernate4/pom.xml @@ -77,6 +77,11 @@ hibernate-validator ${hibernate-validator.version} + + javax.el + javax.el-api + 2.2.5 + diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index 63d97c337b..20be07ca5b 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -58,6 +58,11 @@ hibernate-validator ${hibernate-validator.version} + + javax.el + javax.el-api + 2.2.5 + diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingTests.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingTests.java index c12dfda50c..319d36151e 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingTests.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingTests.java @@ -15,7 +15,6 @@ import org.baeldung.persistence.model.Bar; import org.baeldung.persistence.model.Foo; 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.support.AnnotationConfigContextLoader; @@ -28,9 +27,6 @@ public class FooServiceSortingTests { @PersistenceContext private EntityManager entityManager; - @Autowired - private FooService service; - // tests @Test diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/JPAMultipleDBTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBTest.java similarity index 98% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/JPAMultipleDBTest.java rename to spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBTest.java index 4c6b02ec3d..427e182d9e 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/JPAMultipleDBTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBTest.java @@ -21,13 +21,16 @@ import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { UserConfig.class, ProductConfig.class }) @TransactionConfiguration -public class JPAMultipleDBTest { +public class JpaMultipleDBTest { + @Autowired private UserRepository userRepository; @Autowired private ProductRepository productRepository; + // tests + @Test @Transactional("userTransactionManager") public void whenCreatingUser_thenCreated() { diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java index f6c41258d4..919171de9f 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java @@ -8,6 +8,7 @@ import org.junit.runners.Suite; FooPaginationPersistenceIntegrationTest.class ,FooServicePersistenceIntegrationTest.class ,FooServiceSortingTests.class + ,JpaMultipleDBTest.class // manual only // ,FooServiceSortingWitNullsManualTest.class }) // @formatter:on From 69e2394d4b8a499e8629f2681ba6d6ae7715790b Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 28 Dec 2015 12:04:08 +0200 Subject: [PATCH 37/65] modify ldap configuration --- spring-security-mvc-ldap/pom.xml | 19 +--------- .../org/baeldung/SampleLDAPApplication.java | 4 +-- .../org/baeldung/security/SecurityConfig.java | 13 +++---- .../src/main/resources/templates/login.html | 2 +- .../src/main/resources/webSecurityConfig.xml | 36 +++++++++++++++++++ 5 files changed, 44 insertions(+), 30 deletions(-) create mode 100644 spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index 00165bd740..5282f76a7e 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -35,29 +35,13 @@ spring-security-ldap - - org.springframework.ldap - spring-ldap-core - 2.0.3.RELEASE - - - org.springframework.ldap - spring-ldap-core-tiger - 2.0.3.RELEASE - - org.apache.directory.server apacheds-server-jndi 1.5.5 - - org.apache.mina - mina-core - 2.0.9 - - + @@ -74,7 +58,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} 1.8 1.8 diff --git a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java index 454e52d1d5..4bcb255046 100644 --- a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java +++ b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java @@ -3,16 +3,14 @@ package org.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; -import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Main Application Class - uses Spring Boot. Just run this as a normal Java * class to run up a Jetty Server (on http://localhost:8080) - * + * */ -@EnableScheduling @EnableAutoConfiguration @ComponentScan("org.baeldung") public class SampleLDAPApplication extends WebMvcConfigurerAdapter { diff --git a/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java b/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java index c9bb5b74ae..ee72ee7891 100644 --- a/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java +++ b/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java @@ -1,29 +1,26 @@ package org.baeldung.security; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.stereotype.Controller; /** * Security Configuration - LDAP and HTTP Authorizations. */ -@EnableAutoConfiguration -@ComponentScan -@Controller +@Configuration +// @ImportResource({ "classpath:webSecurityConfig.xml" }) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.ldapAuthentication().userSearchBase("ou=people").userSearchFilter("(uid={0})").groupSearchBase("ou=groups").groupSearchFilter("member={0}").contextSource().root("dc=baeldung,dc=com").ldif("classpath:users.ldif"); + auth.ldapAuthentication().userSearchBase("ou=people").userSearchFilter("(uid={0})").groupSearchBase("ou=groups").groupSearchFilter("(member={0})").contextSource().root("dc=baeldung,dc=com").ldif("classpath:users.ldif"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/", "/home").permitAll().anyRequest().authenticated(); - http.formLogin().loginPage("/login").permitAll().and().logout().logoutSuccessUrl("/"); + http.formLogin().loginPage("/login").permitAll().loginProcessingUrl("/j_spring_security_check").and().logout().logoutSuccessUrl("/"); } } diff --git a/spring-security-mvc-ldap/src/main/resources/templates/login.html b/spring-security-mvc-ldap/src/main/resources/templates/login.html index e3a18c2e48..81f62fde13 100644 --- a/spring-security-mvc-ldap/src/main/resources/templates/login.html +++ b/spring-security-mvc-ldap/src/main/resources/templates/login.html @@ -21,7 +21,7 @@

You have been logged out

There was an error, please try again

Login with Username and Password

-
+
diff --git a/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..6bd2c422d8 --- /dev/null +++ b/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From c8d9bd4f21cefac4dbeb33648871babf585d3f54 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 28 Dec 2015 18:23:13 +0200 Subject: [PATCH 38/65] spring batch work --- .../.classpath | 6 +++++- {spring-batch-intro => spring-batch}/.project | 8 +++++++- {spring-batch-intro => spring-batch}/pom.xml | 7 +++---- .../org/baeldung/spring_batch_intro/App.java | 18 +++++++----------- .../spring_batch_intro/SpringBatchConfig.java | 0 .../spring_batch_intro/SpringConfig.java | 0 .../spring_batch_intro/model/Transaction.java | 0 .../service/CustomItemProcessor.java | 0 .../service/RecordFieldSetMapper.java | 0 .../src/main/resources/input/record.csv | 0 .../src/main/resources/spring-batch-intro.xml | 0 .../src/main/resources/spring.xml | 0 .../xml/output.xml | 0 13 files changed, 22 insertions(+), 17 deletions(-) rename {spring-batch-intro => spring-batch}/.classpath (83%) rename {spring-batch-intro => spring-batch}/.project (69%) rename {spring-batch-intro => spring-batch}/pom.xml (85%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/App.java (60%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java (100%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java (100%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java (100%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java (100%) rename {spring-batch-intro => spring-batch}/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java (100%) rename {spring-batch-intro => spring-batch}/src/main/resources/input/record.csv (100%) rename {spring-batch-intro => spring-batch}/src/main/resources/spring-batch-intro.xml (100%) rename {spring-batch-intro => spring-batch}/src/main/resources/spring.xml (100%) rename {spring-batch-intro => spring-batch}/xml/output.xml (100%) diff --git a/spring-batch-intro/.classpath b/spring-batch/.classpath similarity index 83% rename from spring-batch-intro/.classpath rename to spring-batch/.classpath index 395dbde027..e7ac9faf11 100644 --- a/spring-batch-intro/.classpath +++ b/spring-batch/.classpath @@ -12,7 +12,11 @@ - + + + + + diff --git a/spring-batch-intro/.project b/spring-batch/.project similarity index 69% rename from spring-batch-intro/.project rename to spring-batch/.project index 032f8a9541..0159a7237c 100644 --- a/spring-batch-intro/.project +++ b/spring-batch/.project @@ -1,6 +1,6 @@ - spring-batch-intro + spring-batch @@ -15,8 +15,14 @@ + + org.springframework.ide.eclipse.core.springbuilder + + + + org.springframework.ide.eclipse.core.springnature org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature diff --git a/spring-batch-intro/pom.xml b/spring-batch/pom.xml similarity index 85% rename from spring-batch-intro/pom.xml rename to spring-batch/pom.xml index 28d48c594e..c85aeff6f3 100644 --- a/spring-batch-intro/pom.xml +++ b/spring-batch/pom.xml @@ -1,13 +1,12 @@ - + 4.0.0 org.baeldung - spring-batch-intro + spring-batch 0.1-SNAPSHOT jar - spring-batch-intro + spring-batch http://maven.apache.org diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java similarity index 60% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java index d6af37595c..2ce4dae6e6 100644 --- a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java @@ -4,31 +4,27 @@ import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - public class App { - public static void main(String[] args) { + public static void main(final String[] args) { // Spring Java config - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(SpringConfig.class); context.register(SpringBatchConfig.class); context.refresh(); // Spring xml config - // ApplicationContext context = new ClassPathXmlApplicationContext( - // "spring-batch-intro.xml"); + // ApplicationContext context = new ClassPathXmlApplicationContext("spring-batch.xml"); - JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); - Job job = (Job) context.getBean("firstBatchJob"); + final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); + final Job job = (Job) context.getBean("firstBatchJob"); System.out.println("Starting the batch job"); try { - JobExecution execution = jobLauncher.run(job, new JobParameters()); + final JobExecution execution = jobLauncher.run(job, new JobParameters()); System.out.println("Job Status : " + execution.getStatus()); System.out.println("Job succeeded"); - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); System.out.println("Job failed"); } diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java similarity index 100% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java similarity index 100% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java similarity index 100% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java similarity index 100% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java diff --git a/spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java similarity index 100% rename from spring-batch-intro/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java rename to spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java diff --git a/spring-batch-intro/src/main/resources/input/record.csv b/spring-batch/src/main/resources/input/record.csv similarity index 100% rename from spring-batch-intro/src/main/resources/input/record.csv rename to spring-batch/src/main/resources/input/record.csv diff --git a/spring-batch-intro/src/main/resources/spring-batch-intro.xml b/spring-batch/src/main/resources/spring-batch-intro.xml similarity index 100% rename from spring-batch-intro/src/main/resources/spring-batch-intro.xml rename to spring-batch/src/main/resources/spring-batch-intro.xml diff --git a/spring-batch-intro/src/main/resources/spring.xml b/spring-batch/src/main/resources/spring.xml similarity index 100% rename from spring-batch-intro/src/main/resources/spring.xml rename to spring-batch/src/main/resources/spring.xml diff --git a/spring-batch-intro/xml/output.xml b/spring-batch/xml/output.xml similarity index 100% rename from spring-batch-intro/xml/output.xml rename to spring-batch/xml/output.xml From 55925bf5bd355b79ebd5009f707f69f7d349b3ca Mon Sep 17 00:00:00 2001 From: gmaipady Date: Wed, 30 Dec 2015 21:17:31 +0530 Subject: [PATCH 39/65] Moved from XML config to Java config --- spring-thymeleaf/.classpath | 12 ++--- spring-thymeleaf/pom.xml | 3 ++ .../WEB-INF/appServlet/servlet-context.xml | 53 ------------------- .../src/main/webapp/WEB-INF/root-context.xml | 8 --- .../src/main/webapp/WEB-INF/web.xml | 34 ------------ 5 files changed, 9 insertions(+), 101 deletions(-) delete mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml delete mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml delete mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/web.xml diff --git a/spring-thymeleaf/.classpath b/spring-thymeleaf/.classpath index 28e4a52cd4..81999ab717 100644 --- a/spring-thymeleaf/.classpath +++ b/spring-thymeleaf/.classpath @@ -11,12 +11,6 @@ - - - - - - @@ -28,5 +22,11 @@ + + + + + + diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 1a8dff671e..ae7451a74e 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -112,6 +112,9 @@ org.apache.maven.plugins maven-war-plugin ${maven-war-plugin.version} + + false + org.apache.maven.plugins diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml deleted file mode 100644 index ef42557429..0000000000 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/appServlet/servlet-context.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml deleted file mode 100644 index 5cb2a94d73..0000000000 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/root-context.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml b/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 275a482c6f..0000000000 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - contextConfigLocation - /WEB-INF/root-context.xml - - - - - org.springframework.web.context.ContextLoaderListener - - - - - appServlet - org.springframework.web.servlet.DispatcherServlet - - contextConfigLocation - /WEB-INF/appServlet/servlet-context.xml - - 1 - - - - appServlet - / - - \ No newline at end of file From 438dfffd547def3b0adb1a91f861c753f8546e99 Mon Sep 17 00:00:00 2001 From: gmaipady Date: Wed, 30 Dec 2015 21:21:21 +0530 Subject: [PATCH 40/65] Moved from XML config to Java config --- .../org/baeldung/thymeleaf/config/WebApp.java | 36 +++++++++ .../thymeleaf/config/WebMVCConfig.java | 73 +++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java create mode 100644 spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java new file mode 100644 index 0000000000..45752a6269 --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java @@ -0,0 +1,36 @@ +package org.baeldung.thymeleaf.config; + +import javax.servlet.ServletRegistration.Dynamic; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +/** + * Java configuration file that is used for web application initialization + */ +public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer { + + public WebApp() { + super(); + } + + @Override + protected Class[] getRootConfigClasses() { + return null; + } + + @Override + protected Class[] getServletConfigClasses() { + return new Class[] { WebMVCConfig.class }; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + + @Override + protected void customizeRegistration(final Dynamic registration) { + super.customizeRegistration(registration); + } + +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java new file mode 100644 index 0000000000..c5bd460eee --- /dev/null +++ b/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java @@ -0,0 +1,73 @@ +package org.baeldung.thymeleaf.config; + +import org.baeldung.thymeleaf.formatter.NameFormatter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Description; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.format.FormatterRegistry; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; + +@Configuration +@EnableWebMvc +@ComponentScan({ "org.baeldung.thymeleaf" }) +/** + * Java configuration file that is used for Spring MVC and Thymeleaf + * configurations + */ +public class WebMVCConfig extends WebMvcConfigurerAdapter { + + @Bean + @Description("Thymeleaf Template Resolver") + public ServletContextTemplateResolver templateResolver() { + ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/views/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + + return templateResolver; + } + + @Bean + @Description("Thymeleaf Template Engine") + public SpringTemplateEngine templateEngine() { + SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + + return templateEngine; + } + + @Bean + @Description("Thymeleaf View Resolver") + public ThymeleafViewResolver viewResolver() { + ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } + + @Bean + @Description("Spring Message Resolver") + public ResourceBundleMessageSource messageSource() { + ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); + } + + @Override + @Description("Custom Conversion Service") + public void addFormatters(FormatterRegistry registry) { + registry.addFormatter(new NameFormatter()); + } +} From d9a91f0d28b4c434d071e313def4acf67e8af228 Mon Sep 17 00:00:00 2001 From: Alex V Date: Thu, 31 Dec 2015 05:14:39 +0200 Subject: [PATCH 41/65] Code for "Lambda Expressions and Functional Interfaces. Best Practices and Tips" article --- .../src/main/java/org/baeldung/Adder.java | 12 +++ .../src/main/java/org/baeldung/AdderImpl.java | 16 +++ .../src/main/java/org/baeldung/Bar.java | 12 +++ .../src/main/java/org/baeldung/Baz.java | 11 ++ .../src/main/java/org/baeldung/Foo.java | 9 ++ .../main/java/org/baeldung/FooExtended.java | 11 ++ .../src/main/java/org/baeldung/UseFoo.java | 39 +++++++ .../Java8FunctionalInteracesLambdasTest.java | 101 ++++++++++++++++++ .../baeldung/java8/JavaFolderSizeTest.java | 21 ++-- 9 files changed, 226 insertions(+), 6 deletions(-) create mode 100644 core-java-8/src/main/java/org/baeldung/Adder.java create mode 100644 core-java-8/src/main/java/org/baeldung/AdderImpl.java create mode 100644 core-java-8/src/main/java/org/baeldung/Bar.java create mode 100644 core-java-8/src/main/java/org/baeldung/Baz.java create mode 100644 core-java-8/src/main/java/org/baeldung/Foo.java create mode 100644 core-java-8/src/main/java/org/baeldung/FooExtended.java create mode 100644 core-java-8/src/main/java/org/baeldung/UseFoo.java create mode 100644 core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java diff --git a/core-java-8/src/main/java/org/baeldung/Adder.java b/core-java-8/src/main/java/org/baeldung/Adder.java new file mode 100644 index 0000000000..4578990de7 --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/Adder.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import java.util.function.Consumer; +import java.util.function.Function; + +public interface Adder { + + String addWithFunction(Function f); + + void addWithConsumer(Consumer f); + +} diff --git a/core-java-8/src/main/java/org/baeldung/AdderImpl.java b/core-java-8/src/main/java/org/baeldung/AdderImpl.java new file mode 100644 index 0000000000..a62c0cd4fb --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/AdderImpl.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import java.util.function.Consumer; +import java.util.function.Function; + +public class AdderImpl implements Adder { + + @Override + public String addWithFunction(Function f) { + return f.apply("Something "); + } + + @Override + public void addWithConsumer(Consumer f) {} + +} diff --git a/core-java-8/src/main/java/org/baeldung/Bar.java b/core-java-8/src/main/java/org/baeldung/Bar.java new file mode 100644 index 0000000000..0dd7df6be2 --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/Bar.java @@ -0,0 +1,12 @@ +package org.baeldung; + +@FunctionalInterface +public interface Bar { + + String method(String string); + + default String defaultMethod() { + return "String from Bar"; + } + +} diff --git a/core-java-8/src/main/java/org/baeldung/Baz.java b/core-java-8/src/main/java/org/baeldung/Baz.java new file mode 100644 index 0000000000..bcc46af6e7 --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/Baz.java @@ -0,0 +1,11 @@ +package org.baeldung; + +@FunctionalInterface +public interface Baz { + + String method(String string); + + default String defaultMethod() { + return "String from Baz"; + } +} diff --git a/core-java-8/src/main/java/org/baeldung/Foo.java b/core-java-8/src/main/java/org/baeldung/Foo.java new file mode 100644 index 0000000000..a10e45a8f5 --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/Foo.java @@ -0,0 +1,9 @@ +package org.baeldung; + +@FunctionalInterface +public interface Foo { + + String method(String string); + + default void defaultMethod() {} +} diff --git a/core-java-8/src/main/java/org/baeldung/FooExtended.java b/core-java-8/src/main/java/org/baeldung/FooExtended.java new file mode 100644 index 0000000000..39c3a0765f --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/FooExtended.java @@ -0,0 +1,11 @@ +package org.baeldung; + +@FunctionalInterface +public interface FooExtended extends Baz, Bar { + + @Override + default String defaultMethod() { + return Bar.super.defaultMethod(); + } + +} diff --git a/core-java-8/src/main/java/org/baeldung/UseFoo.java b/core-java-8/src/main/java/org/baeldung/UseFoo.java new file mode 100644 index 0000000000..a29c5631ac --- /dev/null +++ b/core-java-8/src/main/java/org/baeldung/UseFoo.java @@ -0,0 +1,39 @@ +package org.baeldung; + +import java.util.function.Function; + +public class UseFoo { + + private String value = "Enclosing scope value"; + + public String add(String string, Foo foo) { + return foo.method(string); + } + + public String addWithStandardFI(String string, Function fn) { + return fn.apply(string); + } + + public String scopeExperiment() { + Foo fooIC = new Foo() { + String value = "Inner class value"; + + @Override + public String method(String string) { + return this.value; + } + }; + String resultIC = fooIC.method(""); + + Foo fooLambda = parameter -> { + String value = "Lambda value"; + return this.value; + }; + String resultLambda = fooLambda.method(""); + + return "Results: resultIC = " + resultIC + + ", resultLambda = " + resultLambda; + } + + +} diff --git a/core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java b/core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java new file mode 100644 index 0000000000..3845d6ba84 --- /dev/null +++ b/core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java @@ -0,0 +1,101 @@ +package org.baeldung.java8; + +import org.baeldung.Foo; +import org.baeldung.FooExtended; +import org.baeldung.UseFoo; +import org.junit.Before; +import org.junit.Test; + +import java.util.function.Function; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class Java8FunctionalInteracesLambdasTest { + + private UseFoo useFoo; + + @Before + public void init() { + useFoo = new UseFoo(); + } + + @Test + public void functionalInterfaceInstantiation_whenReturnDefiniteString_thenCorrect() { + + Foo foo = parameter -> parameter + "from lambda"; + String result = useFoo.add("Message ", foo); + + assertEquals("Message from lambda", result); + } + + @Test + public void standardFIParameter_whenReturnDefiniteString_thenCorrect() { + + Function fn = parameter -> parameter + "from lambda"; + String result = useFoo.addWithStandardFI("Message ", fn); + + assertEquals("Message from lambda", result); + } + + @Test + public void defaultMethodFromExtendedInterface_whenReturnDefiniteString_thenCorrect() { + + FooExtended fooExtended = string -> string; + String result = fooExtended.defaultMethod(); + + assertEquals("String from Bar", result); + } + + @Test + public void lambdaAndInnerClassInstantiation_whenReturnSameString_thenCorrect() { + + Foo foo = parameter -> parameter + "from Foo"; + + Foo fooByIC = new Foo() { + @Override + public String method(String string) { + return string + "from Foo"; + } + }; + + assertEquals(foo.method("Something "), fooByIC.method("Something ")); + } + + @Test + public void accessVariablesFromDifferentScopes_whenReturnPredefinedString_thenCorrect() { + + assertEquals("Results: resultIC = Inner class value, resultLambda = Enclosing scope value", + useFoo.scopeExperiment()); + } + + @Test + public void shorteningLambdas_whenReturnEqualsResults_thenCorrect() { + + Foo foo = parameter -> buildString(parameter); + + Foo fooHuge = parameter -> { String result = "Something " + parameter; + //many lines of code + return result; + }; + + assertEquals(foo.method("Something"), fooHuge.method("Something")); + } + + private String buildString(String parameter) { + String result = "Something " + parameter; + //many lines of code + return result; + } + + @Test + public void mutatingOfEffectivelyFinalVariable_whenNotEquals_thenCorrect() { + + int[] total = new int[1]; + Runnable r = () -> total[0]++; + r.run(); + + assertNotEquals(0, total[0]); + } + +} diff --git a/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java b/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java index baa41511de..a65971bb91 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java +++ b/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java @@ -15,15 +15,24 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.stream.StreamSupport; import org.apache.commons.io.FileUtils; +import org.junit.Before; import org.junit.Test; public class JavaFolderSizeTest { + private String path; + + @Before + public void init() { + final String separator = File.separator; + path = "src" + separator + "test" + separator + "resources"; + } + @Test public void whenGetFolderSizeRecursive_thenCorrect() { final long expectedSize = 136; - final File folder = new File("src/test/resources"); + final File folder = new File(path); final long size = getFolderSize(folder); assertEquals(expectedSize, size); @@ -34,7 +43,7 @@ public class JavaFolderSizeTest { final long expectedSize = 136; final AtomicLong size = new AtomicLong(0); - final Path folder = Paths.get("src/test/resources"); + final Path folder = Paths.get(path); Files.walkFileTree(folder, new SimpleFileVisitor() { @Override @@ -51,7 +60,7 @@ public class JavaFolderSizeTest { public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException { final long expectedSize = 136; - final Path folder = Paths.get("src/test/resources"); + final Path folder = Paths.get(path); final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum(); assertEquals(expectedSize, size); @@ -61,7 +70,7 @@ public class JavaFolderSizeTest { public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() { final long expectedSize = 136; - final File folder = new File("src/test/resources"); + final File folder = new File(path); final long size = FileUtils.sizeOfDirectory(folder); assertEquals(expectedSize, size); @@ -71,7 +80,7 @@ public class JavaFolderSizeTest { public void whenGetFolderSizeUsingGuava_thenCorrect() { final long expectedSize = 136; - final File folder = new File("src/test/resources"); + final File folder = new File(path); final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); final long size = StreamSupport.stream(files.spliterator(), false).filter(f -> f.isFile()).mapToLong(File::length).sum(); @@ -81,7 +90,7 @@ public class JavaFolderSizeTest { @Test public void whenGetReadableSize_thenCorrect() { - final File folder = new File("src/test/resources"); + final File folder = new File(path); final long size = getFolderSize(folder); final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" }; From 7a35c66a62fba948decad64bc442a683e845941e Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 31 Dec 2015 13:02:15 +0200 Subject: [PATCH 42/65] Handling accessDenied --- .../baeldung/spring/SecSecurityConfig.java | 48 +++++++++++++++++-- .../web/controller/RootController.java | 15 ++++-- .../web/error/CustomAccessDeniedHandler.java | 22 +++++++++ .../RestResponseEntityExceptionHandler.java | 7 +++ .../src/main/resources/webSecurityConfig.xml | 7 ++- 5 files changed, 92 insertions(+), 7 deletions(-) create mode 100644 spring-security-rest-full/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/SecSecurityConfig.java index acf5ff6be5..75daacbb04 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,16 +1,58 @@ package org.baeldung.spring; +import org.baeldung.web.error.CustomAccessDeniedHandler; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableAutoConfiguration -@ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecSecurityConfig { +// +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +// @ImportResource({ "classpath:webSecurityConfig.xml" }) +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private CustomAccessDeniedHandler accessDeniedHandler; public SecSecurityConfig() { super(); } + // java config + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN"); + } + + @Override + public void configure(final WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN") + .anyRequest().authenticated() + .and() + .httpBasic() + .and() + // .exceptionHandling().accessDeniedPage("/my-error-page") + .exceptionHandling().accessDeniedHandler(accessDeniedHandler) + ; + // @formatter:on + } + } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java index 42fc78f611..e83b8cf5ba 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/RootController.java @@ -11,6 +11,7 @@ import org.baeldung.web.metric.IMetricService; import org.baeldung.web.util.LinkUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -51,6 +52,7 @@ public class RootController { return metricService.getFullMetric(); } + @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping(value = "/status-metric", method = RequestMethod.GET) @ResponseBody public Map getStatusMetric() { @@ -67,9 +69,16 @@ public class RootController { return result; } - @RequestMapping(value = "/metric-graph-data", method = RequestMethod.GET) + @RequestMapping(value = "/admin/x", method = RequestMethod.GET) @ResponseBody - public Object[][] getActuatorMetricData() { - return actMetricService.getGraphData(); + public String sampleAdminPage() { + return "Hello"; } + + @RequestMapping(value = "/my-error-page", method = RequestMethod.GET) + @ResponseBody + public String sampleErrorPage() { + return "Error Occurred"; + } + } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java b/spring-security-rest-full/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java new file mode 100644 index 0000000000..ae7340ef88 --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/error/CustomAccessDeniedHandler.java @@ -0,0 +1,22 @@ +package org.baeldung.web.error; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +@Component +public class CustomAccessDeniedHandler implements AccessDeniedHandler { + + @Override + public void handle(final HttpServletRequest request, final HttpServletResponse response, final AccessDeniedException ex) throws IOException, ServletException { + response.getOutputStream().print("Error Message Goes Here"); + // response.sendRedirect("/my-error-page"); + } + +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java b/spring-security-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java index a465a82d75..e9d34aa9cf 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java @@ -11,11 +11,13 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.security.access.AccessDeniedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +//import org.springframework.security.access.AccessDeniedException; @ControllerAdvice public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @@ -54,6 +56,11 @@ public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionH } // 403 + @ExceptionHandler({ AccessDeniedException.class }) + public ResponseEntity handleAccessDeniedException(final Exception ex, final WebRequest request) { + System.out.println("request" + request.getUserPrincipal()); + return new ResponseEntity("Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN); + } // 404 diff --git a/spring-security-rest-full/src/main/resources/webSecurityConfig.xml b/spring-security-rest-full/src/main/resources/webSecurityConfig.xml index 915460bd44..a60033b71a 100644 --- a/spring-security-rest-full/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest-full/src/main/resources/webSecurityConfig.xml @@ -9,19 +9,24 @@ - + + + + + + From 5d37cd403b30ebd7437b233db7dd1eee1afefa84 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 4 Jan 2016 00:55:58 +0200 Subject: [PATCH 43/65] cleanup work --- .../.settings/org.eclipse.wst.common.project.facet.core.xml | 2 +- .../src/main/resources/webSecurityConfig.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml index f5888c1411..8a1c189419 100644 --- a/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml +++ b/spring-security-rest-digest-auth/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -1,5 +1,5 @@ - + diff --git a/spring-security-rest-digest-auth/src/main/resources/webSecurityConfig.xml b/spring-security-rest-digest-auth/src/main/resources/webSecurityConfig.xml index 695efa8047..42a59abff0 100644 --- a/spring-security-rest-digest-auth/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest-digest-auth/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ From 50c173475450f425ad6afecbe8be91aa6d524ef8 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 4 Jan 2016 01:01:27 +0200 Subject: [PATCH 44/65] minor cleanup --- .../main/java/org/baeldung/web/metric/MetricFilter.java | 2 +- .../src/main/resources/springDataPersistenceConfig.xml | 7 +++++-- .../src/main/resources/webSecurityConfig.xml | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java index d77aec7919..6c2fb0cb39 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java @@ -26,7 +26,7 @@ public class MetricFilter implements Filter { public void init(final FilterConfig config) throws ServletException { if (metricService == null || actMetricService == null) { metricService = (IMetricService) WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean("metricService"); - actMetricService = (ICustomActuatorMetricService) WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean("actuatorMetricService"); + actMetricService = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean(CustomActuatorMetricService.class); } } diff --git a/spring-security-rest-full/src/main/resources/springDataPersistenceConfig.xml b/spring-security-rest-full/src/main/resources/springDataPersistenceConfig.xml index 5c971d975d..d6d0ec6e47 100644 --- a/spring-security-rest-full/src/main/resources/springDataPersistenceConfig.xml +++ b/spring-security-rest-full/src/main/resources/springDataPersistenceConfig.xml @@ -1,7 +1,10 @@ diff --git a/spring-security-rest-full/src/main/resources/webSecurityConfig.xml b/spring-security-rest-full/src/main/resources/webSecurityConfig.xml index a60033b71a..d6ba952dfd 100644 --- a/spring-security-rest-full/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest-full/src/main/resources/webSecurityConfig.xml @@ -4,7 +4,7 @@ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" + http://www.springframework.org/schema/beans/spring-beans.xsd" > From a2258914567b31b5783fd60af5e88adcfa0ae55d Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 5 Jan 2016 19:55:11 +0200 Subject: [PATCH 45/65] cleanup and upgrade --- spring-all/pom.xml | 4 -- spring-katharsis/pom.xml | 6 ++- spring-security-mvc-ldap/pom.xml | 42 ++----------------- .../org/baeldung/security/SecurityConfig.java | 4 +- .../src/main/resources/templates/login.html | 2 +- .../src/main/resources/webSecurityConfig.xml | 5 +-- spring-security-rest-full/pom.xml | 26 ++++++------ spring-security-rest/pom.xml | 18 ++++---- .../baeldung/spring/SecurityJavaConfig.java | 7 +--- .../src/main/resources/webSecurityConfig.xml | 4 +- 10 files changed, 42 insertions(+), 76 deletions(-) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 16ff340d81..6ce8ad7196 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -128,7 +128,6 @@ junit junit - ${junit.version} test @@ -164,7 +163,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} 1.8 1.8 @@ -174,7 +172,6 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} false @@ -183,7 +180,6 @@ org.apache.maven.plugins maven-surefire-plugin - ${maven-surefire-plugin.version} diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 554ff4e656..892aaf24f1 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -31,7 +31,7 @@ io.katharsis katharsis-servlet - 1.0.0 + ${katharsis.version} @@ -45,7 +45,7 @@ com.jayway.restassured rest-assured - 2.4.0 + ${restassured.version} test @@ -60,6 +60,8 @@ 1.8 + 1.0.0 + 2.4.0 diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index 5282f76a7e..3f9b9ad1ed 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.4.RELEASE + 1.3.1.RELEASE @@ -39,7 +39,7 @@ org.apache.directory.server apacheds-server-jndi - 1.5.5 + ${apacheds.version} @@ -68,42 +68,8 @@ - - - 4.2.4.RELEASE - 4.0.3.RELEASE - - - 4.3.11.Final - 5.1.37 - - - 1.7.13 - 1.1.3 - - - 5.2.2.Final - - - 19.0 - 3.4 - - - 1.3 - 4.12 - 1.10.19 - - 4.4.1 - 4.5 - - 2.4.1 - - - 3.3 - 2.6 - 2.18.1 - 1.4.15 - + + 1.5.5 diff --git a/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java b/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java index ee72ee7891..0d444e36ff 100644 --- a/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java +++ b/spring-security-mvc-ldap/src/main/java/org/baeldung/security/SecurityConfig.java @@ -9,7 +9,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur * Security Configuration - LDAP and HTTP Authorizations. */ @Configuration -// @ImportResource({ "classpath:webSecurityConfig.xml" }) +// @ImportResource({ "classpath:webSecurityConfig.xml" }) //=> uncomment to use equivalent xml config public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override @@ -20,7 +20,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/", "/home").permitAll().anyRequest().authenticated(); - http.formLogin().loginPage("/login").permitAll().loginProcessingUrl("/j_spring_security_check").and().logout().logoutSuccessUrl("/"); + http.formLogin().loginPage("/login").permitAll().and().logout().logoutSuccessUrl("/"); } } diff --git a/spring-security-mvc-ldap/src/main/resources/templates/login.html b/spring-security-mvc-ldap/src/main/resources/templates/login.html index 81f62fde13..e21ea21e69 100644 --- a/spring-security-mvc-ldap/src/main/resources/templates/login.html +++ b/spring-security-mvc-ldap/src/main/resources/templates/login.html @@ -21,7 +21,7 @@

You have been logged out

There was an error, please try again

Login with Username and Password

- +
diff --git a/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml index 6bd2c422d8..c13f65de5e 100644 --- a/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-ldap/src/main/resources/webSecurityConfig.xml @@ -13,10 +13,7 @@ - + diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index bed716897b..cbcc3fca64 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.0.RELEASE + 1.3.1.RELEASE @@ -113,12 +113,12 @@ com.mysema.querydsl querydsl-apt - 3.6.2 + ${querydsl.version} com.mysema.querydsl querydsl-jpa - 3.6.2 + ${querydsl.version} @@ -126,7 +126,7 @@ cz.jirutka.rsql rsql-parser - 2.0.0 + ${rsql.version} @@ -144,7 +144,6 @@ org.apache.httpcomponents httpcore - ${httpcore.version} @@ -164,7 +163,7 @@ xml-apis xml-apis - 1.4.01 + ${xml-apis.version} org.javassist @@ -200,7 +199,7 @@ com.thoughtworks.xstream xstream - 1.4.8 + ${xstream.version} @@ -243,7 +242,6 @@ junit junit - ${junit.version} test @@ -267,7 +265,7 @@ com.jayway.restassured rest-assured - 2.4.0 + ${rest-assured.version} test @@ -344,7 +342,7 @@ com.mysema.maven apt-maven-plugin - 1.1.3 + ${apt-maven-plugin.version} @@ -434,9 +432,12 @@ 5.1.37 1.7.2.RELEASE + 2.0.0 + 3.6.2 + - 2.5.5 + 1.4.01 1.7.13 @@ -444,6 +445,7 @@ 5.2.2.Final + 1.4.8 19.0 @@ -464,7 +466,7 @@ 2.6 2.18.1 1.4.15 - + 1.1.3 \ No newline at end of file diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 42381bf607..2046b38810 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -82,14 +82,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet-api.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -98,7 +98,7 @@ com.fasterxml.jackson.core jackson-databind - 2.2.2 + ${jackson.version} @@ -111,7 +111,7 @@ org.apache.commons commons-lang3 - 3.1 + ${commons-lang3.version} @@ -171,13 +171,13 @@ io.springfox springfox-swagger2 - 2.2.2 + ${springfox.version} io.springfox springfox-swagger-ui - 2.2.2 + ${springfox.version} @@ -263,7 +263,11 @@ 5.2.2.Final - + 3.0.1 + 1.2 + 2.2.2 + 2.2.2 + 19.0 3.4 diff --git a/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java b/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java index ca882909f0..5b88fefdb2 100644 --- a/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java +++ b/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java @@ -35,19 +35,16 @@ public class SecurityJavaConfig extends WebSecurityConfigurerAdapter { } @Override - protected void configure(final HttpSecurity http) throws Exception { // @formatter:off + protected void configure(final HttpSecurity http) throws Exception {// @formatter:off http .csrf().disable() .exceptionHandling() .authenticationEntryPoint(restAuthenticationEntryPoint) .and() .authorizeRequests() - .antMatchers("/api/foos").authenticated() + .antMatchers("/api/**").authenticated() .and() .formLogin() - .loginProcessingUrl("/j_spring_security_check") - .usernameParameter("j_username") - .passwordParameter("j_password") .successHandler(authenticationSuccessHandler) .failureHandler(new SimpleUrlAuthenticationFailureHandler()) .and() diff --git a/spring-security-rest/src/main/resources/webSecurityConfig.xml b/spring-security-rest/src/main/resources/webSecurityConfig.xml index 20651c458c..619b53fb7e 100644 --- a/spring-security-rest/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest/src/main/resources/webSecurityConfig.xml @@ -11,7 +11,9 @@ - + + + From 4192ee3f75086864a9d622b3d66f7d621be55254 Mon Sep 17 00:00:00 2001 From: David Morley Date: Tue, 5 Jan 2016 21:37:15 -0600 Subject: [PATCH 46/65] Remove Eclipse-specific metadata files --- spring-thymeleaf/.classpath | 32 ---------------------------- spring-thymeleaf/.project | 42 ------------------------------------- 2 files changed, 74 deletions(-) delete mode 100644 spring-thymeleaf/.classpath delete mode 100644 spring-thymeleaf/.project diff --git a/spring-thymeleaf/.classpath b/spring-thymeleaf/.classpath deleted file mode 100644 index 81999ab717..0000000000 --- a/spring-thymeleaf/.classpath +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-thymeleaf/.project b/spring-thymeleaf/.project deleted file mode 100644 index 3c898c7e84..0000000000 --- a/spring-thymeleaf/.project +++ /dev/null @@ -1,42 +0,0 @@ - - - spring-thymeleaf - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - From bb321982a1dedbd7d2d5410ad066b652677364c1 Mon Sep 17 00:00:00 2001 From: David Morley Date: Tue, 5 Jan 2016 21:37:48 -0600 Subject: [PATCH 47/65] Rename package to conform with site name --- spring-thymeleaf/pom.xml | 2 +- .../baeldung/thymeleaf/config/WebApp.java | 72 ++++----- .../thymeleaf/config/WebMVCConfig.java | 146 +++++++++--------- .../thymeleaf/controller/HomeController.java | 2 +- .../controller/StudentController.java | 139 +++++++++-------- .../thymeleaf/formatter/NameFormatter.java | 60 +++---- .../baeldung/thymeleaf/model/Student.java | 120 +++++++------- 7 files changed, 270 insertions(+), 271 deletions(-) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/config/WebApp.java (91%) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/config/WebMVCConfig.java (92%) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/controller/HomeController.java (94%) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/controller/StudentController.java (92%) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/formatter/NameFormatter.java (91%) rename spring-thymeleaf/src/main/java/{org => com}/baeldung/thymeleaf/model/Student.java (91%) diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index ae7451a74e..16e6849f93 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -1,7 +1,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-thymeleaf 0.1-SNAPSHOT war diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java similarity index 91% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java index 45752a6269..89ad7e601e 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebApp.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebApp.java @@ -1,36 +1,36 @@ -package org.baeldung.thymeleaf.config; - -import javax.servlet.ServletRegistration.Dynamic; - -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; - -/** - * Java configuration file that is used for web application initialization - */ -public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer { - - public WebApp() { - super(); - } - - @Override - protected Class[] getRootConfigClasses() { - return null; - } - - @Override - protected Class[] getServletConfigClasses() { - return new Class[] { WebMVCConfig.class }; - } - - @Override - protected String[] getServletMappings() { - return new String[] { "/" }; - } - - @Override - protected void customizeRegistration(final Dynamic registration) { - super.customizeRegistration(registration); - } - -} +package com.baeldung.thymeleaf.config; + +import javax.servlet.ServletRegistration.Dynamic; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +/** + * Java configuration file that is used for web application initialization + */ +public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer { + + public WebApp() { + super(); + } + + @Override + protected Class[] getRootConfigClasses() { + return null; + } + + @Override + protected Class[] getServletConfigClasses() { + return new Class[] { WebMVCConfig.class }; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + + @Override + protected void customizeRegistration(final Dynamic registration) { + super.customizeRegistration(registration); + } + +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java similarity index 92% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java index c5bd460eee..51c60247a1 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/config/WebMVCConfig.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java @@ -1,73 +1,73 @@ -package org.baeldung.thymeleaf.config; - -import org.baeldung.thymeleaf.formatter.NameFormatter; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Description; -import org.springframework.context.support.ResourceBundleMessageSource; -import org.springframework.format.FormatterRegistry; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.thymeleaf.spring4.SpringTemplateEngine; -import org.thymeleaf.spring4.view.ThymeleafViewResolver; -import org.thymeleaf.templateresolver.ServletContextTemplateResolver; - -@Configuration -@EnableWebMvc -@ComponentScan({ "org.baeldung.thymeleaf" }) -/** - * Java configuration file that is used for Spring MVC and Thymeleaf - * configurations - */ -public class WebMVCConfig extends WebMvcConfigurerAdapter { - - @Bean - @Description("Thymeleaf Template Resolver") - public ServletContextTemplateResolver templateResolver() { - ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); - templateResolver.setPrefix("/WEB-INF/views/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); - - return templateResolver; - } - - @Bean - @Description("Thymeleaf Template Engine") - public SpringTemplateEngine templateEngine() { - SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - - return templateEngine; - } - - @Bean - @Description("Thymeleaf View Resolver") - public ThymeleafViewResolver viewResolver() { - ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } - - @Bean - @Description("Spring Message Resolver") - public ResourceBundleMessageSource messageSource() { - ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); - messageSource.setBasename("messages"); - return messageSource; - } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); - } - - @Override - @Description("Custom Conversion Service") - public void addFormatters(FormatterRegistry registry) { - registry.addFormatter(new NameFormatter()); - } -} +package com.baeldung.thymeleaf.config; + +import com.baeldung.thymeleaf.formatter.NameFormatter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Description; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.format.FormatterRegistry; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; + +@Configuration +@EnableWebMvc +@ComponentScan({ "com.baeldung.thymeleaf" }) +/** + * Java configuration file that is used for Spring MVC and Thymeleaf + * configurations + */ +public class WebMVCConfig extends WebMvcConfigurerAdapter { + + @Bean + @Description("Thymeleaf Template Resolver") + public ServletContextTemplateResolver templateResolver() { + ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/views/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + + return templateResolver; + } + + @Bean + @Description("Thymeleaf Template Engine") + public SpringTemplateEngine templateEngine() { + SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + + return templateEngine; + } + + @Bean + @Description("Thymeleaf View Resolver") + public ThymeleafViewResolver viewResolver() { + ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } + + @Bean + @Description("Spring Message Resolver") + public ResourceBundleMessageSource messageSource() { + ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); + } + + @Override + @Description("Custom Conversion Service") + public void addFormatters(FormatterRegistry registry) { + registry.addFormatter(new NameFormatter()); + } +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java similarity index 94% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java index 505dc8303b..a28d059acc 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/HomeController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java @@ -1,4 +1,4 @@ -package org.baeldung.thymeleaf.controller; +package com.baeldung.thymeleaf.controller; import java.text.DateFormat; import java.util.Date; diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java similarity index 92% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java index 3bef22cdae..912eb521f4 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/controller/StudentController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java @@ -1,70 +1,69 @@ -package org.baeldung.thymeleaf.controller; - -import java.util.ArrayList; -import java.util.List; - -import javax.validation.Valid; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -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.baeldung.thymeleaf.model.Student; - -/** - * Handles requests for the student model. - * - */ -@Controller -public class StudentController { - - @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) - public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { - if (!errors.hasErrors()) { - // get mock objects - List students = buildStudents(); - // add current student - students.add(student); - model.addAttribute("students", students); - } - return ((errors.hasErrors()) ? "addStudent" : "listStudents"); - } - - @RequestMapping(value = "/addStudent", method = RequestMethod.GET) - public String addStudent(Model model) { - model.addAttribute("student", new Student()); - return "addStudent"; - } - - @RequestMapping(value = "/listStudents", method = RequestMethod.GET) - public String listStudent(Model model) { - - model.addAttribute("students", buildStudents()); - - return "listStudents"; - } - - private List buildStudents() { - List students = new ArrayList(); - - Student student1 = new Student(); - student1.setId(1001); - student1.setName("John Smith"); - student1.setGender('M'); - student1.setPercentage(Float.valueOf("80.45")); - - students.add(student1); - - Student student2 = new Student(); - student2.setId(1002); - student2.setName("Jane Williams"); - student2.setGender('F'); - student2.setPercentage(Float.valueOf("60.25")); - - students.add(student2); - return students; - } -} +package com.baeldung.thymeleaf.controller; + +import java.util.ArrayList; +import java.util.List; + +import javax.validation.Valid; + +import com.baeldung.thymeleaf.model.Student; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +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; + +/** + * Handles requests for the student model. + * + */ +@Controller +public class StudentController { + + @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) + public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { + if (!errors.hasErrors()) { + // get mock objects + List students = buildStudents(); + // add current student + students.add(student); + model.addAttribute("students", students); + } + return ((errors.hasErrors()) ? "addStudent" : "listStudents"); + } + + @RequestMapping(value = "/addStudent", method = RequestMethod.GET) + public String addStudent(Model model) { + model.addAttribute("student", new Student()); + return "addStudent"; + } + + @RequestMapping(value = "/listStudents", method = RequestMethod.GET) + public String listStudent(Model model) { + + model.addAttribute("students", buildStudents()); + + return "listStudents"; + } + + private List buildStudents() { + List students = new ArrayList(); + + Student student1 = new Student(); + student1.setId(1001); + student1.setName("John Smith"); + student1.setGender('M'); + student1.setPercentage(Float.valueOf("80.45")); + + students.add(student1); + + Student student2 = new Student(); + student2.setId(1002); + student2.setName("Jane Williams"); + student2.setGender('F'); + student2.setPercentage(Float.valueOf("60.25")); + + students.add(student2); + return students; + } +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java similarity index 91% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java index 9c07ef8d14..a5d2366390 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/formatter/NameFormatter.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/formatter/NameFormatter.java @@ -1,30 +1,30 @@ -package org.baeldung.thymeleaf.formatter; - -import java.text.ParseException; -import java.util.Locale; - -import org.springframework.format.Formatter; -import org.thymeleaf.util.StringUtils; - -/** - * - * Name formatter class that implements the Spring Formatter interface. - * Formats a name(String) and return the value with spaces replaced by commas. - * - */ -public class NameFormatter implements Formatter { - - @Override - public String print(String input, Locale locale) { - return formatName(input, locale); - } - - @Override - public String parse(String input, Locale locale) throws ParseException { - return formatName(input, locale); - } - - private String formatName(String input, Locale locale) { - return StringUtils.replace(input, " ", ","); - } -} +package com.baeldung.thymeleaf.formatter; + +import java.text.ParseException; +import java.util.Locale; + +import org.springframework.format.Formatter; +import org.thymeleaf.util.StringUtils; + +/** + * + * Name formatter class that implements the Spring Formatter interface. + * Formats a name(String) and return the value with spaces replaced by commas. + * + */ +public class NameFormatter implements Formatter { + + @Override + public String print(String input, Locale locale) { + return formatName(input, locale); + } + + @Override + public String parse(String input, Locale locale) throws ParseException { + return formatName(input, locale); + } + + private String formatName(String input, Locale locale) { + return StringUtils.replace(input, " ", ","); + } +} diff --git a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java similarity index 91% rename from spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java rename to spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java index f21169dbcf..bce99f286c 100644 --- a/spring-thymeleaf/src/main/java/org/baeldung/thymeleaf/model/Student.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Student.java @@ -1,60 +1,60 @@ -package org.baeldung.thymeleaf.model; - -import java.io.Serializable; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotNull; - -/** - * - * Simple student POJO with few fields - * - */ -public class Student implements Serializable { - - private static final long serialVersionUID = -8582553475226281591L; - - @NotNull(message = "Student ID is required.") - @Min(value = 1000, message = "Student ID must be at least 4 digits.") - private Integer id; - - @NotNull(message = "Student name is required.") - private String name; - - @NotNull(message = "Student gender is required.") - private Character gender; - - private Float percentage; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Character getGender() { - return gender; - } - - public void setGender(Character gender) { - this.gender = gender; - } - - public Float getPercentage() { - return percentage; - } - - public void setPercentage(Float percentage) { - this.percentage = percentage; - } -} +package com.baeldung.thymeleaf.model; + +import java.io.Serializable; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +/** + * + * Simple student POJO with few fields + * + */ +public class Student implements Serializable { + + private static final long serialVersionUID = -8582553475226281591L; + + @NotNull(message = "Student ID is required.") + @Min(value = 1000, message = "Student ID must be at least 4 digits.") + private Integer id; + + @NotNull(message = "Student name is required.") + private String name; + + @NotNull(message = "Student gender is required.") + private Character gender; + + private Float percentage; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Character getGender() { + return gender; + } + + public void setGender(Character gender) { + this.gender = gender; + } + + public Float getPercentage() { + return percentage; + } + + public void setPercentage(Float percentage) { + this.percentage = percentage; + } +} From dbc703c63a4e07dce9f41e5aad633f7a7ef7cce2 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 6 Jan 2016 13:26:07 +0200 Subject: [PATCH 48/65] cleanup and upgrade --- spring-security-basic-auth/pom.xml | 10 ++++++---- spring-security-mvc-custom/pom.xml | 8 +++++--- .../src/main/resources/webSecurityConfig.xml | 2 ++ .../src/main/webapp/WEB-INF/view/console.jsp | 2 +- .../src/main/webapp/WEB-INF/view/homepage.jsp | 2 +- .../src/main/webapp/WEB-INF/view/login.jsp | 8 ++++---- spring-security-mvc-digest-auth/pom.xml | 8 +++++--- 7 files changed, 24 insertions(+), 16 deletions(-) diff --git a/spring-security-basic-auth/pom.xml b/spring-security-basic-auth/pom.xml index 6abefbd7ec..1e15cd5b53 100644 --- a/spring-security-basic-auth/pom.xml +++ b/spring-security-basic-auth/pom.xml @@ -82,14 +82,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -98,7 +98,7 @@ com.google.guava guava - 14.0.1 + ${guava.version} @@ -238,7 +238,9 @@ 5.2.2.Final - + 1.2 + 3.0.1 + 19.0 3.4 diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index 2e2d434fb2..b5f71847f5 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -87,14 +87,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -243,7 +243,9 @@ 5.2.2.Final - + 3.0.1 + 1.2 + 19.0 3.4 diff --git a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml index bbb22c11cb..603ded74fe 100644 --- a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml @@ -12,6 +12,8 @@ + + diff --git a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/console.jsp index d18b59a10c..5a58d8892f 100644 --- a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/console.jsp +++ b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/console.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/homepage.jsp index afd2c6da59..2568adec66 100644 --- a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/homepage.jsp +++ b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/homepage.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp index 0eb857c62a..762218e40f 100644 --- a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp @@ -4,20 +4,20 @@

Login

- + - + - + - + diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index 2dce2835f5..dc2c4d80a5 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -82,14 +82,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -238,7 +238,9 @@ 5.2.2.Final - + 1.2 + 3.0.1 + 19.03.4 From 493d953f851a0414164908bec3431a4cd729406d Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 6 Jan 2016 19:38:25 +0200 Subject: [PATCH 49/65] cleanup and upgrade --- spring-security-mvc-login/pom.xml | 6 ++++-- .../src/main/resources/webSecurityConfig.xml | 2 ++ .../src/main/webapp/WEB-INF/view/login.jsp | 4 ++-- spring-security-rest-basic-auth/pom.xml | 11 +++++++---- spring-security-rest-custom/pom.xml | 6 +----- spring-security-rest-digest-auth/pom.xml | 6 ++++-- 6 files changed, 20 insertions(+), 15 deletions(-) diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index 3d76fcb22f..ee6b37743b 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -87,14 +87,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -235,6 +235,8 @@ 5.2.2.Final + 3.0.1 + 1.2 19.0 diff --git a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml index 2bac3024c7..ec4cf60eb5 100644 --- a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml @@ -12,6 +12,8 @@ + + diff --git a/spring-security-mvc-login/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/login.jsp index 013ceccb4e..95930c139d 100644 --- a/spring-security-mvc-login/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-login/src/main/webapp/WEB-INF/view/login.jsp @@ -9,11 +9,11 @@
User:
Password:
Remember Me:
- + - + diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index 1fbeeaa9a9..767edb7778 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -88,7 +88,7 @@ com.fasterxml.jackson.core jackson-databind - 2.2.3 + ${jackson.version} @@ -134,14 +134,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -304,7 +304,10 @@ 5.2.2.Final - + 1.2 + 3.0.1 + 2.2.3 + 19.03.4 diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index 20984ba6dd..a112fdcd43 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.4.RELEASE + 1.3.1.RELEASE @@ -141,7 +141,6 @@ junit junit - ${junit.version} test @@ -199,7 +198,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} 1.8 1.8 @@ -211,7 +209,6 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} false @@ -220,7 +217,6 @@ org.apache.maven.plugins maven-surefire-plugin - ${maven-surefire-plugin.version} diff --git a/spring-security-rest-digest-auth/pom.xml b/spring-security-rest-digest-auth/pom.xml index d20220ac36..88e760458b 100644 --- a/spring-security-rest-digest-auth/pom.xml +++ b/spring-security-rest-digest-auth/pom.xml @@ -122,14 +122,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -294,6 +294,8 @@ 5.2.2.Final + 3.0.1 + 1.2 19.0 From 9c646171122e7677a50bc4f5e9cb4e2d7a5807b0 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 6 Jan 2016 20:01:17 +0200 Subject: [PATCH 50/65] cleanup and upgrade --- spring-security-mvc-session/pom.xml | 11 +++++++---- .../src/main/resources/webSecurityConfig.xml | 3 ++- .../src/main/webapp/WEB-INF/view/console.jsp | 2 +- .../src/main/webapp/WEB-INF/view/homepage.jsp | 2 +- .../src/main/webapp/WEB-INF/view/login.jsp | 8 ++++---- 5 files changed, 15 insertions(+), 11 deletions(-) diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index c9a919e684..fd90be6cc8 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -87,14 +87,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -103,7 +103,7 @@ com.codahale.metrics metrics-core - 3.0.1 + ${codahale.metrics.version} @@ -243,7 +243,10 @@ 5.2.2.Final - + 3.0.1 + 1.2 + 3.0.1 + 19.0 3.4 diff --git a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml index a9b0019fbd..02b74b0933 100644 --- a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml @@ -12,10 +12,11 @@ + + - diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp index d18b59a10c..5a58d8892f 100644 --- a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp +++ b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp index afd2c6da59..2568adec66 100644 --- a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp +++ b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp index 0eb857c62a..762218e40f 100644 --- a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp @@ -4,20 +4,20 @@

Login

- +
User:
Password:
- + - + - + From 9438588be83453db75bb037b313bdd63cb8516e8 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 7 Jan 2016 15:17:26 +0200 Subject: [PATCH 51/65] cleanup and upgrade --- .../src/main/webapp/WEB-INF/view/login.jsp | 2 +- .../pom.xml | 23 +++++++++++-------- .../src/main/resources/webSecurityConfig.xml | 14 +++++------ .../src/main/webapp/WEB-INF/view/console.jsp | 2 +- .../src/main/webapp/WEB-INF/view/homepage.jsp | 2 +- .../src/main/webapp/WEB-INF/view/login.jsp | 8 +++---- .../src/main/webapp/WEB-INF/view/login.jsp | 2 +- spring-security-oauth/pom.xml | 2 +- 8 files changed, 30 insertions(+), 25 deletions(-) diff --git a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp index 762218e40f..eb41cc79a8 100644 --- a/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-custom/src/main/webapp/WEB-INF/view/login.jsp @@ -17,7 +17,7 @@ - + diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml index 37f271f66d..1691f10f43 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -93,14 +93,14 @@ javax.servlet javax.servlet-api - 3.0.1 + ${javax.servlet.version} provided javax.servlet jstl - 1.2 + ${jstl.version} runtime @@ -109,13 +109,13 @@ com.h2database h2 - 1.4.178 + ${h2.version} postgresql postgresql - 9.1-901.jdbc4 + ${postgresql.version} runtime @@ -260,12 +260,15 @@ - 4.1.4.RELEASE - 3.2.5.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE - 4.3.10.Final - 5.1.35 + 4.3.11.Final + 5.1.37 + 1.4.190 + 9.1-901.jdbc4 + 1.7.12 @@ -273,9 +276,11 @@ 5.1.3.Final + 3.0.1 + 1.2 - 18.0 + 19.0 3.4 diff --git a/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml index 0fa077db00..a11f13c9ab 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml @@ -7,11 +7,11 @@ xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation=" - http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd - http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd + http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd - http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd - http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd"> + http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd + http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd"> @@ -35,9 +35,9 @@ - - - + + + diff --git a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/console.jsp index d18b59a10c..5a58d8892f 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/console.jsp +++ b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/console.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/homepage.jsp index afd2c6da59..2568adec66 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/homepage.jsp +++ b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/homepage.jsp @@ -16,7 +16,7 @@
- ">Logout + ">Logout \ No newline at end of file diff --git a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/login.jsp index 5697d1544a..7636cd5e61 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/login.jsp @@ -17,20 +17,20 @@

Login

- +
User:
Password:
Remember Me:
Remember Me:
- + - + - + diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp index 762218e40f..eb41cc79a8 100644 --- a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp @@ -17,7 +17,7 @@ - + diff --git a/spring-security-oauth/pom.xml b/spring-security-oauth/pom.xml index 473a4e5c35..7bb7aa86c8 100644 --- a/spring-security-oauth/pom.xml +++ b/spring-security-oauth/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.7.RELEASE + 1.3.1.RELEASE From e2d30f5683722be1f1c00570a7a69897c156f5ca Mon Sep 17 00:00:00 2001 From: David Morley Date: Thu, 7 Jan 2016 20:28:55 -0600 Subject: [PATCH 52/65] Rename package org.baeldung -> com.baeldung --- .../src/main/java/{org => com}/baeldung/Adder.java | 2 +- .../src/main/java/{org => com}/baeldung/AdderImpl.java | 2 +- core-java-8/src/main/java/{org => com}/baeldung/Bar.java | 2 +- core-java-8/src/main/java/{org => com}/baeldung/Baz.java | 2 +- core-java-8/src/main/java/{org => com}/baeldung/Foo.java | 2 +- .../src/main/java/{org => com}/baeldung/FooExtended.java | 2 +- .../src/main/java/{org => com}/baeldung/UseFoo.java | 2 +- .../baeldung/java8/Java8CollectionCleanupUnitTest.java | 2 +- .../java8/Java8FunctionalInteracesLambdasTest.java | 8 ++++---- .../{org => com}/baeldung/java8/Java8SortUnitTest.java | 4 ++-- .../{org => com}/baeldung/java8/JavaFolderSizeTest.java | 2 +- .../baeldung/java8/JavaTryWithResourcesTest.java | 2 +- .../java8/base64/ApacheCommonsEncodeDecodeTest.java | 2 +- .../baeldung/java8/base64/Java8EncodeDecodeTest.java | 2 +- .../java/{org => com}/baeldung/java8/entity/Human.java | 2 +- 15 files changed, 19 insertions(+), 19 deletions(-) rename core-java-8/src/main/java/{org => com}/baeldung/Adder.java (90%) rename core-java-8/src/main/java/{org => com}/baeldung/AdderImpl.java (93%) rename core-java-8/src/main/java/{org => com}/baeldung/Bar.java (87%) rename core-java-8/src/main/java/{org => com}/baeldung/Baz.java (87%) rename core-java-8/src/main/java/{org => com}/baeldung/Foo.java (84%) rename core-java-8/src/main/java/{org => com}/baeldung/FooExtended.java (88%) rename core-java-8/src/main/java/{org => com}/baeldung/UseFoo.java (97%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/Java8CollectionCleanupUnitTest.java (97%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/Java8FunctionalInteracesLambdasTest.java (95%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/Java8SortUnitTest.java (98%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/JavaFolderSizeTest.java (99%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/JavaTryWithResourcesTest.java (99%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java (98%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/base64/Java8EncodeDecodeTest.java (99%) rename core-java-8/src/test/java/{org => com}/baeldung/java8/entity/Human.java (98%) diff --git a/core-java-8/src/main/java/org/baeldung/Adder.java b/core-java-8/src/main/java/com/baeldung/Adder.java similarity index 90% rename from core-java-8/src/main/java/org/baeldung/Adder.java rename to core-java-8/src/main/java/com/baeldung/Adder.java index 4578990de7..e3e100f121 100644 --- a/core-java-8/src/main/java/org/baeldung/Adder.java +++ b/core-java-8/src/main/java/com/baeldung/Adder.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import java.util.function.Consumer; import java.util.function.Function; diff --git a/core-java-8/src/main/java/org/baeldung/AdderImpl.java b/core-java-8/src/main/java/com/baeldung/AdderImpl.java similarity index 93% rename from core-java-8/src/main/java/org/baeldung/AdderImpl.java rename to core-java-8/src/main/java/com/baeldung/AdderImpl.java index a62c0cd4fb..55cf84c378 100644 --- a/core-java-8/src/main/java/org/baeldung/AdderImpl.java +++ b/core-java-8/src/main/java/com/baeldung/AdderImpl.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import java.util.function.Consumer; import java.util.function.Function; diff --git a/core-java-8/src/main/java/org/baeldung/Bar.java b/core-java-8/src/main/java/com/baeldung/Bar.java similarity index 87% rename from core-java-8/src/main/java/org/baeldung/Bar.java rename to core-java-8/src/main/java/com/baeldung/Bar.java index 0dd7df6be2..f9b6f2773e 100644 --- a/core-java-8/src/main/java/org/baeldung/Bar.java +++ b/core-java-8/src/main/java/com/baeldung/Bar.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; @FunctionalInterface public interface Bar { diff --git a/core-java-8/src/main/java/org/baeldung/Baz.java b/core-java-8/src/main/java/com/baeldung/Baz.java similarity index 87% rename from core-java-8/src/main/java/org/baeldung/Baz.java rename to core-java-8/src/main/java/com/baeldung/Baz.java index bcc46af6e7..6d03f74198 100644 --- a/core-java-8/src/main/java/org/baeldung/Baz.java +++ b/core-java-8/src/main/java/com/baeldung/Baz.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; @FunctionalInterface public interface Baz { diff --git a/core-java-8/src/main/java/org/baeldung/Foo.java b/core-java-8/src/main/java/com/baeldung/Foo.java similarity index 84% rename from core-java-8/src/main/java/org/baeldung/Foo.java rename to core-java-8/src/main/java/com/baeldung/Foo.java index a10e45a8f5..c42ec86f8b 100644 --- a/core-java-8/src/main/java/org/baeldung/Foo.java +++ b/core-java-8/src/main/java/com/baeldung/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; @FunctionalInterface public interface Foo { diff --git a/core-java-8/src/main/java/org/baeldung/FooExtended.java b/core-java-8/src/main/java/com/baeldung/FooExtended.java similarity index 88% rename from core-java-8/src/main/java/org/baeldung/FooExtended.java rename to core-java-8/src/main/java/com/baeldung/FooExtended.java index 39c3a0765f..c8ed0c35dd 100644 --- a/core-java-8/src/main/java/org/baeldung/FooExtended.java +++ b/core-java-8/src/main/java/com/baeldung/FooExtended.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; @FunctionalInterface public interface FooExtended extends Baz, Bar { diff --git a/core-java-8/src/main/java/org/baeldung/UseFoo.java b/core-java-8/src/main/java/com/baeldung/UseFoo.java similarity index 97% rename from core-java-8/src/main/java/org/baeldung/UseFoo.java rename to core-java-8/src/main/java/com/baeldung/UseFoo.java index a29c5631ac..bfa7a2f2c0 100644 --- a/core-java-8/src/main/java/org/baeldung/UseFoo.java +++ b/core-java-8/src/main/java/com/baeldung/UseFoo.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import java.util.function.Function; diff --git a/core-java-8/src/test/java/org/baeldung/java8/Java8CollectionCleanupUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java similarity index 97% rename from core-java-8/src/test/java/org/baeldung/java8/Java8CollectionCleanupUnitTest.java rename to core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java index acca829b78..7329a2dc97 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/Java8CollectionCleanupUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8; +package com.baeldung.java8; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; diff --git a/core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java similarity index 95% rename from core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java rename to core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java index 3845d6ba84..0620ebd35a 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/Java8FunctionalInteracesLambdasTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java @@ -1,8 +1,8 @@ -package org.baeldung.java8; +package com.baeldung.java8; -import org.baeldung.Foo; -import org.baeldung.FooExtended; -import org.baeldung.UseFoo; +import com.baeldung.Foo; +import com.baeldung.FooExtended; +import com.baeldung.UseFoo; import org.junit.Before; import org.junit.Test; diff --git a/core-java-8/src/test/java/org/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java similarity index 98% rename from core-java-8/src/test/java/org/baeldung/java8/Java8SortUnitTest.java rename to core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index 8ed7828de0..e0e10b293e 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8; +package com.baeldung.java8; import static org.hamcrest.Matchers.equalTo; @@ -6,7 +6,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; -import org.baeldung.java8.entity.Human; +import com.baeldung.java8.entity.Human; import org.junit.Assert; import org.junit.Test; diff --git a/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java similarity index 99% rename from core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java rename to core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java index a65971bb91..2ac16b5d1d 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8; +package com.baeldung.java8; import static org.junit.Assert.assertEquals; diff --git a/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java similarity index 99% rename from core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java rename to core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java index a59682c535..18110b181d 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/JavaTryWithResourcesTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8; +package com.baeldung.java8; import java.io.PrintWriter; import java.io.StringWriter; diff --git a/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java b/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java similarity index 98% rename from core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java rename to core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java index 9745655d8a..07380cdd01 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8.base64; +package com.baeldung.java8.base64; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; diff --git a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java b/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java similarity index 99% rename from core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java rename to core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java index 7b7a0be26a..3c504edbf3 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java8.base64; +package com.baeldung.java8.base64; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; diff --git a/core-java-8/src/test/java/org/baeldung/java8/entity/Human.java b/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java similarity index 98% rename from core-java-8/src/test/java/org/baeldung/java8/entity/Human.java rename to core-java-8/src/test/java/com/baeldung/java8/entity/Human.java index ac58b301b7..cab8546129 100644 --- a/core-java-8/src/test/java/org/baeldung/java8/entity/Human.java +++ b/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java @@ -1,4 +1,4 @@ -package org.baeldung.java8.entity; +package com.baeldung.java8.entity; public class Human { private String name; From 3d564b081e8d9fb5695fea26d4f265c6e472d1e3 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 9 Jan 2016 01:34:39 +0200 Subject: [PATCH 53/65] minor cleanup work --- .../.settings/org.eclipse.jdt.core.prefs | 9 ++- .../src/main/java/com/baeldung/AdderImpl.java | 5 +- .../src/main/java/com/baeldung/Foo.java | 3 +- .../src/main/java/com/baeldung/UseFoo.java | 22 ++++--- .../Java8FunctionalInteracesLambdasTest.java | 60 +++++++++---------- .../com/baeldung/java8/Java8SortUnitTest.java | 2 +- 6 files changed, 50 insertions(+), 51 deletions(-) diff --git a/core-java-8/.settings/org.eclipse.jdt.core.prefs b/core-java-8/.settings/org.eclipse.jdt.core.prefs index c57289fc09..c38ccc1294 100644 --- a/core-java-8/.settings/org.eclipse.jdt.core.prefs +++ b/core-java-8/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,5 @@ eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault @@ -26,7 +27,7 @@ org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=error +org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning @@ -35,7 +36,7 @@ org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=error +org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore @@ -48,6 +49,7 @@ org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignor org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error org.eclipse.jdt.core.compiler.problem.nullReference=warning org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error @@ -68,6 +70,7 @@ org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled @@ -82,6 +85,7 @@ org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedImport=warning org.eclipse.jdt.core.compiler.problem.unusedLabel=warning org.eclipse.jdt.core.compiler.problem.unusedLocal=warning @@ -91,6 +95,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference= org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning org.eclipse.jdt.core.compiler.source=1.8 diff --git a/core-java-8/src/main/java/com/baeldung/AdderImpl.java b/core-java-8/src/main/java/com/baeldung/AdderImpl.java index 55cf84c378..5109f3aaba 100644 --- a/core-java-8/src/main/java/com/baeldung/AdderImpl.java +++ b/core-java-8/src/main/java/com/baeldung/AdderImpl.java @@ -6,11 +6,12 @@ import java.util.function.Function; public class AdderImpl implements Adder { @Override - public String addWithFunction(Function f) { + public String addWithFunction(Function f) { return f.apply("Something "); } @Override - public void addWithConsumer(Consumer f) {} + public void addWithConsumer(Consumer f) { + } } diff --git a/core-java-8/src/main/java/com/baeldung/Foo.java b/core-java-8/src/main/java/com/baeldung/Foo.java index c42ec86f8b..90ebdfeed3 100644 --- a/core-java-8/src/main/java/com/baeldung/Foo.java +++ b/core-java-8/src/main/java/com/baeldung/Foo.java @@ -5,5 +5,6 @@ public interface Foo { String method(String string); - default void defaultMethod() {} + default void defaultMethod() { + } } diff --git a/core-java-8/src/main/java/com/baeldung/UseFoo.java b/core-java-8/src/main/java/com/baeldung/UseFoo.java index bfa7a2f2c0..a91404ebaf 100644 --- a/core-java-8/src/main/java/com/baeldung/UseFoo.java +++ b/core-java-8/src/main/java/com/baeldung/UseFoo.java @@ -6,34 +6,32 @@ public class UseFoo { private String value = "Enclosing scope value"; - public String add(String string, Foo foo) { + public String add(final String string, final Foo foo) { return foo.method(string); } - public String addWithStandardFI(String string, Function fn) { + public String addWithStandardFI(final String string, final Function fn) { return fn.apply(string); } public String scopeExperiment() { - Foo fooIC = new Foo() { + final Foo fooIC = new Foo() { String value = "Inner class value"; @Override - public String method(String string) { - return this.value; + public String method(final String string) { + return value; } }; - String resultIC = fooIC.method(""); + final String resultIC = fooIC.method(""); - Foo fooLambda = parameter -> { - String value = "Lambda value"; + final Foo fooLambda = parameter -> { + final String value = "Lambda value"; return this.value; }; - String resultLambda = fooLambda.method(""); + final String resultLambda = fooLambda.method(""); - return "Results: resultIC = " + resultIC + - ", resultLambda = " + resultLambda; + return "Results: resultIC = " + resultIC + ", resultLambda = " + resultLambda; } - } diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java index 0620ebd35a..94448fcc83 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java @@ -1,15 +1,16 @@ package com.baeldung.java8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.util.function.Function; + +import org.junit.Before; +import org.junit.Test; + import com.baeldung.Foo; import com.baeldung.FooExtended; import com.baeldung.UseFoo; -import org.junit.Before; -import org.junit.Test; - -import java.util.function.Function; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; public class Java8FunctionalInteracesLambdasTest { @@ -22,39 +23,35 @@ public class Java8FunctionalInteracesLambdasTest { @Test public void functionalInterfaceInstantiation_whenReturnDefiniteString_thenCorrect() { - - Foo foo = parameter -> parameter + "from lambda"; - String result = useFoo.add("Message ", foo); + final Foo foo = parameter -> parameter + "from lambda"; + final String result = useFoo.add("Message ", foo); assertEquals("Message from lambda", result); } @Test public void standardFIParameter_whenReturnDefiniteString_thenCorrect() { - - Function fn = parameter -> parameter + "from lambda"; - String result = useFoo.addWithStandardFI("Message ", fn); + final Function fn = parameter -> parameter + "from lambda"; + final String result = useFoo.addWithStandardFI("Message ", fn); assertEquals("Message from lambda", result); } @Test public void defaultMethodFromExtendedInterface_whenReturnDefiniteString_thenCorrect() { - - FooExtended fooExtended = string -> string; - String result = fooExtended.defaultMethod(); + final FooExtended fooExtended = string -> string; + final String result = fooExtended.defaultMethod(); assertEquals("String from Bar", result); } @Test public void lambdaAndInnerClassInstantiation_whenReturnSameString_thenCorrect() { + final Foo foo = parameter -> parameter + "from Foo"; - Foo foo = parameter -> parameter + "from Foo"; - - Foo fooByIC = new Foo() { + final Foo fooByIC = new Foo() { @Override - public String method(String string) { + public String method(final String string) { return string + "from Foo"; } }; @@ -64,35 +61,32 @@ public class Java8FunctionalInteracesLambdasTest { @Test public void accessVariablesFromDifferentScopes_whenReturnPredefinedString_thenCorrect() { - - assertEquals("Results: resultIC = Inner class value, resultLambda = Enclosing scope value", - useFoo.scopeExperiment()); + assertEquals("Results: resultIC = Inner class value, resultLambda = Enclosing scope value", useFoo.scopeExperiment()); } @Test public void shorteningLambdas_whenReturnEqualsResults_thenCorrect() { + final Foo foo = parameter -> buildString(parameter); - Foo foo = parameter -> buildString(parameter); - - Foo fooHuge = parameter -> { String result = "Something " + parameter; - //many lines of code + final Foo fooHuge = parameter -> { + final String result = "Something " + parameter; + // many lines of code return result; }; assertEquals(foo.method("Something"), fooHuge.method("Something")); } - private String buildString(String parameter) { - String result = "Something " + parameter; - //many lines of code + private String buildString(final String parameter) { + final String result = "Something " + parameter; + // many lines of code return result; } @Test public void mutatingOfEffectivelyFinalVariable_whenNotEquals_thenCorrect() { - - int[] total = new int[1]; - Runnable r = () -> total[0]++; + final int[] total = new int[1]; + final Runnable r = () -> total[0]++; r.run(); assertNotEquals(0, total[0]); diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index e0e10b293e..2ba9e417d6 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -6,10 +6,10 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; -import com.baeldung.java8.entity.Human; import org.junit.Assert; import org.junit.Test; +import com.baeldung.java8.entity.Human; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; From d8a8c1c135a3cb1c11f29d282fc775cc9aec13e3 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 9 Jan 2016 13:01:30 +0200 Subject: [PATCH 54/65] cleanup and upgrade --- handling-spring-static-resources/.classpath | 4 +- handling-spring-static-resources/pom.xml | 20 +- .../src/main/resources/webSecurityConfig.xml | 8 +- .../src/main/webapp/WEB-INF/view/login.jsp | 6 +- .../.classpath | 2 +- .../pom.xml | 221 ++++++++++++------ .../CustomAuthenticationFailureHandler.java | 2 +- .../java/org/baeldung/spring/MvcConfig.java | 2 +- .../baeldung/spring/SecSecurityConfig.java | 10 +- .../src/main/resources/webSecurityConfig.xml | 17 +- .../src/main/webapp/WEB-INF/view/admin.jsp | 2 +- .../webapp/WEB-INF/view/changePassword.jsp | 2 +- .../src/main/webapp/WEB-INF/view/console.jsp | 2 +- .../src/main/webapp/WEB-INF/view/home.jsp | 2 +- .../src/main/webapp/WEB-INF/view/homepage.jsp | 2 +- .../src/main/webapp/WEB-INF/view/login.jsp | 11 +- .../src/main/webapp/WEB-INF/view/logout.jsp | 2 +- .../baeldung/test/ChangePasswordLiveTest.java | 2 +- 18 files changed, 202 insertions(+), 115 deletions(-) diff --git a/handling-spring-static-resources/.classpath b/handling-spring-static-resources/.classpath index 88536687a5..71a1c1e0b5 100644 --- a/handling-spring-static-resources/.classpath +++ b/handling-spring-static-resources/.classpath @@ -19,9 +19,9 @@ - + - + diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml index 677d705932..8efacc4b28 100644 --- a/handling-spring-static-resources/pom.xml +++ b/handling-spring-static-resources/pom.xml @@ -171,33 +171,29 @@ - 1.7 + 1.8 - 4.1.5.RELEASE - 3.2.5.RELEASE + 4.2.4.RELEASE + 4.0.3.RELEASE 1.8.1 2.3.2-b01 - - 4.1.5.RELEASE - 3.2.5.RELEASE - - 4.3.10.Final - 5.1.35 - 1.7.2.RELEASE + 4.3.11.Final + 5.1.37 + 1.9.2.RELEASE - 2.5.5 + 2.6.4 1.7.13 1.1.3 - 5.1.3.Final + 5.2.2.Final 19.0 diff --git a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml b/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml index 56d7f9c113..76b5015e7b 100644 --- a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml +++ b/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml @@ -2,10 +2,10 @@ @@ -21,7 +21,7 @@ - + diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp b/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp index 1b09f7c634..8c9f46c027 100644 --- a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp +++ b/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp @@ -41,15 +41,15 @@

- +
User:
Password:
Remember Me:
Remember Me:
- + - + diff --git a/spring-security-login-and-registration/.classpath b/spring-security-login-and-registration/.classpath index 91f27076be..26981b6dd7 100644 --- a/spring-security-login-and-registration/.classpath +++ b/spring-security-login-and-registration/.classpath @@ -23,7 +23,7 @@ - + diff --git a/spring-security-login-and-registration/pom.xml b/spring-security-login-and-registration/pom.xml index ffa8be484b..9e0f15688f 100644 --- a/spring-security-login-and-registration/pom.xml +++ b/spring-security-login-and-registration/pom.xml @@ -9,67 +9,108 @@ spring-security-login-and-registration war - - org.springframework.boot - spring-boot-starter-parent - 1.2.6.RELEASE - + - + + - org.springframework.boot - spring-boot-starter-web - - - org.springframework - spring-context-support + org.springframework.security + spring-security-web + ${org.springframework.security.version} org.springframework.security spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} - + + - org.springframework.boot - spring-boot-starter-tomcat - provided + org.springframework + spring-core + ${org.springframework.version} + + + commons-logging + commons-logging + + - org.apache.tomcat.embed - tomcat-embed-websocket - provided + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-context-support + ${org.springframework.version} + + + org.springframework + spring-jdbc + ${org.springframework.version} + + + org.springframework + spring-beans + ${org.springframework.version} + + + org.springframework + spring-aop + ${org.springframework.version} + + + org.springframework + spring-tx + ${org.springframework.version} + + + org.springframework + spring-expression + ${org.springframework.version} + + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} javax.servlet javax.servlet-api + ${javax.servlet.version} + provided - - javax.servlet.jsp - javax.servlet.jsp-api - ${javax.servlet.jsp-api.version} - + javax.servlet jstl + ${jstl.version} + runtime - - org.springframework.security - spring-security-taglibs - - - javax.el - el-api - 2.2 - + org.springframework spring-test + ${org.springframework.version} test @@ -77,17 +118,19 @@ org.passay passay - 1.0 + ${passay.version} org.springframework.data spring-data-jpa + ${spring-data-jpa.version} org.hibernate hibernate-entitymanager + ${hibernate.version} @@ -98,25 +141,29 @@ org.hibernate hibernate-validator + ${hibernate-validator.version} mysql mysql-connector-java + ${mysql-connector-java.version} commons-dbcp commons-dbcp + ${commons-dbcp.version} com.fasterxml.jackson.core jackson-databind + ${jackson.version} javax.mail mail - 1.4.7 + ${javax.mail.version} com.google.guava @@ -128,32 +175,51 @@ org.slf4j slf4j-api + ${org.slf4j.version} ch.qos.logback logback-classic + ${logback.version} + org.slf4j jcl-over-slf4j + ${org.slf4j.version} org.slf4j log4j-over-slf4j + ${org.slf4j.version} junit junit + ${junit.version} test - + + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + com.jayway.restassured rest-assured - 2.4.0 + ${rest-assured.version} test @@ -163,6 +229,11 @@ + + javax.el + el-api + 2.2 + @@ -181,8 +252,8 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - ${java-version} - ${java-version} + 1.8 + 1.8 @@ -192,36 +263,13 @@ ${maven-war-plugin.version} - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - tomcat8x - embedded - - - - - - - 8081 - - - - - org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} - true - **/*IntegrationTest.java - **/*LiveTest.java + @@ -229,21 +277,54 @@ + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + + - 1.7 - 4.1.6.RELEASE + 1.8 + + + 4.2.4.RELEASE 4.0.3.RELEASE + + 4.3.11.Final + 5.2.2.Final + 5.1.37 + 1.9.2.RELEASE + + 1.7.13 1.1.3 2.3.2-b01 - + 3.0.1 + 1.2 + 1 @@ -253,6 +334,14 @@ 19.0 + 1.3 + 4.12 + 1.0 + 2.4.0 + 1.4.7 + 2.6.4 + 1.4 + 1.4.17 3.3 diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java index e8d995e781..94440f8a89 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java @@ -15,7 +15,7 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa import org.springframework.stereotype.Component; import org.springframework.web.servlet.LocaleResolver; -@Component +@Component("authenticationFailureHandler") public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Autowired diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java index 56141d8f33..1234cde0d0 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java @@ -35,7 +35,7 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { super.addViewControllers(registry); - registry.addViewController("/login.html"); + registry.addViewController("/login"); registry.addViewController("/registration.html"); registry.addViewController("/logout.html"); registry.addViewController("/homepage.html"); diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 677ad514e5..9ae8f6e78b 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -51,7 +51,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { http .csrf().disable() .authorizeRequests() - .antMatchers("/j_spring_security_check*","/login*", "/logout*", "/signin/**", "/signup/**", + .antMatchers("/login*","/login*", "/logout*", "/signin/**", "/signup/**", "/user/registration*", "/regitrationConfirm*", "/expiredAccount*", "/registration*", "/badUser*", "/user/resendRegistrationToken*" ,"/forgetPassword*", "/user/resetPassword*", "/user/changePassword*", "/emailError*", "/resources/**","/old/user/registration*","/successRegister*").permitAll() @@ -59,14 +59,11 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .anyRequest().authenticated() .and() .formLogin() - .loginPage("/login.html") - .loginProcessingUrl("/j_spring_security_check") + .loginPage("/login") .defaultSuccessUrl("/homepage.html") - .failureUrl("/login.html?error=true") + .failureUrl("/login?error=true") .successHandler(myAuthenticationSuccessHandler) .failureHandler(authenticationFailureHandler) - .usernameParameter("j_username") - .passwordParameter("j_password") .permitAll() .and() .sessionManagement() @@ -75,7 +72,6 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .and() .logout() .invalidateHttpSession(false) - .logoutUrl("/j_spring_security_logout") .logoutSuccessUrl("/logout.html?logSucc=true") .deleteCookies("JSESSIONID") .permitAll(); diff --git a/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml b/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml index 3141b19142..4e67a1200f 100644 --- a/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml +++ b/spring-security-login-and-registration/src/main/resources/webSecurityConfig.xml @@ -2,7 +2,7 @@ @@ -28,10 +28,17 @@ - - - + + + + + + + + diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp index db3d8f20ba..ad0a8231ad 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp @@ -15,7 +15,7 @@ "> diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/changePassword.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/changePassword.jsp index c5ff23287d..88836e96f5 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/changePassword.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/changePassword.jsp @@ -17,7 +17,7 @@ diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/console.jsp index 1cf661af87..e06cdd39f0 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/console.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/console.jsp @@ -13,7 +13,7 @@ "> diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/home.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/home.jsp index f8db1632f6..027f583d61 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/home.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/home.jsp @@ -14,7 +14,7 @@ diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/homepage.jsp index 86cac0152f..af931ac66f 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/homepage.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/homepage.jsp @@ -15,7 +15,7 @@ "> diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp index 949b8164de..c22c3241cd 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp @@ -58,18 +58,17 @@ ${SPRING_SECURITY_LAST_EXCEPTION} - | + |

- + + - +

- +

- ">"> diff --git a/spring-security-login-and-registration/src/test/java/org/baeldung/test/ChangePasswordLiveTest.java b/spring-security-login-and-registration/src/test/java/org/baeldung/test/ChangePasswordLiveTest.java index 05377d5578..3939b5685c 100644 --- a/spring-security-login-and-registration/src/test/java/org/baeldung/test/ChangePasswordLiveTest.java +++ b/spring-security-login-and-registration/src/test/java/org/baeldung/test/ChangePasswordLiveTest.java @@ -38,7 +38,7 @@ public class ChangePasswordLiveTest { @Autowired private PasswordEncoder passwordEncoder; - private final FormAuthConfig formConfig = new FormAuthConfig(URL_PREFIX + "/j_spring_security_check", "j_username", "j_password"); + private final FormAuthConfig formConfig = new FormAuthConfig(URL_PREFIX + "/login", "username", "password"); @Before public void init() { From 2ee1f4b36bc02c29269d5e7500b36b04ae033010 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 9 Jan 2016 22:22:58 +0200 Subject: [PATCH 55/65] cleanup and upgrade --- .../src/main/webapp/WEB-INF/view/login.jsp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp index c22c3241cd..a71fe9dc3a 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp @@ -15,20 +15,20 @@ <spring:message code="label.pages.home.title"></spring:message>
/>