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"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="target/metamodel"/>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>

View File

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

View File

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

View File

@ -1,6 +1,10 @@
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
public class Person {
@ -21,12 +25,12 @@ public class Person {
Person() {
}
public Person(String firstname, String surname) {
public Person(final String firstname, final String surname) {
this.firstname = firstname;
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.age = age;
}
@ -35,7 +39,7 @@ public class Person {
return id;
}
public void setId(Long id) {
public void setId(final Long id) {
this.id = id;
}
@ -43,7 +47,7 @@ public class Person {
return firstname;
}
public void setFirstname(String firstname) {
public void setFirstname(final String firstname) {
this.firstname = firstname;
}
@ -51,7 +55,7 @@ public class Person {
return surname;
}
public void setSurname(String surname) {
public void setSurname(final String surname) {
this.surname = surname;
}
@ -59,7 +63,7 @@ public class Person {
return age;
}
public void setAge(int age) {
public void setAge(final int age) {
this.age = age;
}
}

View File

@ -1,6 +1,7 @@
package org.baeldung.dao;
import junit.framework.Assert;
import java.util.Map;
import org.baeldung.entity.Person;
import org.junit.Test;
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.transaction.annotation.Transactional;
import java.util.Map;
import junit.framework.Assert;
@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@TransactionConfiguration(defaultRollback=true)
@TransactionConfiguration(defaultRollback = true)
public class PersonDaoTest {
@Autowired
private PersonDao personDao;
//
@Test
public void testCreation() {
personDao.save(new Person("Erich", "Gamma"));
Person person = new Person("Kent", "Beck");
final Person person = new Person("Kent", "Beck");
personDao.save(person);
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());
}
@Test
public void testMultipleFilter() {
personDao.save(new Person("Erich", "Gamma"));
Person person = personDao.save(new Person("Ralph", "Beck"));
Person person2 = personDao.save(new Person("Ralph", "Johnson"));
final Person person = personDao.save(new Person("Ralph", "Beck"));
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.assertEquals(person2.getId(), personFromDb.getId());
}
@Test
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"));
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.assertEquals(person2.getId(), personFromDb.getId());
}
@ -61,7 +63,7 @@ public class PersonDaoTest {
personDao.save(new Person("Ralph", "Johnson", 35));
personDao.save(new Person("Kent", "Zivago", 30));
int maxAge = personDao.findMaxAge();
final int maxAge = personDao.findMaxAge();
Assert.assertTrue(maxAge == 35);
}
@ -71,7 +73,7 @@ public class PersonDaoTest {
personDao.save(new Person("Ralph", "Johnson", 35));
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.assertSame(35, maxAge.get("Ralph"));
Assert.assertSame(30, maxAge.get("Kent"));

View File

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

View File

@ -25,7 +25,7 @@ public class MyUserDetailsService implements UserDetailsService {
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() {
@ -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);
UserDetails user = availableUsers.get(username);
final UserDetails user = availableUsers.get(username);
if (user == null) {
throw new UsernameNotFoundException("Username not found");
} else {
@ -52,7 +53,6 @@ public class MyUserDetailsService implements UserDetailsService {
* in database or retrieved from another system).
*/
private void populateDemoUsers() {
logger.info("Populate demo users");
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
* @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);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (SecurityRole role : roles) {
final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (final SecurityRole role : roles) {
authorities.add(new SimpleGrantedAuthority(role.toString()));
}
return new User(username, password, true, true, true, true, authorities);

View File

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

View File

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

View File

@ -1,28 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<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: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"
<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: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="
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.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">
<intercept-url pattern="/anonymous*" access="isAnonymous()" />
<intercept-url pattern="/login*" access="permitAll" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<intercept-url pattern="/anonymous*" access="isAnonymous()"/>
<intercept-url pattern="/login*" access="permitAll"/>
<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"/>
@ -35,18 +31,18 @@
<!-- Persistent Remember Me Service -->
<beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<beans:constructor-arg value="myAppKey" />
<beans:constructor-arg ref="jdbcTokenRepository" />
<beans:constructor-arg ref="myUserDetailsService" />
<beans:constructor-arg value="myAppKey"/>
<beans:constructor-arg ref="jdbcTokenRepository"/>
<beans:constructor-arg ref="myUserDetailsService"/>
</beans:bean>
<!-- 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:property name="createTableOnStartup" value="false" />
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="createTableOnStartup" value="false"/>
<beans:property name="dataSource" ref="dataSource"/>
</beans:bean>
<!-- Authentication Manager (uses same UserDetailsService as RememberMeService)-->
<!-- Authentication Manager (uses same UserDetailsService as RememberMeService) -->
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="myUserDetailsService">
</authentication-provider>