From 89d89e6dcef7df1a291394cb501ab46cd246f57a Mon Sep 17 00:00:00 2001 From: Parth Karia Date: Fri, 11 Aug 2017 15:25:43 +0530 Subject: [PATCH 01/11] BAEL-243 Spring Batch using Partitioner --- .../CustomMultiResourcePartitioner.java | 77 ++++++++ .../SpringbatchPartitionConfig.java | 169 ++++++++++++++++++ .../SpringbatchPartitionerApp.java | 28 +++ 3 files changed, 274 insertions(+) create mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java create mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java create mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java new file mode 100644 index 0000000000..4cae69efbd --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java @@ -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 partition(int gridSize) { + Map map = new HashMap(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; + } + +} diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java new file mode 100644 index 0000000000..fe8339a8b4 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java @@ -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") + . 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 itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException { + FlatFileItemReader reader = new FlatFileItemReader(); + DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); + String[] tokens = { "username", "userid", "transactiondate", "amount" }; + tokenizer.setNames(tokens); + reader.setResource(new ClassPathResource("input/partitioner/" + filename)); + DefaultLineMapper lineMapper = new DefaultLineMapper(); + lineMapper.setLineTokenizer(tokenizer); + lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); + reader.setLinesToSkip(1); + reader.setLineMapper(lineMapper); + return reader; + } + + @Bean(destroyMethod = "") + @StepScope + public StaxEventItemWriter itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) throws MalformedURLException { + StaxEventItemWriter 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; + } +} diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java new file mode 100644 index 0000000000..1d6d922969 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java @@ -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"); + } + } +} \ No newline at end of file From 9f9fbc4523d58ce40570f20a9dd631fda3322d41 Mon Sep 17 00:00:00 2001 From: parthkaria Date: Tue, 29 Aug 2017 17:14:13 +0530 Subject: [PATCH 02/11] BAEL-1106 Introduction to javax.measure --- core-java/pom.xml | 8 +++ .../com/baeldung/javax/measure/WaterTank.java | 26 +++++++ .../javax/measure/WaterTankTests.java | 68 +++++++++++++++++++ 3 files changed, 102 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/javax/measure/WaterTank.java create mode 100644 core-java/src/test/java/com/baeldung/javax/measure/WaterTankTests.java diff --git a/core-java/pom.xml b/core-java/pom.xml index 0f8a665fa1..5410ea54e2 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -212,6 +212,13 @@ streamex ${streamex.version} + + + javax.measure + jsr-275 + ${javax-measure.version} + + @@ -438,6 +445,7 @@ 1.5.1 1.13 0.6.5 + 0.9.1 1.3 diff --git a/core-java/src/main/java/com/baeldung/javax/measure/WaterTank.java b/core-java/src/main/java/com/baeldung/javax/measure/WaterTank.java new file mode 100644 index 0000000000..1ab9eee53f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/javax/measure/WaterTank.java @@ -0,0 +1,26 @@ +package com.baeldung.javax.measure; + +import javax.measure.Measure; +import javax.measure.quantity.Volume; + +public class WaterTank { + + private Measure capacityMeasure; + private double capacityDouble; + + public void setCapacityMeasure(Measure capacityMeasure) { + this.capacityMeasure = capacityMeasure; + } + + public void setCapacityDouble(double capacityDouble) { + this.capacityDouble = capacityDouble; + } + + public Measure getCapacityMeasure() { + return capacityMeasure; + } + + public double getCapacityDouble() { + return capacityDouble; + } +} diff --git a/core-java/src/test/java/com/baeldung/javax/measure/WaterTankTests.java b/core-java/src/test/java/com/baeldung/javax/measure/WaterTankTests.java new file mode 100644 index 0000000000..ef54035353 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javax/measure/WaterTankTests.java @@ -0,0 +1,68 @@ +package com.baeldung.javax.measure; + +import javax.measure.Measure; +import javax.measure.converter.UnitConverter; +import javax.measure.quantity.Duration; +import javax.measure.quantity.Length; +import javax.measure.quantity.Pressure; +import javax.measure.quantity.Volume; +import static javax.measure.unit.NonSI.HOUR; +import static javax.measure.unit.NonSI.LITRE; +import static javax.measure.unit.NonSI.MILE; +import static javax.measure.unit.NonSI.MINUTE; +import javax.measure.unit.SI; +import static javax.measure.unit.SI.KILO; +import static javax.measure.unit.SI.METER; +import static javax.measure.unit.SI.NEWTON; +import static javax.measure.unit.SI.SECOND; +import javax.measure.unit.Unit; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class WaterTankTests { + + @Test + public void givenMeasure_whenGetUnitAndConvertValue_thenSuccess() { + WaterTank waterTank = new WaterTank(); + waterTank.setCapacityMeasure(Measure.valueOf(9.2, LITRE)); + assertEquals(LITRE, waterTank.getCapacityMeasure().getUnit()); + + Measure waterCapacity = waterTank.getCapacityMeasure(); + double volumeInLitre = waterCapacity.getValue().doubleValue(); + assertEquals(9.2, volumeInLitre, 0.0f); + + double volumeInMilliLitre = waterCapacity.doubleValue(SI.MILLI(LITRE)); + assertEquals(9200.0, volumeInMilliLitre, 0.0f); + + Unit Kilometer = SI.KILO(METER); + Unit Centimeter = SI.CENTI(METER); + } + + @Test + public void givenMeasure_whenAlternateMeasure_ThenGetAlternateMeasure() { + Unit PASCAL = NEWTON.divide(METER.pow(2)).alternate("Pa"); + assertTrue(Unit.valueOf("Pa").equals(PASCAL)); + } + + @Test + public void givenMeasure_whenCompoundMeasure_ThenGetCompoundMeasure() { + Unit HOUR_MINUTE_SECOND = HOUR.compound(MINUTE).compound(SECOND); + Measure duration = Measure.valueOf(12345, SECOND); + assertEquals("3h25min45s", duration.to(HOUR_MINUTE_SECOND).toString()); + } + + @Test + public void givenMiles_whenConvertToKilometer_ThenConverted() { + double distanceInMiles = 50.0; + UnitConverter mileToKilometer = MILE.getConverterTo(KILO(METER)); + double distanceInKilometers = mileToKilometer.convert(distanceInMiles); + assertEquals(80.4672, distanceInKilometers, 0.00f); + } + + @Test + public void givenSymbol_WhenCompareToSystemUnit_ThenSuccess() { + assertTrue(Unit.valueOf("kW").equals(SI.KILO(SI.WATT))); + assertTrue(Unit.valueOf("ms").equals(SI.SECOND.divide(1000))); + } +} From e573e2c43b35809f5521fa47ce8d4c6dea760348 Mon Sep 17 00:00:00 2001 From: parthkaria Date: Tue, 29 Aug 2017 17:37:29 +0530 Subject: [PATCH 03/11] Unnecessary Committed --- .../CustomMultiResourcePartitioner.java | 77 -------- .../SpringbatchPartitionConfig.java | 169 ------------------ .../SpringbatchPartitionerApp.java | 28 --- 3 files changed, 274 deletions(-) delete mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java delete mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java delete mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java deleted file mode 100644 index 4cae69efbd..0000000000 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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 partition(int gridSize) { - Map map = new HashMap(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; - } - -} diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java deleted file mode 100644 index fe8339a8b4..0000000000 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java +++ /dev/null @@ -1,169 +0,0 @@ -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") - . 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 itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException { - FlatFileItemReader reader = new FlatFileItemReader(); - DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); - String[] tokens = { "username", "userid", "transactiondate", "amount" }; - tokenizer.setNames(tokens); - reader.setResource(new ClassPathResource("input/partitioner/" + filename)); - DefaultLineMapper lineMapper = new DefaultLineMapper(); - lineMapper.setLineTokenizer(tokenizer); - lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); - reader.setLinesToSkip(1); - reader.setLineMapper(lineMapper); - return reader; - } - - @Bean(destroyMethod = "") - @StepScope - public StaxEventItemWriter itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) throws MalformedURLException { - StaxEventItemWriter 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; - } -} diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java deleted file mode 100644 index 1d6d922969..0000000000 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java +++ /dev/null @@ -1,28 +0,0 @@ -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"); - } - } -} \ No newline at end of file From f6216f27549b70ea891582cab92311b554b0697d Mon Sep 17 00:00:00 2001 From: parthkaria Date: Thu, 31 Aug 2017 12:55:56 +0530 Subject: [PATCH 04/11] BAEL-1106 Move code to libraries from core-java --- core-java/pom.xml | 7 ------- libraries/pom.xml | 6 ++++++ .../main/java/com/baeldung/javax/measure/WaterTank.java | 0 .../java/com/baeldung/javax/measure/WaterTankTests.java | 0 4 files changed, 6 insertions(+), 7 deletions(-) rename {core-java => libraries}/src/main/java/com/baeldung/javax/measure/WaterTank.java (100%) rename {core-java => libraries}/src/test/java/com/baeldung/javax/measure/WaterTankTests.java (100%) diff --git a/core-java/pom.xml b/core-java/pom.xml index 5410ea54e2..c532d80bd6 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -213,12 +213,6 @@ ${streamex.version} - - javax.measure - jsr-275 - ${javax-measure.version} - - @@ -445,7 +439,6 @@ 1.5.1 1.13 0.6.5 - 0.9.1 1.3 diff --git a/libraries/pom.xml b/libraries/pom.xml index cf16f0fb79..9b8f3f0a77 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -498,6 +498,11 @@ gt-swing ${geotools.version} + + javax.measure + jsr-275 + ${javax-measure.version} + @@ -564,5 +569,6 @@ 0.6.5 0.9.0 15.2 + 0.9.1 diff --git a/core-java/src/main/java/com/baeldung/javax/measure/WaterTank.java b/libraries/src/main/java/com/baeldung/javax/measure/WaterTank.java similarity index 100% rename from core-java/src/main/java/com/baeldung/javax/measure/WaterTank.java rename to libraries/src/main/java/com/baeldung/javax/measure/WaterTank.java diff --git a/core-java/src/test/java/com/baeldung/javax/measure/WaterTankTests.java b/libraries/src/test/java/com/baeldung/javax/measure/WaterTankTests.java similarity index 100% rename from core-java/src/test/java/com/baeldung/javax/measure/WaterTankTests.java rename to libraries/src/test/java/com/baeldung/javax/measure/WaterTankTests.java From 99e9e2332b9d46627836b85a1ed484fec3a53120 Mon Sep 17 00:00:00 2001 From: parthkaria Date: Thu, 31 Aug 2017 12:57:54 +0530 Subject: [PATCH 05/11] BAEL-1106 Move code to libraries from core-java --- core-java/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java/pom.xml b/core-java/pom.xml index c532d80bd6..0f8a665fa1 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -212,7 +212,6 @@ streamex ${streamex.version} - From f52560cdbbd85206d975756526bedb9e59c76eb4 Mon Sep 17 00:00:00 2001 From: parthkaria Date: Wed, 27 Sep 2017 14:51:43 +0530 Subject: [PATCH 06/11] BAEL-815 Introduction to JGraphT --- libraries/pom.xml | 5 + .../com/baeldung/javax/measure/WaterTank.java | 26 ----- .../javax/measure/WaterTankTests.java | 68 ------------- .../baeldung/jgrapht/CompleteGraphTest.java | 38 ++++++++ .../baeldung/jgrapht/DirectedGraphTests.java | 95 +++++++++++++++++++ .../baeldung/jgrapht/EulerianCircuitTest.java | 42 ++++++++ 6 files changed, 180 insertions(+), 94 deletions(-) delete mode 100644 libraries/src/main/java/com/baeldung/javax/measure/WaterTank.java delete mode 100644 libraries/src/test/java/com/baeldung/javax/measure/WaterTankTests.java create mode 100644 libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java create mode 100644 libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java create mode 100644 libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index b0fdbea2f6..a15ffa6dfc 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -590,6 +590,11 @@ jsr-275 ${javax-measure.version} + + org.jgrapht + jgrapht-core + 1.0.1 + diff --git a/libraries/src/main/java/com/baeldung/javax/measure/WaterTank.java b/libraries/src/main/java/com/baeldung/javax/measure/WaterTank.java deleted file mode 100644 index 1ab9eee53f..0000000000 --- a/libraries/src/main/java/com/baeldung/javax/measure/WaterTank.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.javax.measure; - -import javax.measure.Measure; -import javax.measure.quantity.Volume; - -public class WaterTank { - - private Measure capacityMeasure; - private double capacityDouble; - - public void setCapacityMeasure(Measure capacityMeasure) { - this.capacityMeasure = capacityMeasure; - } - - public void setCapacityDouble(double capacityDouble) { - this.capacityDouble = capacityDouble; - } - - public Measure getCapacityMeasure() { - return capacityMeasure; - } - - public double getCapacityDouble() { - return capacityDouble; - } -} diff --git a/libraries/src/test/java/com/baeldung/javax/measure/WaterTankTests.java b/libraries/src/test/java/com/baeldung/javax/measure/WaterTankTests.java deleted file mode 100644 index ef54035353..0000000000 --- a/libraries/src/test/java/com/baeldung/javax/measure/WaterTankTests.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.javax.measure; - -import javax.measure.Measure; -import javax.measure.converter.UnitConverter; -import javax.measure.quantity.Duration; -import javax.measure.quantity.Length; -import javax.measure.quantity.Pressure; -import javax.measure.quantity.Volume; -import static javax.measure.unit.NonSI.HOUR; -import static javax.measure.unit.NonSI.LITRE; -import static javax.measure.unit.NonSI.MILE; -import static javax.measure.unit.NonSI.MINUTE; -import javax.measure.unit.SI; -import static javax.measure.unit.SI.KILO; -import static javax.measure.unit.SI.METER; -import static javax.measure.unit.SI.NEWTON; -import static javax.measure.unit.SI.SECOND; -import javax.measure.unit.Unit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import org.junit.Test; - -public class WaterTankTests { - - @Test - public void givenMeasure_whenGetUnitAndConvertValue_thenSuccess() { - WaterTank waterTank = new WaterTank(); - waterTank.setCapacityMeasure(Measure.valueOf(9.2, LITRE)); - assertEquals(LITRE, waterTank.getCapacityMeasure().getUnit()); - - Measure waterCapacity = waterTank.getCapacityMeasure(); - double volumeInLitre = waterCapacity.getValue().doubleValue(); - assertEquals(9.2, volumeInLitre, 0.0f); - - double volumeInMilliLitre = waterCapacity.doubleValue(SI.MILLI(LITRE)); - assertEquals(9200.0, volumeInMilliLitre, 0.0f); - - Unit Kilometer = SI.KILO(METER); - Unit Centimeter = SI.CENTI(METER); - } - - @Test - public void givenMeasure_whenAlternateMeasure_ThenGetAlternateMeasure() { - Unit PASCAL = NEWTON.divide(METER.pow(2)).alternate("Pa"); - assertTrue(Unit.valueOf("Pa").equals(PASCAL)); - } - - @Test - public void givenMeasure_whenCompoundMeasure_ThenGetCompoundMeasure() { - Unit HOUR_MINUTE_SECOND = HOUR.compound(MINUTE).compound(SECOND); - Measure duration = Measure.valueOf(12345, SECOND); - assertEquals("3h25min45s", duration.to(HOUR_MINUTE_SECOND).toString()); - } - - @Test - public void givenMiles_whenConvertToKilometer_ThenConverted() { - double distanceInMiles = 50.0; - UnitConverter mileToKilometer = MILE.getConverterTo(KILO(METER)); - double distanceInKilometers = mileToKilometer.convert(distanceInMiles); - assertEquals(80.4672, distanceInKilometers, 0.00f); - } - - @Test - public void givenSymbol_WhenCompareToSystemUnit_ThenSuccess() { - assertTrue(Unit.valueOf("kW").equals(SI.KILO(SI.WATT))); - assertTrue(Unit.valueOf("ms").equals(SI.SECOND.divide(1000))); - } -} diff --git a/libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java b/libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java new file mode 100644 index 0000000000..c085d54689 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java @@ -0,0 +1,38 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.jgrapht.VertexFactory; +import org.jgrapht.alg.HamiltonianCycle; +import org.jgrapht.generate.CompleteGraphGenerator; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.SimpleWeightedGraph; +import org.junit.Before; +import org.junit.Test; + +public class CompleteGraphTest { + + static SimpleWeightedGraph completeGraph; + static int size = 10; + + @Before + public void createCompleteGraph() { + completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class); + CompleteGraphGenerator completeGenerator = new CompleteGraphGenerator(size); + VertexFactory vFactory = new VertexFactory() { + private int id = 0; + public String createVertex() { + return "v" + id++; + } + }; + completeGenerator.generateGraph(completeGraph, vFactory, null); + } + + @Test + public void givenCompleteGraph_whenGetHamiltonianCyclePath_thenGetVerticeListInSequence() { + List verticeList = HamiltonianCycle.getApproximateOptimalForCompleteGraph(completeGraph); + assertEquals(verticeList.size(), completeGraph.vertexSet().size()); + } +} diff --git a/libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java b/libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java new file mode 100644 index 0000000000..7f4cc99715 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java @@ -0,0 +1,95 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.IntStream; + +import org.jgrapht.DirectedGraph; +import org.jgrapht.GraphPath; +import org.jgrapht.alg.CycleDetector; +import org.jgrapht.alg.KosarajuStrongConnectivityInspector; +import org.jgrapht.alg.interfaces.StrongConnectivityAlgorithm; +import org.jgrapht.alg.shortestpath.AllDirectedPaths; +import org.jgrapht.alg.shortestpath.BellmanFordShortestPath; +import org.jgrapht.alg.shortestpath.DijkstraShortestPath; +import org.jgrapht.graph.DefaultDirectedGraph; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.DirectedSubgraph; +import org.jgrapht.traverse.BreadthFirstIterator; +import org.jgrapht.traverse.DepthFirstIterator; +import org.junit.Before; +import org.junit.Test; + +public class DirectedGraphTests { + DirectedGraph directedGraph; + + @Before + public void createDirectedGraph() { + directedGraph = new DefaultDirectedGraph(DefaultEdge.class); + IntStream.range(1, 10).forEach(i -> { + directedGraph.addVertex("v" + i); + }); + directedGraph.addEdge("v1", "v2"); + directedGraph.addEdge("v2", "v4"); + directedGraph.addEdge("v4", "v3"); + directedGraph.addEdge("v3", "v1"); + directedGraph.addEdge("v5", "v4"); + directedGraph.addEdge("v5", "v6"); + directedGraph.addEdge("v6", "v7"); + directedGraph.addEdge("v7", "v5"); + directedGraph.addEdge("v8", "v5"); + directedGraph.addEdge("v9", "v8"); + } + + @Test + public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() { + StrongConnectivityAlgorithm scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph); + List> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs(); + List stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet()); + + String randomVertex1 = stronglyConnectedVertices.get(0); + String randomVertex2 = stronglyConnectedVertices.get(3); + AllDirectedPaths allDirectedPaths = new AllDirectedPaths<>(directedGraph); + + List> possiblePathList = allDirectedPaths.getAllPaths(randomVertex1, randomVertex2, false, stronglyConnectedVertices.size()); + assertTrue(possiblePathList.size() > 0); + } + + @Test + public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() { + CycleDetector cycleDetector = new CycleDetector(directedGraph); + assertTrue(cycleDetector.detectCycles()); + Set cycleVertices = cycleDetector.findCycles(); + assertTrue(cycleVertices.size() > 0); + } + + @Test + public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() { + DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph); + assertNotNull(depthFirstIterator); + } + + @Test + public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() { + BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph); + assertNotNull(breadthFirstIterator); + } + + @Test + public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() { + DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph); + List shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList(); + assertNotNull(shortestPath); + } + + @Test + public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() { + BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph); + List shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList(); + assertNotNull(shortestPath); + } +} diff --git a/libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java b/libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java new file mode 100644 index 0000000000..6f0fb92ab7 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.stream.IntStream; + +import org.jgrapht.GraphPath; +import org.jgrapht.alg.cycle.HierholzerEulerianCycle; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.SimpleWeightedGraph; +import org.junit.Before; +import org.junit.Test; + +public class EulerianCircuitTest { + SimpleWeightedGraph simpleGraph; + + @Before + public void createGraphWithEulerianCircuit() { + simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class); + IntStream.range(1, 6).forEach(i -> { + simpleGraph.addVertex("v" + i); + }); + IntStream.range(1, 6).forEach(i -> { + int endVertexNo = (i + 1) > 5 ? 1 : i + 1; + simpleGraph.addEdge("v" + i, "v" + endVertexNo); + }); + } + + @Test + public void givenGraph_whenCheckEluerianCycle_thenGetResult() { + HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); + assertTrue(eulerianCycle.isEulerian(simpleGraph)); + } + + @Test + public void givenGraphWithEulerianCircuit_whenGetEulerianCycle_thenGetGraphPath() { + HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); + GraphPath path = eulerianCycle.getEulerianCycle(simpleGraph); + assertTrue(path.getEdgeList().containsAll(simpleGraph.edgeSet())); + } +} From 38b2dc00284a18eda549c50daa47f85bfa128183 Mon Sep 17 00:00:00 2001 From: parthkaria Date: Wed, 27 Sep 2017 14:52:54 +0530 Subject: [PATCH 07/11] BAEL-815 Introduction to JGraphT --- libraries/pom.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/libraries/pom.xml b/libraries/pom.xml index a15ffa6dfc..03919b9cec 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -585,11 +585,6 @@ fugue 3.0.0-m007 - - javax.measure - jsr-275 - ${javax-measure.version} - org.jgrapht jgrapht-core @@ -660,7 +655,6 @@ 0.6.5 0.9.0 15.2 - 0.9.1 2.9.9 1.5.1 2.3.0 From 043ea5e574ab5deee7c0935f92121dc6630fb7a2 Mon Sep 17 00:00:00 2001 From: "parth.karia" Date: Mon, 27 Nov 2017 12:03:43 +0530 Subject: [PATCH 08/11] Removes jgrapht from libraries --- libraries/pom.xml | 11 +-- .../baeldung/jgrapht/CompleteGraphTest.java | 38 -------- .../baeldung/jgrapht/DirectedGraphTests.java | 95 ------------------- .../baeldung/jgrapht/EulerianCircuitTest.java | 42 -------- 4 files changed, 1 insertion(+), 185 deletions(-) delete mode 100644 libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java delete mode 100644 libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java delete mode 100644 libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index bf90e4ccd9..0b707b914e 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -587,21 +587,12 @@ hazelcast ${hazelcast.version} - - org.jgrapht - jgrapht-core - 1.0.1 - com.netopyr.wurmloch wurmloch-crdt ${crdt.version} - org.jgrapht - jgrapht-core - 1.0.1 - org.docx4j docx4j 3.3.5 @@ -715,4 +706,4 @@ 3.8.4 2.5.5 - + \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java b/libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java deleted file mode 100644 index c085d54689..0000000000 --- a/libraries/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.jgrapht; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.jgrapht.VertexFactory; -import org.jgrapht.alg.HamiltonianCycle; -import org.jgrapht.generate.CompleteGraphGenerator; -import org.jgrapht.graph.DefaultEdge; -import org.jgrapht.graph.SimpleWeightedGraph; -import org.junit.Before; -import org.junit.Test; - -public class CompleteGraphTest { - - static SimpleWeightedGraph completeGraph; - static int size = 10; - - @Before - public void createCompleteGraph() { - completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class); - CompleteGraphGenerator completeGenerator = new CompleteGraphGenerator(size); - VertexFactory vFactory = new VertexFactory() { - private int id = 0; - public String createVertex() { - return "v" + id++; - } - }; - completeGenerator.generateGraph(completeGraph, vFactory, null); - } - - @Test - public void givenCompleteGraph_whenGetHamiltonianCyclePath_thenGetVerticeListInSequence() { - List verticeList = HamiltonianCycle.getApproximateOptimalForCompleteGraph(completeGraph); - assertEquals(verticeList.size(), completeGraph.vertexSet().size()); - } -} diff --git a/libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java b/libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java deleted file mode 100644 index 7f4cc99715..0000000000 --- a/libraries/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.jgrapht; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.stream.IntStream; - -import org.jgrapht.DirectedGraph; -import org.jgrapht.GraphPath; -import org.jgrapht.alg.CycleDetector; -import org.jgrapht.alg.KosarajuStrongConnectivityInspector; -import org.jgrapht.alg.interfaces.StrongConnectivityAlgorithm; -import org.jgrapht.alg.shortestpath.AllDirectedPaths; -import org.jgrapht.alg.shortestpath.BellmanFordShortestPath; -import org.jgrapht.alg.shortestpath.DijkstraShortestPath; -import org.jgrapht.graph.DefaultDirectedGraph; -import org.jgrapht.graph.DefaultEdge; -import org.jgrapht.graph.DirectedSubgraph; -import org.jgrapht.traverse.BreadthFirstIterator; -import org.jgrapht.traverse.DepthFirstIterator; -import org.junit.Before; -import org.junit.Test; - -public class DirectedGraphTests { - DirectedGraph directedGraph; - - @Before - public void createDirectedGraph() { - directedGraph = new DefaultDirectedGraph(DefaultEdge.class); - IntStream.range(1, 10).forEach(i -> { - directedGraph.addVertex("v" + i); - }); - directedGraph.addEdge("v1", "v2"); - directedGraph.addEdge("v2", "v4"); - directedGraph.addEdge("v4", "v3"); - directedGraph.addEdge("v3", "v1"); - directedGraph.addEdge("v5", "v4"); - directedGraph.addEdge("v5", "v6"); - directedGraph.addEdge("v6", "v7"); - directedGraph.addEdge("v7", "v5"); - directedGraph.addEdge("v8", "v5"); - directedGraph.addEdge("v9", "v8"); - } - - @Test - public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() { - StrongConnectivityAlgorithm scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph); - List> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs(); - List stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet()); - - String randomVertex1 = stronglyConnectedVertices.get(0); - String randomVertex2 = stronglyConnectedVertices.get(3); - AllDirectedPaths allDirectedPaths = new AllDirectedPaths<>(directedGraph); - - List> possiblePathList = allDirectedPaths.getAllPaths(randomVertex1, randomVertex2, false, stronglyConnectedVertices.size()); - assertTrue(possiblePathList.size() > 0); - } - - @Test - public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() { - CycleDetector cycleDetector = new CycleDetector(directedGraph); - assertTrue(cycleDetector.detectCycles()); - Set cycleVertices = cycleDetector.findCycles(); - assertTrue(cycleVertices.size() > 0); - } - - @Test - public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() { - DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph); - assertNotNull(depthFirstIterator); - } - - @Test - public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() { - BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph); - assertNotNull(breadthFirstIterator); - } - - @Test - public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() { - DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph); - List shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList(); - assertNotNull(shortestPath); - } - - @Test - public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() { - BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph); - List shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList(); - assertNotNull(shortestPath); - } -} diff --git a/libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java b/libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java deleted file mode 100644 index 6f0fb92ab7..0000000000 --- a/libraries/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.jgrapht; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.stream.IntStream; - -import org.jgrapht.GraphPath; -import org.jgrapht.alg.cycle.HierholzerEulerianCycle; -import org.jgrapht.graph.DefaultEdge; -import org.jgrapht.graph.SimpleWeightedGraph; -import org.junit.Before; -import org.junit.Test; - -public class EulerianCircuitTest { - SimpleWeightedGraph simpleGraph; - - @Before - public void createGraphWithEulerianCircuit() { - simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class); - IntStream.range(1, 6).forEach(i -> { - simpleGraph.addVertex("v" + i); - }); - IntStream.range(1, 6).forEach(i -> { - int endVertexNo = (i + 1) > 5 ? 1 : i + 1; - simpleGraph.addEdge("v" + i, "v" + endVertexNo); - }); - } - - @Test - public void givenGraph_whenCheckEluerianCycle_thenGetResult() { - HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); - assertTrue(eulerianCycle.isEulerian(simpleGraph)); - } - - @Test - public void givenGraphWithEulerianCircuit_whenGetEulerianCycle_thenGetGraphPath() { - HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>(); - GraphPath path = eulerianCycle.getEulerianCycle(simpleGraph); - assertTrue(path.getEdgeList().containsAll(simpleGraph.edgeSet())); - } -} From b1782b3c19c3f4e3eef2a976efa23ad066d28e00 Mon Sep 17 00:00:00 2001 From: "parth.karia" Date: Mon, 27 Nov 2017 12:05:18 +0530 Subject: [PATCH 09/11] Resolve conflicts manually --- libraries/pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/libraries/pom.xml b/libraries/pom.xml index 0b707b914e..27d867b68b 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -587,6 +587,11 @@ hazelcast ${hazelcast.version} + + org.jgrapht + jgrapht-core + 1.0.1 + com.netopyr.wurmloch wurmloch-crdt From 3daa1b01ce4794f2df03ad0bf44c87b5378f9438 Mon Sep 17 00:00:00 2001 From: "parth.karia" Date: Mon, 27 Nov 2017 12:10:19 +0530 Subject: [PATCH 10/11] BAEL-21 Exploring the new HTTP Client in Java 9 --- .../java9/httpclient/HttpClientExample.java | 76 +++++++++++++++++++ core-java-9/src/main/java/module-info.java | 3 + 2 files changed, 79 insertions(+) create mode 100644 core-java-9/src/main/java/com/baeldung/java9/httpclient/HttpClientExample.java create mode 100644 core-java-9/src/main/java/module-info.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/httpclient/HttpClientExample.java b/core-java-9/src/main/java/com/baeldung/java9/httpclient/HttpClientExample.java new file mode 100644 index 0000000000..6ccfd030a5 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/httpclient/HttpClientExample.java @@ -0,0 +1,76 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.baeldung.java9.httpclient; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; +import jdk.incubator.http.HttpClient; +import jdk.incubator.http.HttpRequest; +import jdk.incubator.http.HttpRequest.BodyProcessor; +import jdk.incubator.http.HttpResponse; +import jdk.incubator.http.HttpResponse.BodyHandler; + +/** + * + * @author pkaria + */ +public class HttpClientExample { + + public void httpGetRequest() throws URISyntaxException, IOException, InterruptedException { + HttpClient client = HttpClient.newHttpClient(); + URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1"); + HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandler.asString()); + String responseBody = response.body(); + int responseStatusCode = response.statusCode(); + System.out.println(responseBody); + } + + public void httpPosttRequest() throws URISyntaxException, IOException, InterruptedException { + HttpClient client = HttpClient + .newBuilder() + .build(); + HttpRequest request = HttpRequest + .newBuilder(new URI("http://jsonplaceholder.typicode.com/posts")) + .POST(BodyProcessor.fromString("Sample Post Request")) + .build(); + HttpResponse response + = client.send(request, HttpResponse.BodyHandler.asString()); + String responseBody = response.body(); + System.out.println(responseBody); + } + + public void asynchronousRequest() throws URISyntaxException { + HttpClient client = HttpClient.newHttpClient(); + URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1"); + HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build(); + CompletableFuture> futureResponse = client.sendAsync(request, + HttpResponse.BodyHandler.asString()); + } + + public void asynchronousMultipleRequests() throws URISyntaxException { + List targets = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2")); + HttpClient client = HttpClient.newHttpClient(); + List> futures = targets + .stream() + .map(target -> client + .sendAsync( + HttpRequest.newBuilder(target) + .GET() + .build(), + BodyHandler.asFile(Paths.get("base", target.getPath()))) + .thenApply(response -> response.body()) + .thenApply(path -> path.toFile())) + .collect(Collectors.toList()); + } +} diff --git a/core-java-9/src/main/java/module-info.java b/core-java-9/src/main/java/module-info.java new file mode 100644 index 0000000000..163dd4f5be --- /dev/null +++ b/core-java-9/src/main/java/module-info.java @@ -0,0 +1,3 @@ +module com.baeldung.java9.httpclient { + requires jdk.incubator.httpclient; +} \ No newline at end of file From d51b1b4f20b98fbc30a42477103ab8b477872faa Mon Sep 17 00:00:00 2001 From: parthkaria Date: Fri, 1 Dec 2017 10:51:33 +0530 Subject: [PATCH 11/11] BAEL-21 Java 9 HttpClient code refactoring --- core-java-9/compile-httpclient.bat | 3 +++ core-java-9/src/main/java/module-info.java | 3 --- .../baeldung}/httpclient/HttpClientExample.java | 17 ++++++++++++----- .../com.baeldung.httpclient/module-info.java | 3 +++ 4 files changed, 18 insertions(+), 8 deletions(-) create mode 100644 core-java-9/compile-httpclient.bat delete mode 100644 core-java-9/src/main/java/module-info.java rename core-java-9/src/{main/java/com/baeldung/java9 => modules/com.baeldung.httpclient/com/baeldung}/httpclient/HttpClientExample.java (82%) create mode 100644 core-java-9/src/modules/com.baeldung.httpclient/module-info.java diff --git a/core-java-9/compile-httpclient.bat b/core-java-9/compile-httpclient.bat new file mode 100644 index 0000000000..9d845784cf --- /dev/null +++ b/core-java-9/compile-httpclient.bat @@ -0,0 +1,3 @@ +javac --module-path mods -d mods/com.baeldung.httpclient^ + src/modules/com.baeldung.httpclient/module-info.java^ + src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java \ No newline at end of file diff --git a/core-java-9/src/main/java/module-info.java b/core-java-9/src/main/java/module-info.java deleted file mode 100644 index 163dd4f5be..0000000000 --- a/core-java-9/src/main/java/module-info.java +++ /dev/null @@ -1,3 +0,0 @@ -module com.baeldung.java9.httpclient { - requires jdk.incubator.httpclient; -} \ No newline at end of file diff --git a/core-java-9/src/main/java/com/baeldung/java9/httpclient/HttpClientExample.java b/core-java-9/src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java similarity index 82% rename from core-java-9/src/main/java/com/baeldung/java9/httpclient/HttpClientExample.java rename to core-java-9/src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java index 6ccfd030a5..44c55715c7 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/httpclient/HttpClientExample.java +++ b/core-java-9/src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java @@ -3,7 +3,7 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package com.baeldung.java9.httpclient; +package com.baeldung.httpclient; import java.io.File; import java.io.IOException; @@ -25,8 +25,15 @@ import jdk.incubator.http.HttpResponse.BodyHandler; * @author pkaria */ public class HttpClientExample { + + public static void main(String[] args) throws Exception { + httpGetRequest(); + httpPosttRequest(); + asynchronousRequest(); + asynchronousMultipleRequests(); + } - public void httpGetRequest() throws URISyntaxException, IOException, InterruptedException { + public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1"); HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build(); @@ -36,7 +43,7 @@ public class HttpClientExample { System.out.println(responseBody); } - public void httpPosttRequest() throws URISyntaxException, IOException, InterruptedException { + public static void httpPosttRequest() throws URISyntaxException, IOException, InterruptedException { HttpClient client = HttpClient .newBuilder() .build(); @@ -50,7 +57,7 @@ public class HttpClientExample { System.out.println(responseBody); } - public void asynchronousRequest() throws URISyntaxException { + public static void asynchronousRequest() throws URISyntaxException { HttpClient client = HttpClient.newHttpClient(); URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1"); HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build(); @@ -58,7 +65,7 @@ public class HttpClientExample { HttpResponse.BodyHandler.asString()); } - public void asynchronousMultipleRequests() throws URISyntaxException { + public static void asynchronousMultipleRequests() throws URISyntaxException { List targets = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2")); HttpClient client = HttpClient.newHttpClient(); List> futures = targets diff --git a/core-java-9/src/modules/com.baeldung.httpclient/module-info.java b/core-java-9/src/modules/com.baeldung.httpclient/module-info.java new file mode 100644 index 0000000000..205c9ea725 --- /dev/null +++ b/core-java-9/src/modules/com.baeldung.httpclient/module-info.java @@ -0,0 +1,3 @@ +module com.baeldung.httpclient { + requires jdk.incubator.httpclient; +}