- 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-all/src/main/java/org/baeldung/caching/config/CachingConfig.java b/spring-all/src/main/java/org/baeldung/caching/config/CachingConfig.java
new file mode 100644
index 0000000000..4153ec9636
--- /dev/null
+++ b/spring-all/src/main/java/org/baeldung/caching/config/CachingConfig.java
@@ -0,0 +1,29 @@
+package org.baeldung.caching.config;
+
+import java.util.Arrays;
+
+import org.baeldung.caching.example.CustomerDataService;
+import org.springframework.cache.CacheManager;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.cache.concurrent.ConcurrentMapCache;
+import org.springframework.cache.support.SimpleCacheManager;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@EnableCaching
+public class CachingConfig {
+
+ @Bean
+ public CustomerDataService customerDataService() {
+ return new CustomerDataService();
+ }
+
+ @Bean
+ public CacheManager cacheManager() {
+ final SimpleCacheManager cacheManager = new SimpleCacheManager();
+ cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("directory"), new ConcurrentMapCache("addresses")));
+ return cacheManager;
+ }
+
+}
diff --git a/spring-all/src/main/java/org/baeldung/caching/config/MyAppConfig.java b/spring-all/src/main/java/org/baeldung/caching/config/MyAppConfig.java
deleted file mode 100644
index 467e50c15e..0000000000
--- a/spring-all/src/main/java/org/baeldung/caching/config/MyAppConfig.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package org.baeldung.caching.config;
-
-import org.springframework.cache.annotation.EnableCaching;
-import org.springframework.context.annotation.Configuration;
-
-@Configuration
-@EnableCaching
-public class MyAppConfig {
- // Your configuration code goes here.
-}
diff --git a/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java b/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java
index 86026de93a..fe4de5d282 100644
--- a/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java
+++ b/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java
@@ -10,12 +10,18 @@ import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Component;
@Component
-@CacheConfig(cacheNames = { "addressDemo" })
+@CacheConfig(cacheNames = { "addresses" })
public class CustomerDataService {
@Autowired
CacheManager cacheManager;
+ // this method configuration is equivalent to xml configuration
+ @Cacheable(value = "addresses", key = "#customer.name")
+ public String getAddress(final Customer customer) {
+ return customer.getAddress();
+ }
+
/**
* The method returns the customer's address,
only it doesn't find it the cache- addresses and directory.
diff --git a/spring-all/src/main/java/org/baeldung/customannotation/DataAccess.java b/spring-all/src/main/java/org/baeldung/customannotation/DataAccess.java
index 11bc30a84a..9a8a493a6d 100644
--- a/spring-all/src/main/java/org/baeldung/customannotation/DataAccess.java
+++ b/spring-all/src/main/java/org/baeldung/customannotation/DataAccess.java
@@ -10,5 +10,5 @@ import java.lang.annotation.Target;
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Documented
public @interface DataAccess {
- Class>entity();
+ Class> entity();
}
diff --git a/spring-all/src/main/java/org/baeldung/customannotation/DataAccessAnnotationProcessor.java b/spring-all/src/main/java/org/baeldung/customannotation/DataAccessAnnotationProcessor.java
index 7902da746e..c792073745 100644
--- a/spring-all/src/main/java/org/baeldung/customannotation/DataAccessAnnotationProcessor.java
+++ b/spring-all/src/main/java/org/baeldung/customannotation/DataAccessAnnotationProcessor.java
@@ -19,15 +19,13 @@ public class DataAccessAnnotationProcessor implements BeanPostProcessor {
}
@Override
- public Object postProcessBeforeInitialization(Object bean, String beanName)
- throws BeansException {
+ public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
scanDataAccessAnnotation(bean, beanName);
return bean;
}
@Override
- public Object postProcessAfterInitialization(Object bean, String beanName)
- throws BeansException {
+ public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
diff --git a/spring-all/src/main/java/org/baeldung/customannotation/DataAccessFieldCallback.java b/spring-all/src/main/java/org/baeldung/customannotation/DataAccessFieldCallback.java
index 16526fa56f..8cb62affc4 100644
--- a/spring-all/src/main/java/org/baeldung/customannotation/DataAccessFieldCallback.java
+++ b/spring-all/src/main/java/org/baeldung/customannotation/DataAccessFieldCallback.java
@@ -12,18 +12,14 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;
-
public final class DataAccessFieldCallback implements FieldCallback {
private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class);
private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
- private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) "
- + "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 ERROR_CREATE_INSTANCE = "Cannot create instance of "
- + "type '{}' or instance creation is failed because: {}";
+ private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " + "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 ERROR_CREATE_INSTANCE = "Cannot create instance of " + "type '{}' or instance creation is failed because: {}";
private ConfigurableListableBeanFactory configurableListableBeanFactory;
private Object bean;
@@ -34,15 +30,14 @@ public final class DataAccessFieldCallback implements FieldCallback {
}
@Override
- public void doWith(final Field field)
- throws IllegalArgumentException, IllegalAccessException {
+ public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
if (!field.isAnnotationPresent(DataAccess.class)) {
return;
}
ReflectionUtils.makeAccessible(field);
final Type fieldGenericType = field.getGenericType();
- // In this example, get actual "GenericDAO' type.
- final Class> generic = field.getType();
+ // In this example, get actual "GenericDAO' type.
+ final Class> generic = field.getType();
final Class> classValue = field.getDeclaredAnnotation(DataAccess.class).entity();
if (genericTypeIsValid(classValue, fieldGenericType)) {
@@ -54,7 +49,6 @@ public final class DataAccessFieldCallback implements FieldCallback {
}
}
-
/**
* For example, if user write:
*
@@ -75,8 +69,6 @@ public final class DataAccessFieldCallback implements FieldCallback {
}
}
-
-
public final Object getBeanInstance(final String beanName, final Class> genericClass, final Class> paramClass) {
Object daoInstance = null;
if (!configurableListableBeanFactory.containsBean(beanName)) {
@@ -90,7 +82,7 @@ public final class DataAccessFieldCallback implements FieldCallback {
logger.error(ERROR_CREATE_INSTANCE, genericClass.getTypeName(), e);
throw new RuntimeException(e);
}
-
+
daoInstance = configurableListableBeanFactory.initializeBean(toRegister, beanName);
configurableListableBeanFactory.autowireBeanProperties(daoInstance, AUTOWIRE_MODE, true);
configurableListableBeanFactory.registerSingleton(beanName, daoInstance);
diff --git a/spring-all/src/main/resources/config.xml b/spring-all/src/main/resources/config.xml
index 244e9027ec..23458539b0 100644
--- a/spring-all/src/main/resources/config.xml
+++ b/spring-all/src/main/resources/config.xml
@@ -10,8 +10,7 @@
-
-
+
@@ -21,7 +20,6 @@
-
@@ -34,7 +32,7 @@
-
+
diff --git a/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingBehaviorTest.java b/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingBehaviorTest.java
index 0b3edaffb3..a4a3733dd8 100644
--- a/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingBehaviorTest.java
+++ b/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingBehaviorTest.java
@@ -1,11 +1,11 @@
package org.baeldung.caching.test;
+import org.baeldung.caching.config.CachingConfig;
import org.baeldung.caching.example.Customer;
import org.baeldung.caching.example.CustomerDataService;
import org.junit.Test;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
@Component
public class SpringCachingBehaviorTest {
@@ -13,12 +13,16 @@ public class SpringCachingBehaviorTest {
@Test
public void testCaching() {
@SuppressWarnings("resource")
- final ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
+ final
+ // final ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
+ AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
+ context.register(CachingConfig.class);
+ context.refresh();
final CustomerDataService service = context.getBean(CustomerDataService.class);
final Customer cust = new Customer("Tom", "67-2, Downing Street, NY");
- service.getAddress1(cust);
- service.getAddress1(cust);
+ service.getAddress(cust);
+ service.getAddress(cust);
// fail("Unable to instantiate the CustomerDataService");
}
diff --git a/spring-all/src/test/java/org/baeldung/customannotation/BeanWithGenericDAO.java b/spring-all/src/test/java/org/baeldung/customannotation/BeanWithGenericDAO.java
index 32d4660f41..9ba915f296 100644
--- a/spring-all/src/test/java/org/baeldung/customannotation/BeanWithGenericDAO.java
+++ b/spring-all/src/test/java/org/baeldung/customannotation/BeanWithGenericDAO.java
@@ -5,10 +5,11 @@ import org.springframework.stereotype.Repository;
@Repository
public class BeanWithGenericDAO {
- @DataAccess(entity=Person.class)
+ @DataAccess(entity = Person.class)
private GenericDAO personGenericDAO;
- public BeanWithGenericDAO() {}
+ public BeanWithGenericDAO() {
+ }
public GenericDAO getPersonGenericDAO() {
return personGenericDAO;
diff --git a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java
index f025a3e00a..e47d03c961 100644
--- a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java
+++ b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java
@@ -15,7 +15,6 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
public class DataAccessFieldCallbackTest {
@@ -36,8 +35,7 @@ public class DataAccessFieldCallbackTest {
}
@Test
- public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue()
- throws NoSuchFieldException, SecurityException {
+ public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue() throws NoSuchFieldException, SecurityException {
final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO);
final Type fieldType = BeanWithGenericDAO.class.getDeclaredField("personGenericDAO").getGenericType();
final boolean result = callback.genericTypeIsValid(Person.class, fieldType);
diff --git a/spring-batch/.classpath b/spring-batch/.classpath
new file mode 100644
index 0000000000..e7ac9faf11
--- /dev/null
+++ b/spring-batch/.classpath
@@ -0,0 +1,31 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/spring-batch/.project b/spring-batch/.project
new file mode 100644
index 0000000000..0159a7237c
--- /dev/null
+++ b/spring-batch/.project
@@ -0,0 +1,29 @@
+
+
+ spring-batch
+
+
+
+
+
+ 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-batch/README.md b/spring-batch/README.md
new file mode 100644
index 0000000000..953e652cea
--- /dev/null
+++ b/spring-batch/README.md
@@ -0,0 +1,7 @@
+=========
+
+## Spring Batch
+
+
+### Relevant Articles:
+- [Introduction to Spring Batch](http://www.baeldung.com/introduction-to-spring-batch)
diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml
new file mode 100644
index 0000000000..c85aeff6f3
--- /dev/null
+++ b/spring-batch/pom.xml
@@ -0,0 +1,43 @@
+
+ 4.0.0
+
+ org.baeldung
+ spring-batch
+ 0.1-SNAPSHOT
+ jar
+
+ spring-batch
+ http://maven.apache.org
+
+
+ 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}
+
+
+
+
diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java
new file mode 100644
index 0000000000..2ce4dae6e6
--- /dev/null
+++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java
@@ -0,0 +1,32 @@
+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.annotation.AnnotationConfigApplicationContext;
+
+public class App {
+ public static void main(final String[] args) {
+ // Spring Java config
+ final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
+ context.register(SpringConfig.class);
+ context.register(SpringBatchConfig.class);
+ context.refresh();
+
+ // Spring xml config
+ // ApplicationContext context = new ClassPathXmlApplicationContext("spring-batch.xml");
+
+ final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
+ final Job job = (Job) context.getBean("firstBatchJob");
+ System.out.println("Starting the batch job");
+ try {
+ final JobExecution execution = jobLauncher.run(job, new JobParameters());
+ System.out.println("Job Status : " + execution.getStatus());
+ System.out.println("Job succeeded");
+ } catch (final Exception e) {
+ e.printStackTrace();
+ System.out.println("Job failed");
+ }
+ }
+}
\ No newline at end of file
diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java
new file mode 100644
index 0000000000..9973005c7c
--- /dev/null
+++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java
@@ -0,0 +1,88 @@
+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 {
+ 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.setLinesToSkip(1);
+ 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/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java
new file mode 100644
index 0000000000..ed7d302047
--- /dev/null
+++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java
@@ -0,0 +1,78 @@
+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());
+ // JobRepositoryFactoryBean's methods Throws Generic Exception,
+ // it would have been better to have a specific one
+ factory.afterPropertiesSet();
+ return (JobRepository) factory.getObject();
+ }
+
+ private PlatformTransactionManager getTransactionManager() {
+ return new ResourcelessTransactionManager();
+ }
+
+ 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;
+ }
+
+}
\ No newline at end of file
diff --git a/spring-batch/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
new file mode 100644
index 0000000000..3b2b9610f2
--- /dev/null
+++ b/spring-batch/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;
+
+ /* getters and setters for the attributes */
+
+ 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/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
new file mode 100644
index 0000000000..ebee1d2802
--- /dev/null
+++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java
@@ -0,0 +1,12 @@
+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) {
+ System.out.println("Processing..." + item);
+ return item;
+ }
+}
\ No newline at end of file
diff --git a/spring-batch/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
new file mode 100644
index 0000000000..94f9e7d94e
--- /dev/null
+++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java
@@ -0,0 +1,35 @@
+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();
+ // 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("userid"));
+ 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/src/main/resources/input/record.csv b/spring-batch/src/main/resources/input/record.csv
new file mode 100644
index 0000000000..e554becb2a
--- /dev/null
+++ b/spring-batch/src/main/resources/input/record.csv
@@ -0,0 +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/src/main/resources/spring-batch-intro.xml b/spring-batch/src/main/resources/spring-batch-intro.xml
new file mode 100644
index 0000000000..93606d232f
--- /dev/null
+++ b/spring-batch/src/main/resources/spring-batch-intro.xml
@@ -0,0 +1,57 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ org.baeldung.spring_batch_intro.model.Transaction
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/spring-batch/src/main/resources/spring.xml b/spring-batch/src/main/resources/spring.xml
new file mode 100644
index 0000000000..dea261c5e6
--- /dev/null
+++ b/spring-batch/src/main/resources/spring.xml
@@ -0,0 +1,45 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-batch/xml/output.xml b/spring-batch/xml/output.xml
new file mode 100644
index 0000000000..acf4969341
--- /dev/null
+++ b/spring-batch/xml/output.xml
@@ -0,0 +1 @@
+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
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/README.md b/spring-data-cassandra/README.md
index a245ff62a1..456eefcf18 100644
--- a/spring-data-cassandra/README.md
+++ b/spring-data-cassandra/README.md
@@ -2,6 +2,7 @@
### Relevant Articles:
- [Introduction to Spring Data Cassandra](http://www.baeldung.com/spring-data-cassandra-tutorial)
+- [Using the CassandraTemplate from Spring Data](http://www.baeldung.com/spring-data-cassandratemplate-cqltemplate)
### Build the Project with Tests Running
```
diff --git a/spring-data-cassandra/pom.xml b/spring-data-cassandra/pom.xml
index b2b649a422..7e21859b5d 100644
--- a/spring-data-cassandra/pom.xml
+++ b/spring-data-cassandra/pom.xml
@@ -11,8 +11,11 @@
UTF-8
+
+ 4.2.3.RELEASE
+
1.3.2.RELEASE
- 4.2.2.RELEASE
+
4.11
1.7.12
1.1.3
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/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-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 69%
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 031b5c0b6f..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
@@ -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,19 +28,18 @@ 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 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