cleanup work

This commit is contained in:
eugenp 2016-03-12 19:44:59 +02:00
parent 91b65dac91
commit eba672e9ad
10 changed files with 100 additions and 103 deletions

View File

@ -6,6 +6,7 @@
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="src" path="target/metamodel"/>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"> <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes> <attributes>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>

View File

@ -1,11 +1,10 @@
package org.baeldung.dao; package org.baeldung.dao;
import org.baeldung.entity.Person;
import javax.persistence.Tuple;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.baeldung.entity.Person;
public interface PersonDao { public interface PersonDao {
public Person save(Person person); public Person save(Person person);

View File

@ -1,18 +1,17 @@
package org.baeldung.dao; package org.baeldung.dao;
import com.mysema.query.group.GroupBy; import java.util.List;
import com.mysema.query.jpa.impl.JPAQuery; import java.util.Map;
import com.mysema.query.jpa.impl.JPAQueryFactory;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.baeldung.entity.Person; import org.baeldung.entity.Person;
import org.baeldung.entity.QPerson; import org.baeldung.entity.QPerson;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import javax.inject.Provider; import com.mysema.query.group.GroupBy;
import javax.persistence.EntityManager; import com.mysema.query.jpa.impl.JPAQuery;
import javax.persistence.PersistenceContext;
import javax.persistence.Tuple;
import java.util.List;
import java.util.Map;
@Repository @Repository
public class PersonDaoImpl implements PersonDao { public class PersonDaoImpl implements PersonDao {
@ -20,49 +19,48 @@ public class PersonDaoImpl implements PersonDao {
@PersistenceContext @PersistenceContext
private EntityManager em; private EntityManager em;
public Person save(Person person) { @Override
public Person save(final Person person) {
em.persist(person); em.persist(person);
return person; return person;
} }
@Override @Override
public List<Person> findPersonsByFirstnameQueryDSL(String firstname) { public List<Person> findPersonsByFirstnameQueryDSL(final String firstname) {
JPAQuery query = new JPAQuery(em); final JPAQuery query = new JPAQuery(em);
QPerson person = QPerson.person; final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname)).list(person); return query.from(person).where(person.firstname.eq(firstname)).list(person);
} }
@Override @Override
public List<Person> findPersonsByFirstnameAndSurnameQueryDSL(String firstname, String surname) { public List<Person> findPersonsByFirstnameAndSurnameQueryDSL(final String firstname, final String surname) {
JPAQuery query = new JPAQuery(em); final JPAQuery query = new JPAQuery(em);
QPerson person = QPerson.person; final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname).and( return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).list(person);
person.surname.eq(surname))).list(person);
} }
@Override @Override
public List<Person> findPersonsByFirstnameInDescendingOrderQueryDSL(String firstname) { public List<Person> findPersonsByFirstnameInDescendingOrderQueryDSL(final String firstname) {
JPAQuery query = new JPAQuery(em); final JPAQuery query = new JPAQuery(em);
QPerson person = QPerson.person; final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname)).orderBy( return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).list(person);
person.surname.desc()).list(person);
} }
@Override @Override
public int findMaxAge() { public int findMaxAge() {
JPAQuery query = new JPAQuery(em); final JPAQuery query = new JPAQuery(em);
QPerson person = QPerson.person; final QPerson person = QPerson.person;
return query.from(person).list(person.age.max()).get(0); return query.from(person).list(person.age.max()).get(0);
} }
@Override @Override
public Map<String, Integer> findMaxAgeByName() { public Map<String, Integer> findMaxAgeByName() {
JPAQuery query = new JPAQuery(em); final JPAQuery query = new JPAQuery(em);
QPerson person = QPerson.person; final QPerson person = QPerson.person;
return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age))); return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age)));
} }

View File

@ -1,6 +1,10 @@
package org.baeldung.entity; package org.baeldung.entity;
import javax.persistence.*; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity @Entity
public class Person { public class Person {
@ -21,12 +25,12 @@ public class Person {
Person() { Person() {
} }
public Person(String firstname, String surname) { public Person(final String firstname, final String surname) {
this.firstname = firstname; this.firstname = firstname;
this.surname = surname; this.surname = surname;
} }
public Person(String firstname, String surname, int age) { public Person(final String firstname, final String surname, final int age) {
this(firstname, surname); this(firstname, surname);
this.age = age; this.age = age;
} }
@ -35,7 +39,7 @@ public class Person {
return id; return id;
} }
public void setId(Long id) { public void setId(final Long id) {
this.id = id; this.id = id;
} }
@ -43,7 +47,7 @@ public class Person {
return firstname; return firstname;
} }
public void setFirstname(String firstname) { public void setFirstname(final String firstname) {
this.firstname = firstname; this.firstname = firstname;
} }
@ -51,7 +55,7 @@ public class Person {
return surname; return surname;
} }
public void setSurname(String surname) { public void setSurname(final String surname) {
this.surname = surname; this.surname = surname;
} }
@ -59,7 +63,7 @@ public class Person {
return age; return age;
} }
public void setAge(int age) { public void setAge(final int age) {
this.age = age; this.age = age;
} }
} }

View File

@ -1,6 +1,7 @@
package org.baeldung.dao; package org.baeldung.dao;
import junit.framework.Assert; import java.util.Map;
import org.baeldung.entity.Person; import org.baeldung.entity.Person;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -10,47 +11,48 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.Map; import junit.framework.Assert;
@ContextConfiguration("/test-context.xml") @ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@Transactional @Transactional
@TransactionConfiguration(defaultRollback=true) @TransactionConfiguration(defaultRollback = true)
public class PersonDaoTest { public class PersonDaoTest {
@Autowired @Autowired
private PersonDao personDao; private PersonDao personDao;
//
@Test @Test
public void testCreation() { public void testCreation() {
personDao.save(new Person("Erich", "Gamma")); personDao.save(new Person("Erich", "Gamma"));
Person person = new Person("Kent", "Beck"); final Person person = new Person("Kent", "Beck");
personDao.save(person); personDao.save(person);
personDao.save(new Person("Ralph", "Johnson")); personDao.save(new Person("Ralph", "Johnson"));
Person personFromDb = personDao.findPersonsByFirstnameQueryDSL("Kent").get(0); final Person personFromDb = personDao.findPersonsByFirstnameQueryDSL("Kent").get(0);
Assert.assertEquals(person.getId(), personFromDb.getId()); Assert.assertEquals(person.getId(), personFromDb.getId());
} }
@Test @Test
public void testMultipleFilter() { public void testMultipleFilter() {
personDao.save(new Person("Erich", "Gamma")); personDao.save(new Person("Erich", "Gamma"));
Person person = personDao.save(new Person("Ralph", "Beck")); final Person person = personDao.save(new Person("Ralph", "Beck"));
Person person2 = personDao.save(new Person("Ralph", "Johnson")); final Person person2 = personDao.save(new Person("Ralph", "Johnson"));
Person personFromDb = personDao.findPersonsByFirstnameAndSurnameQueryDSL("Ralph", "Johnson").get(0); final Person personFromDb = personDao.findPersonsByFirstnameAndSurnameQueryDSL("Ralph", "Johnson").get(0);
Assert.assertNotSame(person.getId(), personFromDb.getId()); Assert.assertNotSame(person.getId(), personFromDb.getId());
Assert.assertEquals(person2.getId(), personFromDb.getId()); Assert.assertEquals(person2.getId(), personFromDb.getId());
} }
@Test @Test
public void testOrdering() { public void testOrdering() {
Person person = personDao.save(new Person("Kent", "Gamma")); final Person person = personDao.save(new Person("Kent", "Gamma"));
personDao.save(new Person("Ralph", "Johnson")); personDao.save(new Person("Ralph", "Johnson"));
Person person2 = personDao.save(new Person("Kent", "Zivago")); final Person person2 = personDao.save(new Person("Kent", "Zivago"));
Person personFromDb = personDao.findPersonsByFirstnameInDescendingOrderQueryDSL("Kent").get(0); final Person personFromDb = personDao.findPersonsByFirstnameInDescendingOrderQueryDSL("Kent").get(0);
Assert.assertNotSame(person.getId(), personFromDb.getId()); Assert.assertNotSame(person.getId(), personFromDb.getId());
Assert.assertEquals(person2.getId(), personFromDb.getId()); Assert.assertEquals(person2.getId(), personFromDb.getId());
} }
@ -61,7 +63,7 @@ public class PersonDaoTest {
personDao.save(new Person("Ralph", "Johnson", 35)); personDao.save(new Person("Ralph", "Johnson", 35));
personDao.save(new Person("Kent", "Zivago", 30)); personDao.save(new Person("Kent", "Zivago", 30));
int maxAge = personDao.findMaxAge(); final int maxAge = personDao.findMaxAge();
Assert.assertTrue(maxAge == 35); Assert.assertTrue(maxAge == 35);
} }
@ -71,7 +73,7 @@ public class PersonDaoTest {
personDao.save(new Person("Ralph", "Johnson", 35)); personDao.save(new Person("Ralph", "Johnson", 35));
personDao.save(new Person("Kent", "Zivago", 30)); personDao.save(new Person("Kent", "Zivago", 30));
Map<String, Integer> maxAge = personDao.findMaxAgeByName(); final Map<String, Integer> maxAge = personDao.findMaxAgeByName();
Assert.assertTrue(maxAge.size() == 2); Assert.assertTrue(maxAge.size() == 2);
Assert.assertSame(35, maxAge.get("Ralph")); Assert.assertSame(35, maxAge.get("Ralph"));
Assert.assertSame(30, maxAge.get("Kent")); Assert.assertSame(30, maxAge.get("Kent"));

View File

@ -102,12 +102,12 @@
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId> <artifactId>jackson-core</artifactId>
<version>2.1.2</version> <version>2.7.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
<version>2.1.2</version> <version>2.7.2</version>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -25,7 +25,7 @@ public class MyUserDetailsService implements UserDetailsService {
private final Log logger = LogFactory.getLog(this.getClass()); private final Log logger = LogFactory.getLog(this.getClass());
private Map<String, User> availableUsers = new HashMap<String, User>(); private final Map<String, User> availableUsers = new HashMap<String, User>();
public MyUserDetailsService() { public MyUserDetailsService() {
@ -33,12 +33,13 @@ public class MyUserDetailsService implements UserDetailsService {
} }
@Override //
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
logger.info("Load user by username " + username); logger.info("Load user by username " + username);
UserDetails user = availableUsers.get(username); final UserDetails user = availableUsers.get(username);
if (user == null) { if (user == null) {
throw new UsernameNotFoundException("Username not found"); throw new UsernameNotFoundException("Username not found");
} else { } else {
@ -52,7 +53,6 @@ public class MyUserDetailsService implements UserDetailsService {
* in database or retrieved from another system). * in database or retrieved from another system).
*/ */
private void populateDemoUsers() { private void populateDemoUsers() {
logger.info("Populate demo users"); logger.info("Populate demo users");
availableUsers.put("user", createUser("user", "password", Arrays.asList(SecurityRole.ROLE_USER))); availableUsers.put("user", createUser("user", "password", Arrays.asList(SecurityRole.ROLE_USER)));
@ -70,12 +70,11 @@ public class MyUserDetailsService implements UserDetailsService {
* Role names user is assigned to * Role names user is assigned to
* @return User * @return User
*/ */
private User createUser(String username, String password, List<SecurityRole> roles) { private User createUser(final String username, final String password, final List<SecurityRole> roles) {
logger.info("Create user " + username); logger.info("Create user " + username);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (SecurityRole role : roles) { for (final SecurityRole role : roles) {
authorities.add(new SimpleGrantedAuthority(role.toString())); authorities.add(new SimpleGrantedAuthority(role.toString()));
} }
return new User(username, password, true, true, true, true, authorities); return new User(username, password, true, true, true, true, authorities);

View File

@ -18,11 +18,13 @@ import com.google.common.base.Preconditions;
@Configuration @Configuration
@EnableTransactionManagement @EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" }) @PropertySource({ "classpath:persistence-h2.properties" })
public class DatabaseConfig { public class PersistenceConfig {
@Autowired @Autowired
private Environment env; private Environment env;
//
@Bean @Bean
public DataSource dataSource() { public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource(); final DriverManagerDataSource dataSource = new DriverManagerDataSource();
@ -32,4 +34,5 @@ public class DatabaseConfig {
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource; return dataSource;
} }
} }

View File

@ -1,11 +1,9 @@
package org.baeldung.spring; package org.baeldung.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.ImportResource;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
/** /**
* Spring Security Configuration. * Spring Security Configuration.
@ -15,9 +13,6 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand
@ImportResource({ "classpath:webSecurityConfig.xml" }) @ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecurityConfig extends WebSecurityConfigurerAdapter { public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationSuccessHandler mySimpleUrlAuthenticationSuccessHandler;
public SecurityConfig() { public SecurityConfig() {
super(); super();
} }

View File

@ -1,55 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation=" xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.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/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/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.2.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"> http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd"
>
<http use-expressions="true"> <http use-expressions="true">
<intercept-url pattern="/anonymous*" access="isAnonymous()" /> <intercept-url pattern="/anonymous*" access="isAnonymous()"/>
<intercept-url pattern="/login*" access="permitAll" /> <intercept-url pattern="/login*" access="permitAll"/>
<intercept-url pattern="/**" access="isAuthenticated()" /> <intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login login-page='/login.html' authentication-success-handler-ref="mySimpleUrlAuthenticationSuccessHandler" authentication-failure-url="/login.html?error=true" /> <form-login login-page='/login.html' authentication-success-handler-ref="mySimpleUrlAuthenticationSuccessHandler" authentication-failure-url="/login.html?error=true"/>
<logout delete-cookies="JSESSIONID" /> <logout delete-cookies="JSESSIONID"/>
<remember-me data-source-ref="dataSource" token-validity-seconds="86400"/> <remember-me data-source-ref="dataSource" token-validity-seconds="86400"/>
</http> </http>
<!-- create H2 embedded database table on startup --> <!-- create H2 embedded database table on startup -->
<jdbc:embedded-database id="dataSource" type="H2"> <jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="classpath:/persisted_logins_create_table.sql"/> <jdbc:script location="classpath:/persisted_logins_create_table.sql"/>
</jdbc:embedded-database> </jdbc:embedded-database>
<!-- Persistent Remember Me Service --> <!-- Persistent Remember Me Service -->
<beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices"> <beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<beans:constructor-arg value="myAppKey" /> <beans:constructor-arg value="myAppKey"/>
<beans:constructor-arg ref="jdbcTokenRepository" /> <beans:constructor-arg ref="jdbcTokenRepository"/>
<beans:constructor-arg ref="myUserDetailsService" /> <beans:constructor-arg ref="myUserDetailsService"/>
</beans:bean> </beans:bean>
<!-- Uses a database table to maintain a set of persistent login data --> <!-- Uses a database table to maintain a set of persistent login data -->
<beans:bean id="jdbcTokenRepository" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl"> <beans:bean id="jdbcTokenRepository" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
<beans:property name="createTableOnStartup" value="false" /> <beans:property name="createTableOnStartup" value="false"/>
<beans:property name="dataSource" ref="dataSource" /> <beans:property name="dataSource" ref="dataSource"/>
</beans:bean> </beans:bean>
<!-- Authentication Manager (uses same UserDetailsService as RememberMeService)--> <!-- Authentication Manager (uses same UserDetailsService as RememberMeService) -->
<authentication-manager alias="authenticationManager"> <authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="myUserDetailsService"> <authentication-provider user-service-ref="myUserDetailsService">
</authentication-provider> </authentication-provider>
</authentication-manager> </authentication-manager>
</beans:beans> </beans:beans>