general formatting work

This commit is contained in:
eugenp 2016-01-30 12:01:41 +02:00
parent fc59834adb
commit 95e2d063f4
36 changed files with 71 additions and 97 deletions

View File

@ -67,8 +67,4 @@ public class CollectionJavaPartitionUnitTest {
assertThat(lastPartition, equalTo(expectedLastPartition)); assertThat(lastPartition, equalTo(expectedLastPartition));
} }
} }

View File

@ -10,5 +10,5 @@ import java.lang.annotation.Target;
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Documented @Documented
public @interface DataAccess { public @interface DataAccess {
Class<?>entity(); Class<?> entity();
} }

View File

@ -19,15 +19,13 @@ public class DataAccessAnnotationProcessor implements BeanPostProcessor {
} }
@Override @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
throws BeansException {
scanDataAccessAnnotation(bean, beanName); scanDataAccessAnnotation(bean, beanName);
return bean; return bean;
} }
@Override @Override
public Object postProcessAfterInitialization(Object bean, String beanName) public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
throws BeansException {
return bean; return bean;
} }

View File

@ -12,18 +12,14 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback; import org.springframework.util.ReflectionUtils.FieldCallback;
public final class DataAccessFieldCallback implements FieldCallback { public final class DataAccessFieldCallback implements FieldCallback {
private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class); private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class);
private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " + "value should have same type with injected generic type.";
+ "value should have same type with injected generic type."; private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " + "to raw (non-generic) declaration. This will make your code less type-safe.";
private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " private static String ERROR_CREATE_INSTANCE = "Cannot create instance of " + "type '{}' or instance creation is failed because: {}";
+ "to raw (non-generic) declaration. This will make your code less type-safe.";
private static String ERROR_CREATE_INSTANCE = "Cannot create instance of "
+ "type '{}' or instance creation is failed because: {}";
private ConfigurableListableBeanFactory configurableListableBeanFactory; private ConfigurableListableBeanFactory configurableListableBeanFactory;
private Object bean; private Object bean;
@ -34,8 +30,7 @@ public final class DataAccessFieldCallback implements FieldCallback {
} }
@Override @Override
public void doWith(final Field field) public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
throws IllegalArgumentException, IllegalAccessException {
if (!field.isAnnotationPresent(DataAccess.class)) { if (!field.isAnnotationPresent(DataAccess.class)) {
return; return;
} }
@ -54,7 +49,6 @@ public final class DataAccessFieldCallback implements FieldCallback {
} }
} }
/** /**
* For example, if user write: * For example, if user write:
* <pre> * <pre>
@ -75,8 +69,6 @@ public final class DataAccessFieldCallback implements FieldCallback {
} }
} }
public final Object getBeanInstance(final String beanName, final Class<?> genericClass, final Class<?> paramClass) { public final Object getBeanInstance(final String beanName, final Class<?> genericClass, final Class<?> paramClass) {
Object daoInstance = null; Object daoInstance = null;
if (!configurableListableBeanFactory.containsBean(beanName)) { if (!configurableListableBeanFactory.containsBean(beanName)) {

View File

@ -5,10 +5,11 @@ import org.springframework.stereotype.Repository;
@Repository @Repository
public class BeanWithGenericDAO { public class BeanWithGenericDAO {
@DataAccess(entity=Person.class) @DataAccess(entity = Person.class)
private GenericDAO<Person> personGenericDAO; private GenericDAO<Person> personGenericDAO;
public BeanWithGenericDAO() {} public BeanWithGenericDAO() {
}
public GenericDAO<Person> getPersonGenericDAO() { public GenericDAO<Person> getPersonGenericDAO() {
return personGenericDAO; return personGenericDAO;

View File

@ -15,7 +15,6 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { CustomAnnotationConfiguration.class }) @ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
public class DataAccessFieldCallbackTest { public class DataAccessFieldCallbackTest {
@ -36,8 +35,7 @@ public class DataAccessFieldCallbackTest {
} }
@Test @Test
public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue() public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue() throws NoSuchFieldException, SecurityException {
throws NoSuchFieldException, SecurityException {
final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO); final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO);
final Type fieldType = BeanWithGenericDAO.class.getDeclaredField("personGenericDAO").getGenericType(); final Type fieldType = BeanWithGenericDAO.class.getDeclaredField("personGenericDAO").getGenericType();
final boolean result = callback.genericTypeIsValid(Person.class, fieldType); final boolean result = callback.genericTypeIsValid(Person.class, fieldType);

View File

@ -40,8 +40,7 @@ public class SpringBatchConfig {
private Resource outputXml; private Resource outputXml;
@Bean @Bean
public ItemReader<Transaction> itemReader() public ItemReader<Transaction> itemReader() throws UnexpectedInputException, ParseException {
throws UnexpectedInputException, ParseException {
FlatFileItemReader<Transaction> reader = new FlatFileItemReader<Transaction>(); FlatFileItemReader<Transaction> reader = new FlatFileItemReader<Transaction>();
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
String[] tokens = { "username", "userid", "transactiondate", "amount" }; String[] tokens = { "username", "userid", "transactiondate", "amount" };
@ -61,8 +60,7 @@ public class SpringBatchConfig {
} }
@Bean @Bean
public ItemWriter<Transaction> itemWriter(Marshaller marshaller) public ItemWriter<Transaction> itemWriter(Marshaller marshaller) throws MalformedURLException {
throws MalformedURLException {
StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<Transaction>(); StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<Transaction>();
itemWriter.setMarshaller(marshaller); itemWriter.setMarshaller(marshaller);
itemWriter.setRootTagName("transactionRecord"); itemWriter.setRootTagName("transactionRecord");
@ -78,11 +76,8 @@ public class SpringBatchConfig {
} }
@Bean @Bean
protected Step step1(ItemReader<Transaction> reader, protected Step step1(ItemReader<Transaction> reader, ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> writer) {
ItemProcessor<Transaction, Transaction> processor, return steps.get("step1").<Transaction, Transaction> chunk(10).reader(reader).processor(processor).writer(writer).build();
ItemWriter<Transaction> writer) {
return steps.get("step1").<Transaction, Transaction> chunk(10)
.reader(reader).processor(processor).writer(writer).build();
} }
@Bean(name = "firstBatchJob") @Bean(name = "firstBatchJob")

View File

@ -38,8 +38,7 @@ public class SpringConfig {
} }
@Bean @Bean
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) public DataSourceInitializer dataSourceInitializer(DataSource dataSource) throws MalformedURLException {
throws MalformedURLException {
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScript(dropReopsitoryTables); databasePopulator.addScript(dropReopsitoryTables);

View File

@ -48,9 +48,7 @@ public class Transaction {
@Override @Override
public String toString() { public String toString() {
return "Transaction [username=" + username + ", userId=" + userId return "Transaction [username=" + username + ", userId=" + userId + ", transactionDate=" + transactionDate + ", amount=" + amount + "]";
+ ", transactionDate=" + transactionDate + ", amount=" + amount
+ "]";
} }
} }

View File

@ -3,8 +3,7 @@ package org.baeldung.spring_batch_intro.service;
import org.baeldung.spring_batch_intro.model.Transaction; import org.baeldung.spring_batch_intro.model.Transaction;
import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemProcessor;
public class CustomItemProcessor implements public class CustomItemProcessor implements ItemProcessor<Transaction, Transaction> {
ItemProcessor<Transaction, Transaction> {
public Transaction process(Transaction item) { public Transaction process(Transaction item) {
System.out.println("Processing..." + item); System.out.println("Processing..." + item);

View File

@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public class ChildDao extends AbstractHibernateDao<Child>implements IChildDao { public class ChildDao extends AbstractHibernateDao<Child> implements IChildDao {
@Autowired @Autowired
private SessionFactory sessionFactory; private SessionFactory sessionFactory;

View File

@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public class FooDao extends AbstractHibernateDao<Foo>implements IFooDao { public class FooDao extends AbstractHibernateDao<Foo> implements IFooDao {
@Autowired @Autowired
private SessionFactory sessionFactory; private SessionFactory sessionFactory;

View File

@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public class ParentDao extends AbstractHibernateDao<Parent>implements IParentDao { public class ParentDao extends AbstractHibernateDao<Parent> implements IParentDao {
@Autowired @Autowired
private SessionFactory sessionFactory; private SessionFactory sessionFactory;

View File

@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class ChildService extends AbstractService<Child>implements IChildService { public class ChildService extends AbstractService<Child> implements IChildService {
@Autowired @Autowired
private IChildDao dao; private IChildDao dao;

View File

@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class FooService extends AbstractService<Foo>implements IFooService { public class FooService extends AbstractService<Foo> implements IFooService {
@Autowired @Autowired
private IFooDao dao; private IFooDao dao;

View File

@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class ParentService extends AbstractService<Parent>implements IParentService { public class ParentService extends AbstractService<Parent> implements IParentService {
@Autowired @Autowired
private IParentDao dao; private IParentDao dao;

View File

@ -4,7 +4,7 @@ import org.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public class FooDao extends AbstractHibernateDao<Foo>implements IFooDao { public class FooDao extends AbstractHibernateDao<Foo> implements IFooDao {
public FooDao() { public FooDao() {
super(); super();

View File

@ -8,6 +8,6 @@ import org.springframework.stereotype.Repository;
@Repository @Repository
@Scope(BeanDefinition.SCOPE_PROTOTYPE) @Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class GenericHibernateDao<T extends Serializable> extends AbstractHibernateDao<T>implements IGenericDao<T> { public class GenericHibernateDao<T extends Serializable> extends AbstractHibernateDao<T> implements IGenericDao<T> {
// //
} }

View File

@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class ChildService extends AbstractHibernateService<Child>implements IChildService { public class ChildService extends AbstractHibernateService<Child> implements IChildService {
@Autowired @Autowired
private IChildDao dao; private IChildDao dao;

View File

@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class FooService extends AbstractHibernateService<Foo>implements IFooService { public class FooService extends AbstractHibernateService<Foo> implements IFooService {
@Autowired @Autowired
@Qualifier("fooHibernateDao") @Qualifier("fooHibernateDao")

View File

@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class ParentService extends AbstractHibernateService<Parent>implements IParentService { public class ParentService extends AbstractHibernateService<Parent> implements IParentService {
@Autowired @Autowired
private IParentDao dao; private IParentDao dao;

View File

@ -41,7 +41,6 @@ public class JPABarAuditTest {
logger.info("tearDownAfterClass()"); logger.info("tearDownAfterClass()");
} }
@Autowired @Autowired
@Qualifier("barJpaService") @Qualifier("barJpaService")
private IBarService barService; private IBarService barService;
@ -51,7 +50,6 @@ public class JPABarAuditTest {
private EntityManager em; private EntityManager em;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
logger.info("setUp()"); logger.info("setUp()");
@ -64,7 +62,6 @@ public class JPABarAuditTest {
em.close(); em.close();
} }
@Test @Test
public final void whenBarsModified_thenBarsAudited() { public final void whenBarsModified_thenBarsAudited() {
@ -84,7 +81,6 @@ public class JPABarAuditTest {
bar1.setName("BAR1b"); bar1.setName("BAR1b");
barService.update(bar1); barService.update(bar1);
// get BAR1 and BAR2 from the DB and check the audit values // get BAR1 and BAR2 from the DB and check the audit values
// detach instances from persistence context to make sure we fire db // detach instances from persistence context to make sure we fire db
em.detach(bar1); em.detach(bar1);

View File

@ -4,7 +4,7 @@ import org.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public class FooDao extends AbstractJpaDAO<Foo>implements IFooDao { public class FooDao extends AbstractJpaDAO<Foo> implements IFooDao {
public FooDao() { public FooDao() {
super(); super();

View File

@ -30,7 +30,7 @@ public class User {
private String email; private String email;
@ManyToMany(fetch = FetchType.EAGER) @ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") )
@JsonApiToMany @JsonApiToMany
@JsonApiIncludeByDefault @JsonApiIncludeByDefault
private Set<Role> roles; private Set<Role> roles;

View File

@ -24,13 +24,16 @@ public class LoggingAspect {
}; };
@Pointcut("@target(org.springframework.stereotype.Repository)") @Pointcut("@target(org.springframework.stereotype.Repository)")
public void repositoryMethods() {} public void repositoryMethods() {
}
@Pointcut("@annotation(org.baeldung.aop.annotations.Loggable)") @Pointcut("@annotation(org.baeldung.aop.annotations.Loggable)")
public void loggableMethods() {} public void loggableMethods() {
}
@Pointcut("@args(org.baeldung.aop.annotations.Entity)") @Pointcut("@args(org.baeldung.aop.annotations.Entity)")
public void methodsAcceptingEntities() {} public void methodsAcceptingEntities() {
}
@Before("repositoryMethods()") @Before("repositoryMethods()")
public void logMethodCall(JoinPoint jp) { public void logMethodCall(JoinPoint jp) {

View File

@ -16,7 +16,8 @@ public class PerformanceAspect {
private static Logger logger = Logger.getLogger(PerformanceAspect.class.getName()); private static Logger logger = Logger.getLogger(PerformanceAspect.class.getName());
@Pointcut("within(@org.springframework.stereotype.Repository *)") @Pointcut("within(@org.springframework.stereotype.Repository *)")
public void repositoryClassMethods() {} public void repositoryClassMethods() {
}
@Around("repositoryClassMethods()") @Around("repositoryClassMethods()")
public Object measureMethodExecutionTime(ProceedingJoinPoint pjp) throws Throwable { public Object measureMethodExecutionTime(ProceedingJoinPoint pjp) throws Throwable {

View File

@ -21,13 +21,16 @@ public class PublishingAspect {
} }
@Pointcut("@target(org.springframework.stereotype.Repository)") @Pointcut("@target(org.springframework.stereotype.Repository)")
public void repositoryMethods() {} public void repositoryMethods() {
}
@Pointcut("execution(* *..create*(Long,..))") @Pointcut("execution(* *..create*(Long,..))")
public void firstLongParamMethods() {} public void firstLongParamMethods() {
}
@Pointcut("repositoryMethods() && firstLongParamMethods()") @Pointcut("repositoryMethods() && firstLongParamMethods()")
public void entityCreationMethods() {} public void entityCreationMethods() {
}
@AfterReturning(value = "entityCreationMethods()", returning = "entity") @AfterReturning(value = "entityCreationMethods()", returning = "entity")
public void logMethodCall(JoinPoint jp, Object entity) throws Throwable { public void logMethodCall(JoinPoint jp, Object entity) throws Throwable {

View File

@ -14,9 +14,6 @@ public class Foo {
@Override @Override
public String toString() { public String toString() {
return "Foo{" + return "Foo{" + "id=" + id + ", name='" + name + '\'' + '}';
"id=" + id +
", name='" + name + '\'' +
'}';
} }
} }

View File

@ -22,8 +22,7 @@ public class UserController {
} }
@RequestMapping(value = "/processForm", method = RequestMethod.POST) @RequestMapping(value = "/processForm", method = RequestMethod.POST)
public String processForm(@ModelAttribute(value = "user") final User user, public String processForm(@ModelAttribute(value = "user") final User user, final Model model) {
final Model model) {
// Insert User into DB // Insert User into DB
model.addAttribute("name", user.getFirstname() + " " + user.getLastname()); model.addAttribute("name", user.getFirstname() + " " + user.getLastname());
return "hello"; return "hello";

View File

@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class AopLoggingTest { public class AopLoggingTest {
@Before @Before

View File

@ -23,7 +23,7 @@ import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class AopPerformanceTest { public class AopPerformanceTest {
@Before @Before

View File

@ -22,7 +22,7 @@ import java.util.regex.Pattern;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class AopPublishingTest { public class AopPublishingTest {
@Before @Before
@ -60,8 +60,7 @@ public class AopPublishingTest {
dao.create(1L, "Bar"); dao.create(1L, "Bar");
String logMessage = messages.get(0); String logMessage = messages.get(0);
Pattern pattern = Pattern.compile("Created foo instance: " + Pattern pattern = Pattern.compile("Created foo instance: " + Pattern.quote(new Foo(1L, "Bar").toString()));
Pattern.quote(new Foo(1L, "Bar").toString()));
assertTrue(pattern.matcher(logMessage).matches()); assertTrue(pattern.matcher(logMessage).matches());
} }
} }

View File

@ -5,7 +5,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration @Configuration
@ComponentScan(basePackages = {"org.baeldung.dao", "org.baeldung.aop", "org.baeldung.events"}) @ComponentScan(basePackages = { "org.baeldung.dao", "org.baeldung.aop", "org.baeldung.events" })
@EnableAspectJAutoProxy @EnableAspectJAutoProxy
public class TestConfig { public class TestConfig {
} }

View File

@ -19,8 +19,8 @@ public @interface PasswordMatches {
String message() default "Passwords don't match"; String message() default "Passwords don't match";
Class<?>[]groups() default {}; Class<?>[] groups() default {};
Class<? extends Payload>[]payload() default {}; Class<? extends Payload>[] payload() default {};
} }

View File

@ -20,7 +20,7 @@ public @interface ValidEmail {
String message() default "Invalid Email"; String message() default "Invalid Email";
Class<?>[]groups() default {}; Class<?>[] groups() default {};
Class<? extends Payload>[]payload() default {}; Class<? extends Payload>[] payload() default {};
} }

View File

@ -20,8 +20,8 @@ public @interface ValidPassword {
String message() default "Invalid Password"; String message() default "Invalid Password";
Class<?>[]groups() default {}; Class<?>[] groups() default {};
Class<? extends Payload>[]payload() default {}; Class<? extends Payload>[] payload() default {};
} }