Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2017-08-11 23:54:15 +02:00
commit 99bad7dfeb
19 changed files with 521 additions and 25 deletions

View File

@ -6,7 +6,7 @@ public class ServiceMain {
public static void main(String[] args) throws InterruptedException { public static void main(String[] args) throws InterruptedException {
ProcessHandle thisProcess = ProcessHandle.current(); ProcessHandle thisProcess = ProcessHandle.current();
long pid = thisProcess.getPid(); long pid = thisProcess.pid();
Optional<String[]> opArgs = Optional.ofNullable(args); Optional<String[]> opArgs = Optional.ofNullable(args);
String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command")); String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));

View File

@ -10,7 +10,7 @@ import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
public class Java9ObjectsAPIUnitTest { public class Java9ObjectsAPIUnitTest {
@Test @Test
public void givenNullObject_whenRequireNonNullElse_thenElse(){ public void givenNullObject_whenRequireNonNullElse_thenElse(){
assertThat(Objects.<List>requireNonNullElse(null, Collections.EMPTY_LIST), assertThat(Objects.<List>requireNonNullElse(null, Collections.EMPTY_LIST),
@ -23,6 +23,11 @@ public class Java9ObjectsAPIUnitTest {
Collections.EMPTY_LIST), is(List.of("item1", "item2"))); Collections.EMPTY_LIST), is(List.of("item1", "item2")));
} }
@Test(expected = NullPointerException.class)
public void givenNull_whenRequireNonNullElse_thenException(){
Objects.<List>requireNonNullElse(null, null);
}
@Test @Test
public void givenObject_whenRequireNonNullElseGet_thenObject(){ public void givenObject_whenRequireNonNullElseGet_thenObject(){
assertThat(Objects.<List>requireNonNullElseGet(null, List::of), assertThat(Objects.<List>requireNonNullElseGet(null, List::of),
@ -32,40 +37,39 @@ public class Java9ObjectsAPIUnitTest {
@Test @Test
public void givenNumber_whenInvokeCheckIndex_thenNumber(){ public void givenNumber_whenInvokeCheckIndex_thenNumber(){
int length = 5; int length = 5;
assertThat(Objects.checkIndex(4, length), is(4)); assertThat(Objects.checkIndex(4, length), is(4));
try{
Objects.checkIndex(5, length);
}catch(Exception ex){
assertThat(ex, instanceOf(IndexOutOfBoundsException.class));
}
} }
@Test(expected = IndexOutOfBoundsException.class)
public void givenOutOfRangeNumber_whenInvokeCheckIndex_thenException(){
int length = 5;
Objects.checkIndex(5, length);
}
@Test @Test
public void givenSubRange_whenCheckFromToIndex_thenNumber(){ public void givenSubRange_whenCheckFromToIndex_thenNumber(){
int length = 6; int length = 6;
assertThat(Objects.checkFromToIndex(2,length,length), is(2)); assertThat(Objects.checkFromToIndex(2,length,length), is(2));
try{
Objects.checkFromToIndex(2,7,length);
}catch(Exception ex){
assertThat(ex, instanceOf(IndexOutOfBoundsException.class));
}
} }
@Test @Test(expected = IndexOutOfBoundsException.class)
public void giveSubRange_whenCheckFromIndexSize_thenNumber(){ public void givenInvalidSubRange_whenCheckFromToIndex_thenException(){
int length = 6; int length = 6;
Objects.checkFromToIndex(2,7,length);
}
assertThat(Objects.checkFromToIndex(2,5,length), is(2));
try{ @Test
Objects.checkFromToIndex(2,6,length); public void givenSubRange_whenCheckFromIndexSize_thenNumber(){
}catch(Exception ex){ int length = 6;
assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); assertThat(Objects.checkFromIndexSize(2,3,length), is(2));
} }
@Test(expected = IndexOutOfBoundsException.class)
public void givenInvalidSubRange_whenCheckFromIndexSize_thenException(){
int length = 6;
Objects.checkFromIndexSize(2, 6, length);
} }

View File

@ -29,6 +29,8 @@
- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) - [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph)
- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) - [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue)
- [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) - [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss)
- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -462,6 +462,11 @@
<artifactId>pcollections</artifactId> <artifactId>pcollections</artifactId>
<version>${pcollections.version}</version> <version>${pcollections.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.machinezoo.noexception</groupId>
<artifactId>noexception</artifactId>
<version>1.1.0</version>
</dependency>
<dependency> <dependency>
<groupId>org.eclipse.collections</groupId> <groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId> <artifactId>eclipse-collections</artifactId>
@ -510,4 +515,4 @@
<rome.version>1.0</rome.version> <rome.version>1.0</rome.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version> <eclipse-collections.version>8.2.0</eclipse-collections.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,24 @@
package com.baeldung.noexception;
import com.machinezoo.noexception.ExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CustomExceptionHandler extends ExceptionHandler {
private Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);
@Override
public boolean handle(Throwable throwable) {
if (throwable.getClass()
.isAssignableFrom(RuntimeException.class)
|| throwable.getClass()
.isAssignableFrom(Error.class)) {
return false;
} else {
logger.error("Caught Exception ", throwable);
return true;
}
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.noexception;
import com.machinezoo.noexception.Exceptions;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NoExceptionUnitTest {
private static Logger logger = LoggerFactory.getLogger(NoExceptionUnitTest.class);
@Test
public void whenStdExceptionHandling_thenCatchAndLog() {
try {
System.out.println("Result is " + Integer.parseInt("foobar"));
} catch (Throwable exception) {
logger.error("Caught exception:", exception);
}
}
@Test
public void whenDefaultNoException_thenCatchAndLog() {
Exceptions.log().run(() -> System.out.println("Result is " + Integer.parseInt("foobar")));
}
@Test
public void givenLogger_whenDefaultNoException_thenCatchAndLogWithClassName() {
Exceptions.log(logger).run(() -> System.out.println("Result is " + Integer.parseInt("foobar")));
}
@Test
public void givenLoggerAndMessage_whenDefaultNoException_thenCatchAndLogWithMessage() {
Exceptions.log(logger, "Something went wrong:").run(() -> System.out.println("Result is " + Integer.parseInt("foobar")));
}
@Test
public void givenDefaultValue_whenDefaultNoException_thenCatchAndLogPrintDefault() {
System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> Integer.parseInt("foobar")).orElse(-1));
}
@Test(expected = Error.class)
public void givenCustomHandler_whenError_thenRethrowError() {
CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler();
customExceptionHandler.run(() -> throwError());
}
@Test
public void givenCustomHandler_whenException_thenCatchAndLog() {
CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler();
customExceptionHandler.run(() -> throwException());
}
private static void throwError() {
throw new Error("This is very bad.");
}
private static void throwException() {
String testString = "foo";
testString.charAt(5);
}
}

View File

@ -0,0 +1,77 @@
/*
* Copyright 2006-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.baeldung.spring_batch_intro.partitioner;
import java.util.HashMap;
import java.util.Map;
import org.springframework.batch.core.partition.support.Partitioner;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
public class CustomMultiResourcePartitioner implements Partitioner {
private static final String DEFAULT_KEY_NAME = "fileName";
private static final String PARTITION_KEY = "partition";
private Resource[] resources = new Resource[0];
private String keyName = DEFAULT_KEY_NAME;
/**
* The resources to assign to each partition. In Spring configuration you
* can use a pattern to select multiple resources.
* @param resources the resources to use
*/
public void setResources(Resource[] resources) {
this.resources = resources;
}
/**
* The name of the key for the file name in each {@link ExecutionContext}.
* Defaults to "fileName".
* @param keyName the value of the key
*/
public void setKeyName(String keyName) {
this.keyName = keyName;
}
/**
* Assign the filename of each of the injected resources to an
* {@link ExecutionContext}.
*
* @see Partitioner#partition(int)
*/
@Override
public Map<String, ExecutionContext> partition(int gridSize) {
Map<String, ExecutionContext> map = new HashMap<String, ExecutionContext>(gridSize);
int i = 0, k = 1;
for (Resource resource : resources) {
ExecutionContext context = new ExecutionContext();
Assert.state(resource.exists(), "Resource does not exist: " + resource);
context.putString(keyName, resource.getFilename());
context.putString("opFileName", "output" + k++ + ".xml");
map.put(PARTITION_KEY + i, context);
i++;
}
return map;
}
}

View File

@ -0,0 +1,169 @@
package org.baeldung.spring_batch_intro.partitioner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.ParseException;
import javax.sql.DataSource;
import org.baeldung.spring_batch_intro.model.Transaction;
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.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
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.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.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.task.TaskExecutor;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
@EnableBatchProcessing
public class SpringbatchPartitionConfig {
@Autowired
ResourcePatternResolver resoursePatternResolver;
@Autowired
private JobBuilderFactory jobs;
@Autowired
private StepBuilderFactory steps;
@Bean(name = "partitionerJob")
public Job partitionerJob() throws UnexpectedInputException, MalformedURLException, ParseException {
return jobs.get("partitionerJob")
.start(partitionStep())
.build();
}
@Bean
public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException {
return steps.get("partitionStep")
.partitioner("slaveStep", partitioner())
.step(slaveStep())
.taskExecutor(taskExecutor())
.build();
}
@Bean
public Step slaveStep() throws UnexpectedInputException, MalformedURLException, ParseException {
return steps.get("slaveStep")
.<Transaction, Transaction> chunk(1)
.reader(itemReader(null))
.writer(itemWriter(marshaller(), null))
.build();
}
@Bean
public CustomMultiResourcePartitioner partitioner() {
CustomMultiResourcePartitioner partitioner = new CustomMultiResourcePartitioner();
Resource[] resources;
try {
resources = resoursePatternResolver.getResources("file:src/main/resources/input/partitioner/*.csv");
} catch (IOException e) {
throw new RuntimeException("I/O problems when resolving the input file pattern.", e);
}
partitioner.setResources(resources);
return partitioner;
}
@Bean
@StepScope
public FlatFileItemReader<Transaction> itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException {
FlatFileItemReader<Transaction> reader = new FlatFileItemReader<Transaction>();
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
String[] tokens = { "username", "userid", "transactiondate", "amount" };
tokenizer.setNames(tokens);
reader.setResource(new ClassPathResource("input/partitioner/" + filename));
DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<Transaction>();
lineMapper.setLineTokenizer(tokenizer);
lineMapper.setFieldSetMapper(new RecordFieldSetMapper());
reader.setLinesToSkip(1);
reader.setLineMapper(lineMapper);
return reader;
}
@Bean(destroyMethod = "")
@StepScope
public StaxEventItemWriter<Transaction> itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) throws MalformedURLException {
StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<>();
itemWriter.setMarshaller(marshaller);
itemWriter.setRootTagName("transactionRecord");
itemWriter.setResource(new FileSystemResource("src/main/resources/output/" + filename));
return itemWriter;
}
@Bean
public Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(new Class[] { Transaction.class });
return marshaller;
}
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setMaxPoolSize(5);
taskExecutor.setCorePoolSize(5);
taskExecutor.setQueueCapacity(5);
taskExecutor.afterPropertiesSet();
return taskExecutor;
}
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 DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql")
.addScript("classpath:org/springframework/batch/core/schema-h2.sql")
.build();
return db;
}
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;
}
}

View File

@ -0,0 +1,28 @@
package org.baeldung.spring_batch_intro.partitioner;
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 SpringbatchPartitionerApp {
public static void main(final String[] args) {
// Spring Java config
final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(SpringbatchPartitionConfig.class);
context.refresh();
final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
final Job job = (Job) context.getBean("partitionerJob");
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");
}
}
}

View File

@ -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
1 username user_id transaction_date transaction_amount
2 devendra 1234 31/10/2015 10000
3 john 2134 3/12/2015 12321
4 robin 2134 2/02/2015 23411

View File

@ -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
1 username user_id transaction_date transaction_amount
2 devendra 1234 31/10/2015 10000
3 john 2134 3/12/2015 12321
4 robin 2134 2/02/2015 23411

View File

@ -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
1 username user_id transaction_date transaction_amount
2 devendra 1234 31/10/2015 10000
3 john 2134 3/12/2015 12321
4 robin 2134 2/02/2015 23411

View File

@ -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
1 username user_id transaction_date transaction_amount
2 devendra 1234 31/10/2015 10000
3 john 2134 3/12/2015 12321
4 robin 2134 2/02/2015 23411

View File

@ -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
1 username user_id transaction_date transaction_amount
2 devendra 1234 31/10/2015 10000
3 john 2134 3/12/2015 12321
4 robin 2134 2/02/2015 23411

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<transactionRecord>
<transactionRecord>
<amount>10000.0</amount>
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
<userId>1234</userId>
<username>devendra</username>
</transactionRecord>
<transactionRecord>
<amount>12321.0</amount>
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
<userId>2134</userId>
<username>john</username>
</transactionRecord>
<transactionRecord>
<amount>23411.0</amount>
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
<userId>2134</userId>
<username>robin</username>
</transactionRecord>
</transactionRecord>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<transactionRecord>
<transactionRecord>
<amount>10000.0</amount>
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
<userId>1234</userId>
<username>devendra</username>
</transactionRecord>
<transactionRecord>
<amount>12321.0</amount>
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
<userId>2134</userId>
<username>john</username>
</transactionRecord>
<transactionRecord>
<amount>23411.0</amount>
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
<userId>2134</userId>
<username>robin</username>
</transactionRecord>
</transactionRecord>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<transactionRecord>
<transactionRecord>
<amount>10000.0</amount>
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
<userId>1234</userId>
<username>devendra</username>
</transactionRecord>
<transactionRecord>
<amount>12321.0</amount>
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
<userId>2134</userId>
<username>john</username>
</transactionRecord>
<transactionRecord>
<amount>23411.0</amount>
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
<userId>2134</userId>
<username>robin</username>
</transactionRecord>
</transactionRecord>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<transactionRecord>
<transactionRecord>
<amount>10000.0</amount>
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
<userId>1234</userId>
<username>devendra</username>
</transactionRecord>
<transactionRecord>
<amount>12321.0</amount>
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
<userId>2134</userId>
<username>john</username>
</transactionRecord>
<transactionRecord>
<amount>23411.0</amount>
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
<userId>2134</userId>
<username>robin</username>
</transactionRecord>
</transactionRecord>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<transactionRecord>
<transactionRecord>
<amount>10000.0</amount>
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
<userId>1234</userId>
<username>devendra</username>
</transactionRecord>
<transactionRecord>
<amount>12321.0</amount>
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
<userId>2134</userId>
<username>john</username>
</transactionRecord>
<transactionRecord>
<amount>23411.0</amount>
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
<userId>2134</userId>
<username>robin</username>
</transactionRecord>
</transactionRecord>