Merge remote-tracking branch 'eugenp/master'
This commit is contained in:
commit
58b0b93d22
|
@ -1,4 +1,6 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
|
||||
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
|
||||
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
|
||||
- [Design a Genetic Algorithm in Java](https://www.baeldung.com/java-genetic-algorithm)
|
||||
- [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
/bin/
|
|
@ -1,20 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class RoundUpToHundred {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
double input = scanner.nextDouble();
|
||||
scanner.close();
|
||||
|
||||
RoundUpToHundred.round(input);
|
||||
}
|
||||
|
||||
static long round(double input) {
|
||||
long i = (long) Math.ceil(input);
|
||||
return ((i + 99) / 100) * 100;
|
||||
};
|
||||
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RoundUpToHundredTest {
|
||||
@Test
|
||||
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
|
||||
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
|
||||
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
|
||||
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
|
||||
}
|
||||
}
|
|
@ -5,7 +5,6 @@ import java.util.Scanner;
|
|||
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
|
||||
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
|
||||
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
|
||||
import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||
|
||||
public class RunAlgorithm {
|
||||
|
||||
|
@ -13,11 +12,8 @@ public class RunAlgorithm {
|
|||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Run algorithm:");
|
||||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Slope One");
|
||||
System.out.println("3 - Simple Genetic Algorithm");
|
||||
System.out.println("4 - Ant Colony");
|
||||
System.out.println("5 - Dijkstra");
|
||||
System.out.println("6 - All pairs in an array that add up to a given sum");
|
||||
System.out.println("2 - Simple Genetic Algorithm");
|
||||
System.out.println("3 - Ant Colony");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
|
@ -25,19 +21,13 @@ public class RunAlgorithm {
|
|||
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||
break;
|
||||
case 2:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
case 3:
|
||||
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
|
||||
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
|
||||
break;
|
||||
case 4:
|
||||
case 3:
|
||||
AntColonyOptimization antColony = new AntColonyOptimization(21);
|
||||
antColony.startAntOptimization();
|
||||
break;
|
||||
case 5:
|
||||
System.out.println("Please run the DijkstraAlgorithmTest.");
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
|
|
|
@ -9,4 +9,5 @@
|
|||
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
|
||||
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
|
|
@ -1 +0,0 @@
|
|||
/bin/
|
|
@ -1,14 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RoundUpToHundredTest {
|
||||
@Test
|
||||
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
|
||||
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
|
||||
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
|
||||
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
|
||||
}
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
S ########
|
||||
# #
|
||||
# ### ## #
|
||||
# # # #
|
||||
# # # # #
|
||||
# ## #####
|
||||
# # #
|
||||
# # # # #
|
||||
##### ####
|
||||
# # E
|
||||
# # # #
|
||||
##########
|
|
@ -1,22 +0,0 @@
|
|||
S ##########################
|
||||
# # # #
|
||||
# # #### ############### #
|
||||
# # # # # #
|
||||
# # #### # # ###############
|
||||
# # # # # # #
|
||||
# # # #### ### ########### #
|
||||
# # # # # #
|
||||
# ################## #
|
||||
######### # # # # #
|
||||
# # #### # ####### # #
|
||||
# # ### ### # # # # #
|
||||
# # ## # ##### # #
|
||||
##### ####### # # # # #
|
||||
# # ## ## #### # #
|
||||
# ##### ####### # #
|
||||
# # ############
|
||||
####### ######### # #
|
||||
# # ######## #
|
||||
# ####### ###### ## # E
|
||||
# # # ## #
|
||||
############################
|
|
@ -10,7 +10,6 @@
|
|||
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
|
||||
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
|
||||
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
/bin/
|
|
@ -1,20 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class RoundUpToHundred {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
double input = scanner.nextDouble();
|
||||
scanner.close();
|
||||
|
||||
RoundUpToHundred.round(input);
|
||||
}
|
||||
|
||||
static long round(double input) {
|
||||
long i = (long) Math.ceil(input);
|
||||
return ((i + 99) / 100) * 100;
|
||||
};
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.algorithms;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||
|
||||
public class RunAlgorithm {
|
||||
|
||||
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("1 - Slope One");
|
||||
System.out.println("2 - Dijkstra");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
case 2:
|
||||
System.out.println("Please run the DijkstraAlgorithmLongRunningUnitTest.");
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.algorithms.mercator;
|
||||
|
||||
class EllipticalMercator extends Mercator {
|
||||
|
||||
@Override
|
||||
double yAxisProjection(double input) {
|
||||
|
||||
input = Math.min(Math.max(input, -89.5), 89.5);
|
||||
double earthDimensionalRateNormalized = 1.0 - Math.pow(RADIUS_MINOR / RADIUS_MAJOR, 2);
|
||||
|
||||
double inputOnEarthProj = Math.sqrt(earthDimensionalRateNormalized) * Math.sin( Math.toRadians(input));
|
||||
|
||||
inputOnEarthProj = Math.pow(((1.0 - inputOnEarthProj)/(1.0+inputOnEarthProj)), 0.5 * Math.sqrt(earthDimensionalRateNormalized));
|
||||
double inputOnEarthProjNormalized = Math.tan(0.5 * ((Math.PI*0.5) - Math.toRadians(input)))/inputOnEarthProj;
|
||||
return (-1) * RADIUS_MAJOR * Math.log(inputOnEarthProjNormalized);
|
||||
}
|
||||
|
||||
@Override
|
||||
double xAxisProjection(double input) {
|
||||
return RADIUS_MAJOR * Math.toRadians(input);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.algorithms.mercator;
|
||||
|
||||
abstract class Mercator {
|
||||
final static double RADIUS_MAJOR = 6378137.0;
|
||||
final static double RADIUS_MINOR = 6356752.3142;
|
||||
|
||||
abstract double yAxisProjection(double input);
|
||||
|
||||
abstract double xAxisProjection(double input);
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.algorithms.mercator;
|
||||
|
||||
public class SphericalMercator extends Mercator {
|
||||
|
||||
@Override
|
||||
double xAxisProjection(double input) {
|
||||
return Math.toRadians(input) * RADIUS_MAJOR;
|
||||
}
|
||||
|
||||
@Override
|
||||
double yAxisProjection(double input) {
|
||||
return Math.log(Math.tan(Math.PI / 4 + Math.toRadians(input) / 2)) * RADIUS_MAJOR;
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.java.src;
|
||||
package com.baeldung.algorithms.roundedup;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.algorithms.mercator;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
|
||||
public class EllipticalMercatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void giventThatTheInputIs22_whenXAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
|
||||
Mercator mercator = new EllipticalMercator();
|
||||
double result = mercator.xAxisProjection(22);
|
||||
Assert.assertEquals(result, 2449028.7974520186, 0.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giventThatTheInputIs44_whenYAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
|
||||
Mercator mercator = new EllipticalMercator();
|
||||
double result = mercator.yAxisProjection(44);
|
||||
Assert.assertEquals(result, 5435749.887511954, 0.0);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.algorithms.mercator;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SphericalMercatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void giventThatTheInputIs22_whenXAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
|
||||
Mercator mercator = new SphericalMercator();
|
||||
double result = mercator.xAxisProjection(22);
|
||||
Assert.assertEquals(result, 2449028.7974520186, 0.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giventThatTheInputIs44_whenYAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
|
||||
Mercator mercator = new SphericalMercator();
|
||||
double result = mercator.yAxisProjection(44);
|
||||
Assert.assertEquals(result, 5465442.183322753, 0.0);
|
||||
}
|
||||
}
|
|
@ -1,10 +1,10 @@
|
|||
package com.java.src;
|
||||
package com.baeldung.algorithms.roundedup;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RoundUpToHundredTest {
|
||||
public class RoundUpToHundredUnitTest {
|
||||
@Test
|
||||
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
|
||||
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
|
|
@ -1 +0,0 @@
|
|||
/bin/
|
|
@ -1,20 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class RoundUpToHundred {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
double input = scanner.nextDouble();
|
||||
scanner.close();
|
||||
|
||||
RoundUpToHundred.round(input);
|
||||
}
|
||||
|
||||
static long round(double input) {
|
||||
long i = (long) Math.ceil(input);
|
||||
return ((i + 99) / 100) * 100;
|
||||
};
|
||||
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RoundUpToHundredTest {
|
||||
@Test
|
||||
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
|
||||
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
|
||||
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
|
||||
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
|
||||
}
|
||||
}
|
|
@ -1,38 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>flyway-cdi</artifactId>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>cdi-portable-extension</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0.SP1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
<version>5.1.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-jdbc</artifactId>
|
||||
<version>8.5.33</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>1.3.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -1,74 +0,0 @@
|
|||
package com.baeldung.cdi.extension;
|
||||
|
||||
import org.apache.tomcat.jdbc.pool.DataSource;
|
||||
import org.flywaydb.core.Flyway;
|
||||
|
||||
import javax.annotation.sql.DataSourceDefinition;
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import javax.enterprise.event.Observes;
|
||||
import javax.enterprise.inject.Any;
|
||||
import javax.enterprise.inject.Default;
|
||||
import javax.enterprise.inject.literal.InjectLiteral;
|
||||
import javax.enterprise.inject.spi.*;
|
||||
import javax.enterprise.util.AnnotationLiteral;
|
||||
|
||||
|
||||
/**
|
||||
* Flyway is now under CDI container like:
|
||||
*
|
||||
* @ApplicationScoped
|
||||
* @FlywayType public class Flyway{
|
||||
* @Inject setDataSource(DataSource dataSource){
|
||||
* //...
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
|
||||
public class FlywayExtension implements Extension {
|
||||
|
||||
DataSourceDefinition dataSourceDefinition = null;
|
||||
|
||||
public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) {
|
||||
bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName());
|
||||
}
|
||||
|
||||
public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType<?> patEvent) {
|
||||
AnnotatedType at = patEvent.getAnnotatedType();
|
||||
dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class);
|
||||
}
|
||||
|
||||
public void processAnnotatedType(@Observes ProcessAnnotatedType<Flyway> patEvent) {
|
||||
patEvent.configureAnnotatedType()
|
||||
//Add Scope
|
||||
.add(ApplicationScoped.Literal.INSTANCE)
|
||||
//Add Qualifier
|
||||
.add(new AnnotationLiteral<FlywayType>() {
|
||||
})
|
||||
//Decorate setDataSource(DataSource dataSource){} with @Inject
|
||||
.filterMethods(annotatedMethod -> {
|
||||
return annotatedMethod.getParameters().size() == 1 &&
|
||||
annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class);
|
||||
})
|
||||
.findFirst().get().add(InjectLiteral.INSTANCE);
|
||||
}
|
||||
|
||||
void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) {
|
||||
abdEvent.addBean()
|
||||
.types(javax.sql.DataSource.class, DataSource.class)
|
||||
.qualifiers(new AnnotationLiteral<Default>() {}, new AnnotationLiteral<Any>() {})
|
||||
.scope(ApplicationScoped.class)
|
||||
.name(DataSource.class.getName())
|
||||
.beanClass(DataSource.class)
|
||||
.createWith(creationalContext -> {
|
||||
DataSource instance = new DataSource();
|
||||
instance.setUrl(dataSourceDefinition.url());
|
||||
instance.setDriverClassName(dataSourceDefinition.className());
|
||||
return instance;
|
||||
});
|
||||
}
|
||||
|
||||
void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) {
|
||||
Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral<FlywayType>() {}).get();
|
||||
flyway.migrate();
|
||||
}
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
package com.baeldung.cdi.extension;
|
||||
|
||||
import javax.inject.Qualifier;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.*;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({FIELD, METHOD, PARAMETER, TYPE})
|
||||
@Qualifier
|
||||
public @interface FlywayType {
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
<beans version="2.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||
bean-discovery-mode="annotated">
|
||||
</beans>
|
|
@ -1,2 +0,0 @@
|
|||
com.baeldung.cdi.extension.FlywayExtension
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>main-app</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>cdi-portable-extension</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0.SP1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jboss.weld.se</groupId>
|
||||
<artifactId>weld-se-core</artifactId>
|
||||
<version>3.0.5.Final</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>flyway-cdi</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.197</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>1.3.2</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -1,16 +0,0 @@
|
|||
package com.baeldung.cdi.extension;
|
||||
|
||||
import javax.annotation.sql.DataSourceDefinition;
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import javax.enterprise.inject.se.SeContainer;
|
||||
import javax.enterprise.inject.se.SeContainerInitializer;
|
||||
|
||||
@ApplicationScoped
|
||||
@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb")
|
||||
public class MainApp {
|
||||
public static void main(String[] args) {
|
||||
SeContainerInitializer initializer = SeContainerInitializer.newInstance();
|
||||
try (SeContainer container = initializer.initialize()) {
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
<beans version="2.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||
bean-discovery-mode="annotated">
|
||||
</beans>
|
|
@ -1,4 +0,0 @@
|
|||
create table PERSON (
|
||||
ID int not null,
|
||||
NAME varchar(100) not null
|
||||
);
|
|
@ -1,3 +0,0 @@
|
|||
insert into PERSON (ID, NAME) values (1, 'Axel');
|
||||
insert into PERSON (ID, NAME) values (2, 'Mr. Foo');
|
||||
insert into PERSON (ID, NAME) values (3, 'Ms. Bar');
|
|
@ -1,30 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>cdi-portable-extension</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<modules>
|
||||
<module>main-app</module>
|
||||
<module>flyway-cdi</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0.SP1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class AddCommand implements Command {
|
||||
|
||||
private int a;
|
||||
private int b;
|
||||
|
||||
public AddCommand(int a, int b) {
|
||||
this.a = a;
|
||||
this.b = b;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer execute() {
|
||||
return a + b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class AddRule implements Rule {
|
||||
|
||||
private int result;
|
||||
|
||||
@Override
|
||||
public boolean evaluate(Expression expression) {
|
||||
boolean evalResult = false;
|
||||
if (expression.getOperator() == Operator.ADD) {
|
||||
this.result = expression.getX() + expression.getY();
|
||||
evalResult = true;
|
||||
}
|
||||
return evalResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result getResult() {
|
||||
return new Result(result);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Addition implements Operation {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Calculator {
|
||||
|
||||
public int calculate(int a, int b, String operator) {
|
||||
int result = Integer.MIN_VALUE;
|
||||
|
||||
if ("add".equals(operator)) {
|
||||
result = a + b;
|
||||
} else if ("multiply".equals(operator)) {
|
||||
result = a * b;
|
||||
} else if ("divide".equals(operator)) {
|
||||
result = a / b;
|
||||
} else if ("subtract".equals(operator)) {
|
||||
result = a - b;
|
||||
} else if ("modulo".equals(operator)) {
|
||||
result = a % b;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public int calculateUsingSwitch(int a, int b, String operator) {
|
||||
int result = 0;
|
||||
switch (operator) {
|
||||
case "add":
|
||||
result = a + b;
|
||||
break;
|
||||
case "multiply":
|
||||
result = a * b;
|
||||
break;
|
||||
case "divide":
|
||||
result = a / b;
|
||||
break;
|
||||
case "subtract":
|
||||
result = a - b;
|
||||
break;
|
||||
case "modulo":
|
||||
result = a % b;
|
||||
break;
|
||||
default:
|
||||
result = Integer.MIN_VALUE;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public int calculateUsingSwitch(int a, int b, Operator operator) {
|
||||
int result = 0;
|
||||
switch (operator) {
|
||||
case ADD:
|
||||
result = a + b;
|
||||
break;
|
||||
case MULTIPLY:
|
||||
result = a * b;
|
||||
break;
|
||||
case DIVIDE:
|
||||
result = a / b;
|
||||
break;
|
||||
case SUBTRACT:
|
||||
result = a - b;
|
||||
break;
|
||||
case MODULO:
|
||||
result = a % b;
|
||||
break;
|
||||
default:
|
||||
result = Integer.MIN_VALUE;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public int calculate(int a, int b, Operator operator) {
|
||||
return operator.apply(a, b);
|
||||
}
|
||||
|
||||
public int calculateUsingFactory(int a, int b, String operation) {
|
||||
Operation targetOperation = OperatorFactory.getOperation(operation)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));
|
||||
return targetOperation.apply(a, b);
|
||||
}
|
||||
|
||||
public int calculate(Command command) {
|
||||
return command.execute();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public interface Command {
|
||||
Integer execute();
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Division implements Operation {
|
||||
@Override public int apply(int a, int b) {
|
||||
return a / b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Expression {
|
||||
|
||||
private Integer x;
|
||||
private Integer y;
|
||||
private Operator operator;
|
||||
|
||||
public Expression(Integer x, Integer y, Operator operator) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.operator = operator;
|
||||
}
|
||||
|
||||
public Integer getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public Integer getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public Operator getOperator() {
|
||||
return operator;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Modulo implements Operation {
|
||||
@Override public int apply(int a, int b) {
|
||||
return a % b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Multiplication implements Operation {
|
||||
@Override public int apply(int a, int b) {
|
||||
return 0;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public interface Operation {
|
||||
int apply(int a, int b);
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public enum Operator {
|
||||
|
||||
ADD {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
},
|
||||
|
||||
MULTIPLY {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a * b;
|
||||
}
|
||||
},
|
||||
|
||||
SUBTRACT {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a - b;
|
||||
}
|
||||
},
|
||||
|
||||
DIVIDE {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a / b;
|
||||
}
|
||||
},
|
||||
|
||||
MODULO {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a % b;
|
||||
}
|
||||
};
|
||||
|
||||
public abstract int apply(int a, int b);
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class OperatorFactory {
|
||||
|
||||
static Map<String, Operation> operationMap = new HashMap<>();
|
||||
static {
|
||||
operationMap.put("add", new Addition());
|
||||
operationMap.put("divide", new Division());
|
||||
operationMap.put("multiply", new Multiplication());
|
||||
operationMap.put("subtract", new Subtraction());
|
||||
operationMap.put("modulo", new Modulo());
|
||||
}
|
||||
|
||||
public static Optional<Operation> getOperation(String operation) {
|
||||
return Optional.ofNullable(operationMap.get(operation));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Result {
|
||||
int value;
|
||||
|
||||
public Result(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public interface Rule {
|
||||
|
||||
boolean evaluate(Expression expression);
|
||||
|
||||
Result getResult();
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class RuleEngine {
|
||||
|
||||
private static List<Rule> rules = new ArrayList<>();
|
||||
|
||||
static {
|
||||
rules.add(new AddRule());
|
||||
}
|
||||
|
||||
public Result process(Expression expression) {
|
||||
|
||||
Rule rule = rules.stream()
|
||||
.filter(r -> r.evaluate(expression))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Expression does not matches any Rule"));
|
||||
return rule.getResult();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Subtraction implements Operation {
|
||||
@Override public int apply(int a, int b) {
|
||||
return a - b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.reduceIfelse;
|
||||
|
||||
import com.baeldung.reducingIfElse.AddCommand;
|
||||
import com.baeldung.reducingIfElse.Calculator;
|
||||
import com.baeldung.reducingIfElse.Operator;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CalculatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCalculateUsingStringOperator_thenReturnCorrectResult() {
|
||||
Calculator calculator = new Calculator();
|
||||
int result = calculator.calculate(3, 4, "add");
|
||||
assertEquals(7, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculateUsingEnumOperator_thenReturnCorrectResult() {
|
||||
Calculator calculator = new Calculator();
|
||||
int result = calculator.calculate(3, 4, Operator.valueOf("ADD"));
|
||||
assertEquals(7, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculateUsingCommand_thenReturnCorrectResult() {
|
||||
Calculator calculator = new Calculator();
|
||||
int result = calculator.calculate(new AddCommand(3, 7));
|
||||
assertEquals(10, result);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.reduceIfelse;
|
||||
|
||||
import com.baeldung.reducingIfElse.Expression;
|
||||
import com.baeldung.reducingIfElse.Operator;
|
||||
import com.baeldung.reducingIfElse.Result;
|
||||
import com.baeldung.reducingIfElse.RuleEngine;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class RuleEngineUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenNumbersGivenToRuleEngine_thenReturnCorrectResult() {
|
||||
Expression expression = new Expression(5, 5, Operator.ADD);
|
||||
RuleEngine engine = new RuleEngine();
|
||||
Result result = engine.process(expression);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(10, result.getValue());
|
||||
}
|
||||
}
|
|
@ -61,11 +61,11 @@
|
|||
<properties>
|
||||
<openjdk.jmh.version>1.19</openjdk.jmh.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<eclipse.collections.version>7.1.0</eclipse.collections.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,197 @@
|
|||
package com.baeldung.array.operations;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
public class ArrayOperations {
|
||||
|
||||
// Get the first and last item of an array
|
||||
public static <T> T getFirstObject(T[] array) {
|
||||
return array[0];
|
||||
}
|
||||
|
||||
public static int getFirstInt(int[] array) {
|
||||
return array[0];
|
||||
}
|
||||
|
||||
public static <T> T getLastObject(T[] array) {
|
||||
return array[array.length - 1];
|
||||
}
|
||||
|
||||
public static int getLastInt(int[] array) {
|
||||
return array[array.length - 1];
|
||||
}
|
||||
|
||||
// Append a new item to an array
|
||||
public static <T> T[] appendObject(T[] array, T newItem) {
|
||||
return ArrayUtils.add(array, newItem);
|
||||
}
|
||||
|
||||
public static int[] appendInt(int[] array, int newItem) {
|
||||
int[] newArray = Arrays.copyOf(array, array.length + 1);
|
||||
newArray[newArray.length - 1] = newItem;
|
||||
return newArray;
|
||||
}
|
||||
|
||||
public static int[] appendIntWithUtils(int[] array, int newItem) {
|
||||
return ArrayUtils.add(array, newItem);
|
||||
}
|
||||
|
||||
// Compare two arrays to check if they have the same elements
|
||||
public static <T> boolean compareObjectArrays(T[] array1, T[] array2) {
|
||||
return Arrays.equals(array1, array2);
|
||||
}
|
||||
|
||||
public static boolean compareIntArrays(int[] array1, int[] array2) {
|
||||
return Arrays.equals(array1, array2);
|
||||
}
|
||||
|
||||
// Deep Compare (for nested arrays)
|
||||
public static <T> boolean deepCompareObjectArrayUsingArrays(T[][] array1, T[][] array2) {
|
||||
// We can use Objects.deepEquals for a broader approach
|
||||
return Arrays.deepEquals(array1, array2);
|
||||
}
|
||||
|
||||
public static boolean deepCompareIntArrayUsingArrays(int[][] array1, int[][] array2) {
|
||||
return Arrays.deepEquals(array1, array2);
|
||||
}
|
||||
|
||||
// Check if array is empty
|
||||
public static <T> boolean isEmptyObjectArrayUsingUtils(T[] array1) {
|
||||
return ArrayUtils.isEmpty(array1);
|
||||
}
|
||||
|
||||
public static boolean isEmptyIntArrayUsingUtils(int[] array1) {
|
||||
return ArrayUtils.isEmpty(array1);
|
||||
}
|
||||
|
||||
// Remove duplicates
|
||||
public static Integer[] removeDuplicateObjects(Integer[] array) {
|
||||
// We can use other ways of converting the array to a set too
|
||||
Set<Integer> set = new HashSet<>(Arrays.asList(array));
|
||||
return set.toArray(new Integer[set.size()]);
|
||||
}
|
||||
|
||||
public static int[] removeDuplicateInts(int[] array) {
|
||||
// Box
|
||||
Integer[] list = ArrayUtils.toObject(array);
|
||||
// Remove duplicates
|
||||
Set<Integer> set = new HashSet<Integer>(Arrays.asList(list));
|
||||
// Create array and unbox
|
||||
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
|
||||
}
|
||||
|
||||
// Remove duplicates preserving the order
|
||||
public static Integer[] removeDuplicateWithOrderObjectArray(Integer[] array) {
|
||||
// We can use other ways of converting the array to a set too
|
||||
Set<Integer> set = new LinkedHashSet<>(Arrays.asList(array));
|
||||
return set.toArray(new Integer[set.size()]);
|
||||
}
|
||||
|
||||
public static int[] removeDuplicateWithOrderIntArray(int[] array) {
|
||||
// Box
|
||||
Integer[] list = ArrayUtils.toObject(array);
|
||||
// Remove duplicates
|
||||
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(list));
|
||||
// Create array and unbox
|
||||
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
|
||||
}
|
||||
|
||||
// Print an array
|
||||
public static String printObjectArray(Integer[] array) {
|
||||
return ArrayUtils.toString(array);
|
||||
}
|
||||
|
||||
public static String printObjectArray(Integer[][] array) {
|
||||
return ArrayUtils.toString(array);
|
||||
}
|
||||
|
||||
public static String printIntArray(int[] array) {
|
||||
return ArrayUtils.toString(array);
|
||||
}
|
||||
|
||||
public static String printIntArray(int[][] array) {
|
||||
return ArrayUtils.toString(array);
|
||||
}
|
||||
|
||||
// Box or Unbox values
|
||||
public static int[] unboxIntegerArray(Integer[] array) {
|
||||
return ArrayUtils.toPrimitive(array);
|
||||
}
|
||||
|
||||
public static Integer[] boxIntArray(int[] array) {
|
||||
return ArrayUtils.toObject(array);
|
||||
}
|
||||
|
||||
// Map array values
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T, U> U[] mapObjectArray(T[] array, Function<T, U> function, Class<U> targetClazz) {
|
||||
U[] newArray = (U[]) Array.newInstance(targetClazz, array.length);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
newArray[i] = function.apply(array[i]);
|
||||
}
|
||||
return newArray;
|
||||
}
|
||||
|
||||
public static String[] mapIntArrayToString(int[] array) {
|
||||
return Arrays.stream(array)
|
||||
.mapToObj(value -> String.format("Value: %s", value))
|
||||
.toArray(String[]::new);
|
||||
}
|
||||
|
||||
// Filter array values
|
||||
public static Integer[] filterObjectArray(Integer[] array, Predicate<Integer> predicate) {
|
||||
return Arrays.stream(array)
|
||||
.filter(predicate)
|
||||
.toArray(Integer[]::new);
|
||||
}
|
||||
|
||||
public static int[] filterIntArray(int[] array, IntPredicate predicate) {
|
||||
return Arrays.stream(array)
|
||||
.filter(predicate)
|
||||
.toArray();
|
||||
}
|
||||
|
||||
// Insert item between others
|
||||
public static int[] insertBetweenIntArray(int[] array, int... values) {
|
||||
return ArrayUtils.insert(2, array, values);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T[] insertBetweenObjectArray(T[] array, T... values) {
|
||||
return ArrayUtils.insert(2, array, values);
|
||||
}
|
||||
|
||||
// Shuffling arrays
|
||||
public static int[] shuffleIntArray(int[] array) {
|
||||
// we create a different array instance for testing purposes
|
||||
int[] shuffled = Arrays.copyOf(array, array.length);
|
||||
ArrayUtils.shuffle(shuffled);
|
||||
return shuffled;
|
||||
}
|
||||
|
||||
public static <T> T[] shuffleObjectArray(T[] array) {
|
||||
// we create a different array instance for testing purposes
|
||||
T[] shuffled = Arrays.copyOf(array, array.length);
|
||||
ArrayUtils.shuffle(shuffled);
|
||||
return shuffled;
|
||||
}
|
||||
|
||||
// Get random number
|
||||
public static int getRandomFromIntArray(int[] array) {
|
||||
return array[new Random().nextInt(array.length)];
|
||||
}
|
||||
|
||||
public static <T> T getRandomFromObjectArray(T[] array) {
|
||||
return array[new Random().nextInt(array.length)];
|
||||
}
|
||||
}
|
|
@ -0,0 +1,365 @@
|
|||
package com.baeldung.array.operations;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.assertj.core.api.Condition;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ArrayOperationsUnitTest {
|
||||
|
||||
private Integer[] defaultObjectArray;
|
||||
private int[] defaultIntArray;
|
||||
private Integer[][] defaultJaggedObjectArray;
|
||||
private int[][] defaultJaggedIntArray;
|
||||
|
||||
@BeforeEach
|
||||
public void setupDefaults() {
|
||||
defaultObjectArray = new Integer[] { 3, 5, 2, 5, 14, 4 };
|
||||
defaultIntArray = new int[] { 3, 5, 2, 5, 14, 4 };
|
||||
defaultJaggedObjectArray = new Integer[][] { { 1, 3 }, { 5 }, {} };
|
||||
defaultJaggedIntArray = new int[][] { { 1, 3 }, { 5 }, {} };
|
||||
}
|
||||
|
||||
// Get the first and last item of an array
|
||||
@Test
|
||||
public void whenGetFirstObjectCalled_thenReturnFirstItemOfArray() {
|
||||
Integer output = ArrayOperations.getFirstObject(defaultObjectArray);
|
||||
|
||||
assertThat(output).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFirstIntCalled_thenReturnFirstItemOfArray() {
|
||||
int output = ArrayOperations.getFirstInt(defaultIntArray);
|
||||
|
||||
assertThat(output).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetLastObjectCalled_thenReturnLastItemOfArray() {
|
||||
Integer output = ArrayOperations.getLastObject(defaultObjectArray);
|
||||
|
||||
assertThat(output).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetLastIntCalled_thenReturnLastItemOfArray() {
|
||||
int output = ArrayOperations.getLastInt(defaultIntArray);
|
||||
|
||||
assertThat(output).isEqualTo(4);
|
||||
}
|
||||
|
||||
// Append a new item to an array
|
||||
@Test
|
||||
public void whenAppendObject_thenReturnArrayWithExtraItem() {
|
||||
Integer[] output = ArrayOperations.appendObject(defaultObjectArray, 7);
|
||||
|
||||
assertThat(output).endsWith(4, 7)
|
||||
.hasSize(7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendInt_thenReturnArrayWithExtraItem() {
|
||||
int[] output = ArrayOperations.appendInt(defaultIntArray, 7);
|
||||
int[] outputUsingUtils = ArrayOperations.appendIntWithUtils(defaultIntArray, 7);
|
||||
|
||||
assertThat(output).endsWith(4, 7)
|
||||
.hasSize(7);
|
||||
assertThat(outputUsingUtils).endsWith(4, 7)
|
||||
.hasSize(7);
|
||||
}
|
||||
|
||||
// Compare two arrays to check if they have the same elements
|
||||
@Test
|
||||
public void whenCompareObjectArrays_thenReturnBoolean() {
|
||||
Integer[] array2 = { 8, 7, 6 };
|
||||
Integer[] sameArray = { 3, 5, 2, 5, 14, 4 };
|
||||
boolean output = ArrayOperations.compareObjectArrays(defaultObjectArray, array2);
|
||||
boolean output2 = ArrayOperations.compareObjectArrays(defaultObjectArray, sameArray);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompareIntArrays_thenReturnBoolean() {
|
||||
int[] array2 = { 8, 7, 6 };
|
||||
int[] sameArray = { 3, 5, 2, 5, 14, 4 };
|
||||
boolean output = ArrayOperations.compareIntArrays(defaultIntArray, array2);
|
||||
boolean output2 = ArrayOperations.compareIntArrays(defaultIntArray, sameArray);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
}
|
||||
|
||||
// Deep compare
|
||||
@Test
|
||||
public void whenDeepCompareObjectArrays_thenReturnBoolean() {
|
||||
Integer[][] sameArray = { { 1, 3 }, { 5 }, {} };
|
||||
Integer[][] array2 = { { 1, 3 }, { 5 }, { 3 } };
|
||||
boolean output = ArrayOperations.deepCompareObjectArrayUsingArrays(defaultJaggedObjectArray, array2);
|
||||
boolean output2 = ArrayOperations.deepCompareObjectArrayUsingArrays(defaultJaggedObjectArray, sameArray);
|
||||
// Because arrays are Objects, we could wrongly use the non-deep approach
|
||||
boolean outputUsingNonDeep = ArrayOperations.compareObjectArrays(defaultJaggedObjectArray, sameArray);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
// This is not what we would expect!
|
||||
assertThat(outputUsingNonDeep).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeepCompareIntArrays_thenReturnBoolean() {
|
||||
int[][] sameArray = { { 1, 3 }, { 5 }, {} };
|
||||
int[][] array2 = { { 1, 3 }, { 5 }, { 3 } };
|
||||
boolean output = ArrayOperations.deepCompareIntArrayUsingArrays(defaultJaggedIntArray, array2);
|
||||
boolean output2 = ArrayOperations.deepCompareIntArrayUsingArrays(defaultJaggedIntArray, sameArray);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
}
|
||||
|
||||
// Empty Check
|
||||
@Test
|
||||
public void whenIsEmptyObjectArray_thenReturnBoolean() {
|
||||
Integer[] array2 = {};
|
||||
Integer[] array3 = null;
|
||||
Integer[] array4 = { null, null, null };
|
||||
Integer[] array5 = { null };
|
||||
Integer[][] array6 = { {}, {}, {} };
|
||||
boolean output = ArrayOperations.isEmptyObjectArrayUsingUtils(defaultObjectArray);
|
||||
boolean output2 = ArrayOperations.isEmptyObjectArrayUsingUtils(array2);
|
||||
boolean output3 = ArrayOperations.isEmptyObjectArrayUsingUtils(array3);
|
||||
boolean output4 = ArrayOperations.isEmptyObjectArrayUsingUtils(array4);
|
||||
boolean output5 = ArrayOperations.isEmptyObjectArrayUsingUtils(array5);
|
||||
boolean output6 = ArrayOperations.isEmptyObjectArrayUsingUtils(array6);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
assertThat(output3).isTrue();
|
||||
// Mind these edge cases!
|
||||
assertThat(output4).isFalse();
|
||||
assertThat(output5).isFalse();
|
||||
assertThat(output6).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIsEmptyIntArray_thenReturnBoolean() {
|
||||
int[] array2 = {};
|
||||
boolean output = ArrayOperations.isEmptyIntArrayUsingUtils(defaultIntArray);
|
||||
boolean output2 = ArrayOperations.isEmptyIntArrayUsingUtils(array2);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
}
|
||||
|
||||
// Remove Duplicates
|
||||
@Test
|
||||
public void whenRemoveDuplicateObjectArray_thenReturnArrayWithNoDuplicates() {
|
||||
Integer[] output = ArrayOperations.removeDuplicateObjects(defaultObjectArray);
|
||||
|
||||
assertThat(output).containsOnlyOnce(5)
|
||||
.hasSize(5)
|
||||
.doesNotHaveDuplicates();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveDuplicateIntArray_thenReturnArrayWithNoDuplicates() {
|
||||
int[] output = ArrayOperations.removeDuplicateInts(defaultIntArray);
|
||||
|
||||
assertThat(output).containsOnlyOnce(5)
|
||||
.hasSize(5)
|
||||
.doesNotHaveDuplicates();
|
||||
}
|
||||
|
||||
// Remove Duplicates Preserving order
|
||||
@Test
|
||||
public void whenRemoveDuplicatePreservingOrderObjectArray_thenReturnArrayWithNoDuplicates() {
|
||||
Integer[] array2 = { 3, 5, 2, 14, 4 };
|
||||
Integer[] output = ArrayOperations.removeDuplicateWithOrderObjectArray(defaultObjectArray);
|
||||
|
||||
assertThat(output).containsOnlyOnce(5)
|
||||
.hasSize(5)
|
||||
.containsExactly(array2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveDuplicatePreservingOrderIntArray_thenReturnArrayWithNoDuplicates() {
|
||||
int[] array2 = { 3, 5, 2, 14, 4 };
|
||||
int[] output = ArrayOperations.removeDuplicateWithOrderIntArray(defaultIntArray);
|
||||
|
||||
assertThat(output).containsOnlyOnce(5)
|
||||
.hasSize(5)
|
||||
.containsExactly(array2);
|
||||
}
|
||||
|
||||
// Print
|
||||
@Test
|
||||
public void whenPrintObjectArray_thenReturnString() {
|
||||
String output = ArrayOperations.printObjectArray(defaultObjectArray);
|
||||
String jaggedOutput = ArrayOperations.printObjectArray(defaultJaggedObjectArray);
|
||||
// Comparing to Arrays output:
|
||||
String wrongArraysOutput = Arrays.toString(defaultJaggedObjectArray);
|
||||
String differentFormatArraysOutput = Arrays.toString(defaultObjectArray);
|
||||
// We should use Arrays.deepToString for jagged arrays
|
||||
String differentFormatJaggedArraysOutput = Arrays.deepToString(defaultJaggedObjectArray);
|
||||
|
||||
assertThat(output).isEqualTo("{3,5,2,5,14,4}");
|
||||
assertThat(jaggedOutput).isEqualTo("{{1,3},{5},{}}");
|
||||
assertThat(differentFormatArraysOutput).isEqualTo("[3, 5, 2, 5, 14, 4]");
|
||||
assertThat(wrongArraysOutput).contains("[[Ljava.lang.Integer;@");
|
||||
assertThat(differentFormatJaggedArraysOutput).contains("[[1, 3], [5], []]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPrintIntArray_thenReturnString() {
|
||||
String output = ArrayOperations.printIntArray(defaultIntArray);
|
||||
String jaggedOutput = ArrayOperations.printIntArray(defaultJaggedIntArray);
|
||||
// Comparing to Arrays output:
|
||||
String wrongArraysOutput = Arrays.toString(defaultJaggedObjectArray);
|
||||
String differentFormatArraysOutput = Arrays.toString(defaultObjectArray);
|
||||
|
||||
assertThat(output).isEqualTo("{3,5,2,5,14,4}");
|
||||
assertThat(jaggedOutput).isEqualTo("{{1,3},{5},{}}");
|
||||
assertThat(differentFormatArraysOutput).isEqualTo("[3, 5, 2, 5, 14, 4]");
|
||||
assertThat(wrongArraysOutput).contains("[[Ljava.lang.Integer;@");
|
||||
}
|
||||
|
||||
// Box and unbox
|
||||
@Test
|
||||
public void whenUnboxObjectArray_thenReturnPrimitiveArray() {
|
||||
int[] output = ArrayOperations.unboxIntegerArray(defaultObjectArray);
|
||||
|
||||
assertThat(output).containsExactly(defaultIntArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void henBoxPrimitiveArray_thenReturnObjectArray() {
|
||||
Integer[] output = ArrayOperations.boxIntArray(defaultIntArray);
|
||||
|
||||
assertThat(output).containsExactly(defaultObjectArray);
|
||||
}
|
||||
|
||||
// Map values
|
||||
@Test
|
||||
public void whenMapMultiplyingObjectArray_thenReturnMultipliedArray() {
|
||||
Integer[] multipliedExpectedArray = new Integer[] { 6, 10, 4, 10, 28, 8 };
|
||||
Integer[] output = ArrayOperations.mapObjectArray(defaultObjectArray, value -> value * 2, Integer.class);
|
||||
|
||||
assertThat(output).containsExactly(multipliedExpectedArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapDividingObjectArray_thenReturnDividedArray() {
|
||||
Double[] multipliedExpectedArray = new Double[] { 1.5, 2.5, 1.0, 2.5, 7.0, 2.0 };
|
||||
Double[] output = ArrayOperations.mapObjectArray(defaultObjectArray, value -> value / 2.0, Double.class);
|
||||
|
||||
assertThat(output).containsExactly(multipliedExpectedArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapIntArrayToString_thenReturnArray() {
|
||||
String[] expectedArray = new String[] { "Value: 3", "Value: 5", "Value: 2", "Value: 5", "Value: 14",
|
||||
"Value: 4" };
|
||||
String[] output = ArrayOperations.mapIntArrayToString(defaultIntArray);
|
||||
|
||||
assertThat(output).containsExactly(expectedArray);
|
||||
}
|
||||
|
||||
// Filter values
|
||||
@Test
|
||||
public void whenFilterObjectArray_thenReturnFilteredArray() {
|
||||
Integer[] multipliedExpectedArray = new Integer[] { 2, 14, 4 };
|
||||
Integer[] output = ArrayOperations.filterObjectArray(defaultObjectArray, value -> value % 2 == 0);
|
||||
|
||||
assertThat(output).containsExactly(multipliedExpectedArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterIntArray_thenReturnFilteredArray() {
|
||||
int[] expectedArray = new int[] { 2, 14, 4 };
|
||||
int[] output = ArrayOperations.filterIntArray(defaultIntArray, value -> (int) value % 2 == 0);
|
||||
|
||||
assertThat(output).containsExactly(expectedArray);
|
||||
}
|
||||
|
||||
// Insert between
|
||||
@Test
|
||||
public void whenInsertBetweenIntArrayToString_thenReturnNewArray() {
|
||||
int[] expectedArray = { 3, 5, 77, 88, 2, 5, 14, 4 };
|
||||
int[] output = ArrayOperations.insertBetweenIntArray(defaultIntArray, 77, 88);
|
||||
|
||||
assertThat(output).containsExactly(expectedArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsertBetweenObjectArrayToString_thenReturnNewArray() {
|
||||
Integer[] expectedArray = { 3, 5, 77, 99, 2, 5, 14, 4 };
|
||||
Integer[] output = ArrayOperations.insertBetweenObjectArray(defaultObjectArray, 77, 99);
|
||||
|
||||
assertThat(output).containsExactly(expectedArray);
|
||||
}
|
||||
|
||||
// Shuffle between
|
||||
@Test
|
||||
public void whenShufflingIntArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
|
||||
int[] output = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
int[] output2 = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
int[] output3 = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
int[] output4 = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
int[] output5 = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
int[] output6 = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
|
||||
Condition<int[]> atLeastOneArraysIsNotEqual = new Condition<int[]>(
|
||||
"at least one output should be different (order-wise)") {
|
||||
@Override
|
||||
public boolean matches(int[] value) {
|
||||
return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3)
|
||||
|| !Arrays.equals(value, output4) || !Arrays.equals(value, output5)
|
||||
|| !Arrays.equals(value, output6);
|
||||
}
|
||||
};
|
||||
|
||||
assertThat(defaultIntArray).has(atLeastOneArraysIsNotEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenShufflingObjectArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
|
||||
Integer[] output = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
Integer[] output2 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
Integer[] output3 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
Integer[] output4 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
Integer[] output5 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
Integer[] output6 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
|
||||
Condition<Integer[]> atLeastOneArraysIsNotEqual = new Condition<Integer[]>(
|
||||
"at least one output should be different (order-wise)") {
|
||||
@Override
|
||||
public boolean matches(Integer[] value) {
|
||||
return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3)
|
||||
|| !Arrays.equals(value, output4) || !Arrays.equals(value, output5)
|
||||
|| !Arrays.equals(value, output6);
|
||||
}
|
||||
};
|
||||
|
||||
assertThat(defaultObjectArray).has(atLeastOneArraysIsNotEqual);
|
||||
}
|
||||
|
||||
// Get random item
|
||||
@Test
|
||||
public void whenGetRandomFromIntArrayToString_thenReturnItemContainedInArray() {
|
||||
int output = ArrayOperations.getRandomFromIntArray(defaultIntArray);
|
||||
|
||||
assertThat(defaultIntArray).contains(output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRandomFromObjectArrayToString_thenReturnItemContainedInArray() {
|
||||
Integer output = ArrayOperations.getRandomFromObjectArray(defaultObjectArray);
|
||||
|
||||
assertThat(defaultObjectArray).contains(output);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.enummap;
|
||||
|
||||
/**
|
||||
* This enum is used for benchmarking, therefore has many values.
|
||||
*/
|
||||
public enum DummyEnum {
|
||||
CCC_000,
|
||||
CCC_001,CCC_002,CCC_003,CCC_004,CCC_005,CCC_006,CCC_007,CCC_008,CCC_009,CCC_010,
|
||||
CCC_011,CCC_012,CCC_013,CCC_014,CCC_015,CCC_016,CCC_017,CCC_018,CCC_019,CCC_020,
|
||||
CCC_021,CCC_022,CCC_023,CCC_024,CCC_025,CCC_026,CCC_027,CCC_028,CCC_029,CCC_030,
|
||||
CCC_031,CCC_032,CCC_033,CCC_034,CCC_035,CCC_036,CCC_037,CCC_038,CCC_039,CCC_040,
|
||||
CCC_041,CCC_042,CCC_043,CCC_044,CCC_045,CCC_046,CCC_047,CCC_048,CCC_049,
|
||||
}
|
|
@ -0,0 +1,119 @@
|
|||
package com.baeldung.enummap;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode({ Mode.AverageTime })
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 5)
|
||||
public class EnumMapBenchmarkLiveTest {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class BenchmarkState {
|
||||
EnumMap<DummyEnum, String> enumMap = new EnumMap<>(DummyEnum.class);
|
||||
HashMap<DummyEnum, String> hashMap = new HashMap<>();
|
||||
TreeMap<DummyEnum, String> treeMap = new TreeMap<>();
|
||||
int len = DummyEnum.values().length;
|
||||
Random random = new Random();
|
||||
int randomIndex;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
DummyEnum[] values = DummyEnum.values();
|
||||
for (int i = 0; i < len; i++) {
|
||||
enumMap.put(values[i], values[i].toString());
|
||||
hashMap.put(values[i], values[i].toString());
|
||||
treeMap.put(values[i], values[i].toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Setup(Level.Invocation)
|
||||
public void additionalSetup() {
|
||||
randomIndex = random.nextInt(len);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark01_EnumMapPut(BenchmarkState s) {
|
||||
s.enumMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark01_HashMapPut(BenchmarkState s) {
|
||||
s.hashMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark01_TreeMapPut(BenchmarkState s) {
|
||||
s.treeMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark02_EnumMapGet(BenchmarkState s) {
|
||||
s.enumMap.get(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark02_HashMapGet(BenchmarkState s) {
|
||||
s.hashMap.get(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark02_TreeMapGet(BenchmarkState s) {
|
||||
s.treeMap.get(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark03_EnumMapContainsKey(BenchmarkState s) {
|
||||
s.enumMap.containsKey(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark03_HashMapContainsKey(BenchmarkState s) {
|
||||
s.hashMap.containsKey(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark03_TreeMapContainsKey(BenchmarkState s) {
|
||||
s.treeMap.containsKey(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark04_EnumMapContainsValue(BenchmarkState s) {
|
||||
s.enumMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark04_HashMapContainsValue(BenchmarkState s) {
|
||||
s.hashMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark04_TreeMapContainsValue(BenchmarkState s) {
|
||||
s.treeMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder().include(EnumMapBenchmarkLiveTest.class.getSimpleName()).threads(1).forks(0).shouldFailOnError(true).shouldDoGC(false).jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,144 @@
|
|||
package com.baeldung.enummap;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static java.util.AbstractMap.SimpleEntry;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
|
||||
public class EnumMapUnitTest {
|
||||
public enum DayOfWeek {
|
||||
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenContructedWithEnumType_ThenOnlyAcceptThatAsKey() {
|
||||
Map dayMap = new EnumMap<>(DayOfWeek.class);
|
||||
assertThatCode(
|
||||
() -> dayMap.put(TimeUnit.NANOSECONDS, "NANOSECONDS"))
|
||||
.isInstanceOf(ClassCastException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConstructedWithEnumMap_ThenSameKeyTypeAndInitialMappings() {
|
||||
EnumMap<DayOfWeek, String> activityMap = new EnumMap<>(DayOfWeek.class);
|
||||
activityMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
activityMap.put(DayOfWeek.TUESDAY, "Basketball");
|
||||
|
||||
EnumMap<DayOfWeek, String> activityMapCopy = new EnumMap<>(activityMap);
|
||||
assertThat(activityMapCopy.size()).isEqualTo(2);
|
||||
assertThat(activityMapCopy.get(DayOfWeek.MONDAY))
|
||||
.isEqualTo("Soccer");
|
||||
assertThat(activityMapCopy.get(DayOfWeek.TUESDAY))
|
||||
.isEqualTo("Basketball");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyMap_whenConstructedWithMap_ThenException() {
|
||||
HashMap ordinaryMap = new HashMap();
|
||||
assertThatCode(() -> new EnumMap(ordinaryMap))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("Specified map is empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapWithEntries_whenConstructedWithMap_ThenSucceed() {
|
||||
HashMap<DayOfWeek, String> ordinaryMap = new HashMap<>();
|
||||
ordinaryMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
ordinaryMap.put(DayOfWeek.TUESDAY, "Basketball");
|
||||
EnumMap<DayOfWeek, String> enumMap = new EnumMap<>(ordinaryMap);
|
||||
assertThat(enumMap.size()).isEqualTo(2);
|
||||
assertThat(enumMap.get(DayOfWeek.MONDAY)).isEqualTo("Soccer");
|
||||
assertThat(enumMap.get(DayOfWeek.TUESDAY)).isEqualTo("Basketball");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapWithMultiTypeEntries_whenConstructedWithMap_ThenException() {
|
||||
HashMap<Enum, String> ordinaryMap = new HashMap<>();
|
||||
ordinaryMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
ordinaryMap.put(TimeUnit.MILLISECONDS, "Other enum type");
|
||||
assertThatCode(() -> new EnumMap(ordinaryMap))
|
||||
.isInstanceOf(ClassCastException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPut_thenGet() {
|
||||
Map<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
|
||||
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
|
||||
activityMap.put(DayOfWeek.THURSDAY, null);
|
||||
assertThat(activityMap.get(DayOfWeek.WEDNESDAY)).isEqualTo("Hiking");
|
||||
assertThat(activityMap.get(DayOfWeek.THURSDAY)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapping_whenContains_thenTrue() {
|
||||
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
|
||||
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isFalse();
|
||||
assertThat(activityMap.containsValue("Hiking")).isFalse();
|
||||
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
|
||||
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isTrue();
|
||||
assertThat(activityMap.containsValue("Hiking")).isTrue();
|
||||
|
||||
assertThat(activityMap.containsKey(DayOfWeek.SATURDAY)).isFalse();
|
||||
assertThat(activityMap.containsValue(null)).isFalse();
|
||||
activityMap.put(DayOfWeek.SATURDAY, null);
|
||||
assertThat(activityMap.containsKey(DayOfWeek.SATURDAY)).isTrue();
|
||||
assertThat(activityMap.containsValue(null)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemove_thenRemoved() {
|
||||
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
|
||||
|
||||
activityMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
assertThat(activityMap.remove(DayOfWeek.MONDAY)).isEqualTo("Soccer");
|
||||
assertThat(activityMap.containsKey(DayOfWeek.MONDAY)).isFalse();
|
||||
|
||||
activityMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
assertThat(activityMap.remove(DayOfWeek.MONDAY, "Hiking")).isEqualTo(false);
|
||||
assertThat(activityMap.remove(DayOfWeek.MONDAY, "Soccer")).isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSubView_thenSubViewOrdered() {
|
||||
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
|
||||
activityMap.put(DayOfWeek.THURSDAY, "Karate");
|
||||
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
|
||||
activityMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
|
||||
Collection<String> values = activityMap.values();
|
||||
assertThat(values).containsExactly("Soccer", "Hiking", "Karate");
|
||||
|
||||
Set<DayOfWeek> keys = activityMap.keySet();
|
||||
assertThat(keys)
|
||||
.containsExactly(DayOfWeek.MONDAY, DayOfWeek.WEDNESDAY,DayOfWeek.THURSDAY);
|
||||
|
||||
assertThat(activityMap.entrySet())
|
||||
.containsExactly(
|
||||
new SimpleEntry(DayOfWeek.MONDAY, "Soccer"),
|
||||
new SimpleEntry(DayOfWeek.WEDNESDAY, "Hiking"),
|
||||
new SimpleEntry(DayOfWeek.THURSDAY, "Karate"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubView_whenChange_thenReflected() {
|
||||
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
|
||||
activityMap.put(DayOfWeek.THURSDAY, "Karate");
|
||||
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
|
||||
activityMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
|
||||
Collection<String> values = activityMap.values();
|
||||
assertThat(values).containsExactly("Soccer", "Hiking", "Karate");
|
||||
|
||||
activityMap.put(DayOfWeek.TUESDAY, "Basketball");
|
||||
assertThat(values)
|
||||
.containsExactly("Soccer", "Basketball", "Hiking", "Karate");
|
||||
|
||||
values.remove("Hiking");
|
||||
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isFalse();
|
||||
assertThat(activityMap.size()).isEqualTo(3);
|
||||
}
|
||||
}
|
|
@ -30,3 +30,4 @@
|
|||
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
|
||||
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
|
||||
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)
|
||||
- [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads)
|
||||
|
|
|
@ -0,0 +1,72 @@
|
|||
package com.baeldung.concurrent.evenandodd;
|
||||
|
||||
public class PrintEvenOdd {
|
||||
|
||||
public static void main(String... args) {
|
||||
Printer print = new Printer();
|
||||
Thread t1 = new Thread(new TaskEvenOdd(print, 10, false));
|
||||
t1.setName("Odd");
|
||||
Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));
|
||||
t2.setName("Even");
|
||||
t1.start();
|
||||
t2.start();
|
||||
}
|
||||
}
|
||||
|
||||
class TaskEvenOdd implements Runnable {
|
||||
private int max;
|
||||
private Printer print;
|
||||
private boolean isEvenNumber;
|
||||
|
||||
TaskEvenOdd(Printer print, int max, boolean isEvenNumber) {
|
||||
this.print = print;
|
||||
this.max = max;
|
||||
this.isEvenNumber = isEvenNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
int number = isEvenNumber == true ? 2 : 1;
|
||||
while (number <= max) {
|
||||
if (isEvenNumber) {
|
||||
print.printEven(number);
|
||||
} else {
|
||||
print.printOdd(number);
|
||||
}
|
||||
number += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Printer {
|
||||
boolean isOdd = false;
|
||||
|
||||
synchronized void printEven(int number) {
|
||||
while (isOdd == false) {
|
||||
try {
|
||||
wait();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
System.out.println(Thread.currentThread()
|
||||
.getName() + ":" + number);
|
||||
isOdd = false;
|
||||
notify();
|
||||
}
|
||||
|
||||
synchronized void printOdd(int number) {
|
||||
while (isOdd == true) {
|
||||
try {
|
||||
wait();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
System.out.println(Thread.currentThread()
|
||||
.getName() + ":" + number);
|
||||
isOdd = true;
|
||||
notify();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.concurrent.evenandodd;
|
||||
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
public class SemaphoreDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
SharedPrinter sp = new SharedPrinter();
|
||||
Thread odd = new Thread(new Odd(sp, 10));
|
||||
odd.setName("Odd");
|
||||
Thread even = new Thread(new Even(sp, 10));
|
||||
even.setName("Even");
|
||||
|
||||
odd.start();
|
||||
even.start();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class SharedPrinter {
|
||||
|
||||
Semaphore semEven = new Semaphore(0);
|
||||
Semaphore semOdd = new Semaphore(1);
|
||||
|
||||
public void printEvenNum(int num) {
|
||||
try {
|
||||
semEven.acquire();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println(Thread.currentThread()
|
||||
.getName() + ":"+num);
|
||||
semOdd.release();
|
||||
}
|
||||
|
||||
public void printOddNum(int num) {
|
||||
try {
|
||||
semOdd.acquire();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println(Thread.currentThread()
|
||||
.getName() + ":"+ num);
|
||||
semEven.release();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
class Even implements Runnable {
|
||||
SharedPrinter sp;
|
||||
int max;
|
||||
|
||||
Even(SharedPrinter sp, int max) {
|
||||
this.sp = sp;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 2; i <= max; i = i + 2) {
|
||||
sp.printEvenNum(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Odd implements Runnable {
|
||||
SharedPrinter sp;
|
||||
int max;
|
||||
|
||||
Odd(SharedPrinter sp, int max) {
|
||||
this.sp = sp;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 1; i <= max; i = i + 2) {
|
||||
sp.printOddNum(i);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
package com.baeldung.bufferedreader;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class BufferedReaderExample {
|
||||
|
||||
public String readAllLines(BufferedReader reader) throws IOException {
|
||||
StringBuilder content = new StringBuilder();
|
||||
String line;
|
||||
|
||||
while ((line = reader.readLine()) != null) {
|
||||
content.append(line);
|
||||
content.append(System.lineSeparator());
|
||||
}
|
||||
|
||||
return content.toString();
|
||||
}
|
||||
|
||||
public String readAllLinesWithStream(BufferedReader reader) {
|
||||
return reader
|
||||
.lines()
|
||||
.collect(Collectors.joining(System.lineSeparator()));
|
||||
}
|
||||
|
||||
public String readAllCharsOneByOne(BufferedReader reader) throws IOException {
|
||||
StringBuilder content = new StringBuilder();
|
||||
|
||||
int value;
|
||||
while ((value = reader.read()) != -1) {
|
||||
content.append((char) value);
|
||||
}
|
||||
|
||||
return content.toString();
|
||||
}
|
||||
|
||||
public String readMultipleChars(BufferedReader reader) throws IOException {
|
||||
int length = 5;
|
||||
char[] chars = new char[length];
|
||||
int charsRead = reader.read(chars, 0, length);
|
||||
|
||||
String result;
|
||||
if (charsRead != -1) {
|
||||
result = new String(chars, 0, charsRead);
|
||||
} else {
|
||||
result = "";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String readFile() {
|
||||
BufferedReader reader = null;
|
||||
try {
|
||||
reader = new BufferedReader(new FileReader("src/main/resources/input.txt"));
|
||||
String content = readAllLines(reader);
|
||||
return content;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
} finally {
|
||||
try {
|
||||
if (reader != null) {
|
||||
reader.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String readFileTryWithResources() {
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/input.txt"))) {
|
||||
String content = readAllLines(reader);
|
||||
return content;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In lacus enim, scelerisque id sapien ut, semper euismod quam. Nunc ullamcorper semper blandit. Praesent quis quam mollis, iaculis lectus a, fringilla leo. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis vitae auctor mauris. Pellentesque eu pellentesque lorem, vel ultricies libero. Pellentesque vestibulum sagittis eros. In vestibulum lacus elit. Interdum et malesuada fames ac ante ipsum primis in faucibus.
|
||||
|
||||
Vivamus pharetra lacus fringilla nisl molestie eleifend. Donec et dolor non quam mattis mattis. Proin malesuada maximus elit id semper. Donec facilisis dolor ut feugiat auctor. Proin accumsan semper consectetur. Vivamus facilisis odio vel bibendum imperdiet. Sed rutrum nisi nec nisi interdum fringilla. Aliquam laoreet velit ullamcorper egestas ultrices. Aliquam ultricies sem sed orci interdum, eu porta purus malesuada. Sed accumsan, nunc ut maximus rhoncus, arcu ante pretium ex, non ultrices magna nisi et velit. Pellentesque tempor mi quis lacus consectetur, quis imperdiet enim efficitur. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
|
||||
|
||||
Nunc sed maximus erat. Aenean imperdiet finibus massa ac aliquam. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis dignissim cursus purus, eu tempus urna. Nunc sed mauris scelerisque, luctus eros ut, viverra nisi. Maecenas congue sed ligula in eleifend. Praesent nec dignissim enim, dictum efficitur massa. Nullam eros dui, rutrum quis aliquam accumsan, sollicitudin cursus eros. Phasellus euismod, lorem vitae vehicula ullamcorper, leo lorem vestibulum magna, vitae malesuada libero ipsum id lorem. Aenean finibus turpis facilisis tortor bibendum, vitae dignissim dolor dictum. Ut quis ornare nisi, non rutrum sapien.
|
||||
|
||||
Etiam placerat, est eget placerat imperdiet, neque urna tristique est, a dictum nisl dolor vitae leo. Vivamus porttitor mi vitae volutpat ultrices. Quisque at ante porta mauris ultricies iaculis. Phasellus iaculis sollicitudin urna nec facilisis. Suspendisse dapibus vulputate scelerisque. Fusce felis diam, eleifend in tristique in, malesuada a purus. Suspendisse euismod ipsum sed urna imperdiet, quis venenatis lacus dapibus. Maecenas vitae est vel sem fringilla ornare at ut mi. Quisque porta, nulla at rutrum fringilla, mi ligula egestas libero, ac convallis elit diam et sapien. Vestibulum purus tortor, ornare ut enim sed, mattis lobortis erat. Maecenas ac ante tincidunt, euismod mauris a, fermentum diam. Nullam arcu est, consequat sed enim in, bibendum aliquet velit. Donec bibendum magna ac augue sagittis vehicula. Curabitur nec mauris eu augue bibendum volutpat. Fusce fringilla varius fringilla.
|
||||
|
||||
Aliquam faucibus massa non orci accumsan, porta consectetur diam vulputate. Nullam nec erat mollis, imperdiet libero nec, tincidunt neque. Aenean varius purus nec est auctor, sed vulputate libero varius. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vel neque elit. Donec vulputate fermentum nulla, ut aliquam neque tempor in. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec vel venenatis est. Suspendisse luctus elit quis dui dapibus, id sodales dolor cursus. Curabitur ut vehicula dui. Fusce aliquet est et ante feugiat, et tempus ex congue. Nunc eget dapibus leo. Nunc eu accumsan diam. Suspendisse risus eros, rutrum et volutpat in, consequat in nulla. Suspendisse id felis a orci accumsan iaculis.
|
||||
|
||||
Duis tincidunt diam eget tortor aliquet sodales. Etiam sodales purus ac urna mollis, et cursus enim porttitor. Nulla viverra ligula nunc, ornare condimentum felis posuere sed. Fusce aliquet pretium sagittis. Sed ac mi elementum massa dictum ornare. Integer quis dapibus lectus. Curabitur in rhoncus justo, et vulputate justo. Integer eget efficitur felis.
|
||||
|
||||
Sed finibus vel tortor ac egestas. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas vestibulum nulla mi, blandit efficitur sapien fermentum eu. Integer sed turpis eros. Phasellus sed aliquam ligula. Etiam dictum quam in dapibus mattis. Donec et tristique quam. Pellentesque gravida luctus dolor, eu ornare sapien. Donec justo ante, lacinia non sem et, ultricies dignissim nibh. Vivamus eu nisl et magna pulvinar efficitur. Sed at vehicula lectus, sit amet luctus sem. Morbi vehicula sapien nisi, nec sagittis orci vestibulum et.
|
||||
|
||||
Praesent non finibus diam. Quisque sit amet nisl vitae augue lobortis commodo. Morbi ullamcorper, tortor id ornare maximus, erat ipsum ullamcorper ipsum, in imperdiet diam sem vel erat. Sed pellentesque quis ex sed volutpat. Vestibulum volutpat diam ac dignissim sollicitudin. Praesent at luctus ex, at volutpat dui. Nunc nulla dui, lobortis et pharetra quis, efficitur in turpis. Donec sodales auctor purus id mollis. Sed auctor eu erat eget bibendum. Mauris tincidunt ornare neque id consequat. Suspendisse non massa ante. Quisque velit enim, rhoncus at erat eget, scelerisque placerat elit. Donec finibus luctus dolor. In sed eleifend lorem. Sed tempor ullamcorper lorem nec tristique. Fusce nec volutpat neque, id elementum est.
|
||||
|
||||
Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum mattis elementum tellus, vitae maximus nulla eleifend ut. Vestibulum eu nibh vulputate, posuere felis eget, aliquet ex. Nullam leo ex, lacinia a ante ac, accumsan efficitur ligula. Vestibulum ornare gravida tempus. Proin rhoncus felis sit amet dolor commodo facilisis. Integer aliquet, diam sed pharetra feugiat, sem massa mollis orci, eget pretium libero nunc at quam. Ut rhoncus quam vitae massa hendrerit, ornare condimentum odio varius. Donec odio sapien, tristique eget libero ac, interdum facilisis odio. Phasellus nec mauris vel dolor semper mattis et quis ligula. Donec nec porttitor nunc. Integer maximus quam vitae sem gravida, ut commodo ex porttitor.
|
||||
|
||||
Sed cursus nisi turpis, vel laoreet massa blandit ut. Cras posuere velit nulla, nec pellentesque ipsum dignissim eget. Donec pharetra, ex et commodo viverra, leo dolor dapibus tellus, vel dignissim est sem ac lectus. Quisque a arcu dapibus, aliquet magna sed, rhoncus neque. Integer suscipit, nulla ac varius lacinia, orci metus scelerisque neque, a laoreet nibh risus vitae dolor. Pellentesque felis metus, pulvinar vel cursus id, ultrices non purus. Donec mi lectus, faucibus sit amet nunc at, sagittis pretium lectus. Fusce nec purus arcu. Mauris neque neque, blandit eget mi at, auctor tempus orci. Mauris sapien lorem, luctus nec tellus non, porttitor aliquam dui.
|
||||
|
||||
Mauris non ex risus. Aliquam imperdiet in eros eget placerat. Sed congue sed sapien porta sollicitudin. Phasellus tempor hendrerit metus vitae tincidunt. Suspendisse congue nisi sed augue dapibus, at pretium ante mollis. Cras non posuere nulla. Proin malesuada finibus magna vel iaculis. Cras in dapibus lorem. Pellentesque volutpat dolor sit amet magna tincidunt mollis. Nunc et lectus sodales, accumsan est vitae, ornare augue. Maecenas malesuada arcu leo, eget blandit lectus porttitor et. Nam aliquam sapien sit amet purus consequat lobortis. Aenean varius, augue porta dignissim efficitur, felis velit dapibus leo, tincidunt ultricies magna felis id ligula. Duis hendrerit, lectus eu elementum euismod, elit lectus consequat mi, sit amet egestas justo massa ut urna. Proin eleifend interdum ultrices.
|
||||
|
||||
Donec lacinia orci pharetra ornare tincidunt. Nulla facilisi. Maecenas malesuada dui ac elit sagittis tincidunt id dictum dolor. Quisque lobortis purus ac metus volutpat viverra. Proin finibus sapien ut odio semper consectetur. Sed gravida luctus egestas. Mauris pretium volutpat elit, at commodo arcu sagittis nec. Ut condimentum fringilla urna ac dignissim. Cras aliquam metus pulvinar, pulvinar nibh at, placerat arcu. Nulla ornare tortor sed lectus mollis, vitae fringilla tellus egestas. Vivamus efficitur tincidunt sapien, sed finibus mi congue eu. Nullam magna velit, lacinia vitae ligula eget, molestie consectetur felis. Suspendisse varius turpis orci, ac laoreet arcu accumsan sed. Fusce quis fermentum lacus, nec varius libero. Pellentesque ac odio ut justo lobortis elementum sit amet vehicula lorem. Nulla interdum nulla eget mi tristique, vitae egestas nunc egestas.
|
||||
|
||||
Curabitur commodo libero eu elit tincidunt, quis placerat risus vehicula. Vestibulum vehicula id nunc iaculis fermentum. Aenean semper, tellus ac semper rutrum, justo lorem feugiat leo, quis vulputate neque dui non ligula. Etiam egestas, enim eget tempor porta, nunc est tristique ante, vel suscipit massa lorem vel diam. Donec faucibus ante id turpis rhoncus congue. Nullam laoreet, diam efficitur scelerisque consequat, ligula leo ultrices est, non fermentum elit mauris ut dolor. Morbi non porttitor lorem. Sed volutpat sapien et lorem porttitor, ultricies ultricies tellus congue. Mauris sodales, tortor nec sagittis finibus, dui odio aliquet nibh, in luctus sapien massa eu risus. Nulla in est sed ante molestie vehicula vel nec lectus. Fusce maximus a quam eget aliquam. Vivamus pulvinar quis nisi a maximus. Proin cursus lacus sapien, et hendrerit elit pretium a. Donec tellus lectus, consectetur id dolor a, luctus rutrum libero. Suspendisse auctor scelerisque dui, nec pellentesque felis viverra nec. Cras elit ex, varius sed pulvinar sed, suscipit ultrices lacus.
|
||||
|
||||
Vivamus eu luctus lectus. Maecenas congue magna orci, quis semper nulla blandit vel. Phasellus dignissim risus placerat lacinia sagittis. Praesent at gravida nisi, at pulvinar diam. Nulla egestas lectus sed felis facilisis egestas. Curabitur posuere gravida urna eu vestibulum. Pellentesque at dolor gravida, placerat quam sit amet, fermentum ligula. Morbi fringilla, mi eget mollis dictum, neque dolor ullamcorper leo, a rutrum libero ipsum eget orci. Curabitur consectetur iaculis vestibulum. Suspendisse ultricies ligula et neque lacinia luctus. Sed dignissim neque id eros sollicitudin pellentesque.
|
||||
|
||||
Donec et magna quis lectus pharetra finibus a fringilla sapien. Phasellus accumsan, erat eu sodales cursus, tortor elit dapibus risus, ut ornare neque arcu in tellus. Nam ac vehicula diam, at aliquam nisl. Cras in sem eget nisi ultrices rutrum sit amet eu velit. Sed molestie tellus eget ante scelerisque, sit amet pulvinar neque fringilla. Nunc volutpat facilisis egestas. Cras sodales dui ac massa egestas, in mattis leo rhoncus. Pellentesque vitae urna vehicula ipsum sodales suscipit. Sed commodo tempus fringilla.
|
||||
|
||||
Etiam egestas elit vitae mi maximus fringilla quis eget libero. Fusce finibus ultrices tellus at molestie. Pellentesque posuere blandit elementum. Etiam eu erat eu urna hendrerit euismod. Nulla quis lectus rhoncus, ultricies urna eget, pretium neque. Cras sit amet ipsum sit amet purus rutrum ultricies nec vitae tortor. Sed tempor dapibus augue in pulvinar. Ut pretium sapien in malesuada accumsan. Donec eget ultrices erat, ut efficitur ligula. Sed posuere mauris est, nec convallis ipsum tempus non.
|
||||
|
||||
Duis a ullamcorper ante. Quisque eu ultricies metus, at aliquet odio. Nullam tempus molestie augue ut varius. Fusce purus eros, dictum nec finibus sed, sodales et diam. Suspendisse sed mi purus. Donec eleifend ipsum diam, nec fringilla enim laoreet non. Phasellus condimentum, magna sit amet porttitor suscipit, arcu risus lobortis dolor, ac fringilla nibh nisl vel purus. Phasellus facilisis posuere orci sit amet tempus. Nam nec enim maximus, rhoncus felis a, rutrum diam.
|
||||
|
||||
Suspendisse potenti. Donec vel tempor neque. In aliquet nulla in eleifend bibendum. Sed sapien sem, finibus in sodales vitae, euismod in sem. Phasellus nec elit a erat pulvinar semper. Aliquam luctus nisl in libero molestie aliquam. Nunc ac ornare felis. Ut non mauris ut ipsum rhoncus pretium. Curabitur tristique lacus a sagittis aliquam. Morbi vel volutpat tellus. Maecenas volutpat, lacus sed tempus imperdiet, eros tellus volutpat nisi, a egestas augue nulla quis arcu. In sollicitudin imperdiet efficitur. Suspendisse viverra aliquet nisi, congue ultrices arcu hendrerit in.
|
||||
|
||||
Maecenas vitae vestibulum nunc. Nullam semper faucibus tincidunt. Etiam sed hendrerit risus. Proin gravida, urna nec tincidunt tempus, nulla sapien porttitor nibh, porttitor lobortis nunc quam et tortor. Praesent ut varius lacus, ut hendrerit enim. Ut nec turpis ac felis imperdiet bibendum. Phasellus porttitor enim odio, et vehicula mi convallis vel. Quisque porta scelerisque sagittis. Praesent dignissim sagittis vulputate. Aenean non justo ac est volutpat bibendum. Aliquam mattis, sapien dapibus pellentesque semper, velit urna malesuada diam, nec varius nibh eros at erat. Proin leo ante, ultricies id velit ut, faucibus porta nibh. Sed nec fermentum urna, sed mollis leo. Aliquam erat volutpat.
|
||||
|
||||
Donec condimentum, urna sed hendrerit vestibulum, ante nibh lacinia dui, in tincidunt odio sem eget orci. In hac habitasse platea dictumst. Mauris id ex id ante tempus finibus eu sagittis erat. Quisque interdum urna risus, vel varius nibh euismod non. Nulla eget pellentesque quam. Aliquam vestibulum ac tortor non lobortis. Sed vitae erat sed libero dignissim dictum nec in turpis. Vivamus id ornare elit, ut facilisis lectus. Morbi dictum purus eget ipsum dignissim porttitor. Sed at vehicula purus, nec rhoncus quam. Nunc a nisl quis arcu blandit fermentum vel quis odio. Vivamus rhoncus, sapien sed lacinia hendrerit, velit urna fermentum dolor, id feugiat magna ligula sed urna. Proin euismod efficitur libero, eget porttitor lacus tempus quis. Duis tincidunt quis est a laoreet. Nam sit amet tristique nisl, sit amet mattis mi.
|
||||
|
||||
Aenean id dictum nulla, sed laoreet magna. Morbi consectetur in turpis at aliquam. Maecenas rutrum feugiat metus, at ullamcorper augue fermentum ut. Vivamus in magna pretium nibh dictum rhoncus luctus at orci. In hac habitasse platea dictumst. Fusce convallis, nulla nec hendrerit suscipit, ipsum diam lobortis sem, vitae elementum lectus erat sit amet magna. Quisque sollicitudin fringilla purus, ac molestie justo congue vitae. Nulla sapien leo, ullamcorper ac tellus in, cursus rhoncus enim. Suspendisse rutrum magna non ex elementum elementum id vitae enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse ornare libero eu molestie pulvinar. Phasellus faucibus, magna eget rutrum porta, lorem turpis blandit lectus, eu viverra massa risus et ex.
|
||||
|
||||
Ut consectetur eros lacus, ac ullamcorper lacus mattis a. Cras congue justo ut erat interdum, et scelerisque nisi malesuada. Quisque sed sapien sollicitudin purus tincidunt finibus vestibulum vel dolor. Cras iaculis bibendum erat, a dictum urna viverra et. Integer non neque vulputate, tincidunt purus nec, rutrum arcu. Aliquam nec magna non sem semper laoreet quis at quam. Mauris dui lectus, convallis eu efficitur at, facilisis nec lorem. Cras felis sem, egestas ac rutrum vel, mollis et ex. Aenean semper egestas libero, nec commodo mi blandit efficitur. Duis nec quam in massa dignissim sagittis vel vitae leo. Nam molestie hendrerit auctor.
|
||||
|
||||
Sed suscipit egestas tellus sed cursus. Donec vel massa sit amet dui condimentum accumsan. Phasellus libero eros, lobortis a nisi id, porttitor maximus lectus. Praesent consectetur diam urna, id viverra turpis elementum in. Vivamus vitae pretium justo, nec tempor felis. Vivamus volutpat ultricies magna. Suspendisse vulputate lectus ac orci volutpat ullamcorper. Nulla eu leo pretium, commodo arcu accumsan, tempor nisl. Fusce sit amet tellus a ipsum vehicula laoreet sed vitae mauris. Duis porttitor massa mattis nibh placerat consequat. Fusce rutrum commodo tortor eget pellentesque. Suspendisse tempor enim libero, consequat dictum nibh dictum varius. Pellentesque feugiat sit amet urna sed facilisis. Curabitur a sagittis augue.
|
|
@ -0,0 +1,75 @@
|
|||
package com.baeldung.bufferedreader;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class BufferedReaderExampleUnitTest {
|
||||
|
||||
private static final String FILE_PATH = "src/main/resources/input.txt";
|
||||
|
||||
@Test
|
||||
public void givenBufferedReader_whenReadAllLines_thenReturnsContent() throws IOException {
|
||||
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
|
||||
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readAllLines(reader);
|
||||
|
||||
assertThat(content).isNotEmpty();
|
||||
assertThat(content).contains("Lorem ipsum");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBufferedReader_whenReadAllLinesWithStream_thenReturnsContent() throws IOException {
|
||||
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
|
||||
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readAllLinesWithStream(reader);
|
||||
|
||||
assertThat(content).isNotEmpty();
|
||||
assertThat(content).contains("Lorem ipsum");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadFile_thenReturnsContent() {
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readFile();
|
||||
|
||||
assertThat(content.toString()).contains("Lorem ipsum");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBufferedReader_whenReadAllCharsOneByOne_thenReturnsContent() throws IOException {
|
||||
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
|
||||
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readAllCharsOneByOne(reader);
|
||||
|
||||
assertThat(content).isNotEmpty();
|
||||
assertThat(content).contains("Lorem ipsum");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBufferedReader_whenReadMultipleChars_thenReturnsContent() throws IOException {
|
||||
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
|
||||
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readMultipleChars(reader);
|
||||
|
||||
assertThat(content).isNotEmpty();
|
||||
assertThat(content).isEqualTo("Lorem");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadFileTryWithResources_thenReturnsContent() {
|
||||
BufferedReaderExample bre = new BufferedReaderExample();
|
||||
String content = bre.readFileTryWithResources();
|
||||
|
||||
assertThat(content.toString()).contains("Lorem ipsum");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.bufferedreader;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class BufferedReaderUnitTest {
|
||||
|
||||
private static final String FILE_PATH = "src/main/resources/input.txt";
|
||||
|
||||
@Test
|
||||
public void givenBufferedReader_whenSkipUnderscores_thenOk() throws IOException {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(new StringReader("1__2__3__4__5"))) {
|
||||
int value;
|
||||
while((value = reader.read()) != -1) {
|
||||
result.append((char) value);
|
||||
reader.skip(2L);
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals("12345", result.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBufferedReader_whenSkipsWhitespacesAtBeginning_thenOk() throws IOException {
|
||||
String result;
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(new StringReader(" Lorem ipsum dolor sit amet."))) {
|
||||
do {
|
||||
reader.mark(1);
|
||||
} while(Character.isWhitespace(reader.read()));
|
||||
|
||||
reader.reset();
|
||||
result = reader.readLine();
|
||||
}
|
||||
|
||||
assertEquals("Lorem ipsum dolor sit amet.", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatesNewBufferedReader_thenOk() throws IOException {
|
||||
try(BufferedReader reader = Files.newBufferedReader(Paths.get(FILE_PATH))) {
|
||||
assertNotNull(reader);
|
||||
assertTrue(reader.ready());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -17,12 +17,9 @@
|
|||
- [Sorting in Java](http://www.baeldung.com/java-sorting)
|
||||
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
||||
- [Grep in Java](http://www.baeldung.com/grep-in-java)
|
||||
- [Simulated Annealing for Travelling Salesman Problem](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||
- [Slope One Algorithm: Collaborative Filtering Recommendation Systems](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
|
||||
- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding)
|
||||
- [The Basics of Java Generics](http://www.baeldung.com/java-generics)
|
||||
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
|
||||
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
|
||||
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
|
||||
|
@ -158,3 +155,6 @@
|
|||
- [Java Switch Statement](https://www.baeldung.com/java-switch)
|
||||
- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java)
|
||||
- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator)
|
||||
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
||||
- [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks)
|
||||
- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures)
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.abstractclasses.application;
|
||||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.StandardFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
|
||||
Application application = new Application();
|
||||
String filePath = application.getFilePathFromResourcesFolder("files/test.txt");
|
||||
|
||||
BaseFileReader lowercaseFileReader = new LowercaseFileReader(filePath);
|
||||
lowercaseFileReader.readFile().forEach(line -> System.out.println(line));
|
||||
|
||||
BaseFileReader upperCaseFileReader = new UppercaseFileReader(filePath);
|
||||
upperCaseFileReader.readFile().forEach(line -> System.out.println(line));
|
||||
|
||||
BaseFileReader standardFileReader = new StandardFileReader(filePath);
|
||||
standardFileReader.readFile().forEach(line -> System.out.println(line));
|
||||
|
||||
}
|
||||
|
||||
private String getFilePathFromResourcesFolder(String fileName) {
|
||||
return getClass().getClassLoader().getResource(fileName).getPath().substring(1);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.abstractclasses.filereaders;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class BaseFileReader {
|
||||
|
||||
protected String filePath;
|
||||
|
||||
protected BaseFileReader(String filePath) {
|
||||
this.filePath = filePath;
|
||||
}
|
||||
|
||||
public String getFilePath() {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public abstract List<String> readFile() throws IOException;
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.abstractclasses.filereaders;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class LowercaseFileReader extends BaseFileReader {
|
||||
|
||||
public LowercaseFileReader(String filePath) {
|
||||
super(filePath);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> readFile() throws IOException {
|
||||
return Files.lines(Paths.get(filePath))
|
||||
.map(String::toLowerCase)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.abstractclasses.filereaders;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StandardFileReader extends BaseFileReader {
|
||||
|
||||
public StandardFileReader(String filePath) {
|
||||
super(filePath);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> readFile() throws IOException {
|
||||
return Files.lines(Paths.get(filePath)).collect(Collectors.toList());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.abstractclasses.filereaders;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class UppercaseFileReader extends BaseFileReader {
|
||||
|
||||
public UppercaseFileReader(String filePath) {
|
||||
super(filePath);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> readFile() throws IOException {
|
||||
return Files.lines(Paths.get(filePath))
|
||||
.map(String::toUpperCase)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
|
@ -8,22 +8,26 @@ import java.net.Socket;
|
|||
import javax.net.SocketFactory;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.SSLParameters;
|
||||
|
||||
public class SimpleClient {
|
||||
static void startClient(String host, int port) throws IOException {
|
||||
static String startClient(String host, int port) throws IOException {
|
||||
SocketFactory factory = SSLSocketFactory.getDefault();
|
||||
|
||||
try (Socket connection = factory.createSocket(host, port)) {
|
||||
((SSLSocket) connection).setEnabledCipherSuites(
|
||||
new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"});
|
||||
((SSLSocket) connection).setEnabledProtocols(
|
||||
new String[] { "TLSv1.2"});
|
||||
BufferedReader input = new BufferedReader(
|
||||
new InputStreamReader(connection.getInputStream()));
|
||||
System.out.println(input.readLine());
|
||||
SSLParameters sslParams = new SSLParameters();
|
||||
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
|
||||
((SSLSocket) connection).setSSLParameters(sslParams);
|
||||
BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
return input.readLine();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
startClient("localhost", 1234);
|
||||
System.out.println(startClient("localhost", 8443));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,7 +4,6 @@ import java.io.IOException;
|
|||
import java.io.PrintWriter;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.util.Date;
|
||||
|
||||
import javax.net.ServerSocketFactory;
|
||||
import javax.net.ssl.SSLServerSocket;
|
||||
|
@ -13,6 +12,7 @@ import javax.net.ssl.SSLServerSocketFactory;
|
|||
public class SimpleServer {
|
||||
static void startServer(int port) throws IOException {
|
||||
ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
|
||||
|
||||
try (ServerSocket listener = factory.createServerSocket(port)) {
|
||||
((SSLServerSocket) listener).setNeedClientAuth(true);
|
||||
((SSLServerSocket) listener).setEnabledCipherSuites(
|
||||
|
@ -22,13 +22,13 @@ public class SimpleServer {
|
|||
while (true) {
|
||||
try (Socket socket = listener.accept()) {
|
||||
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
|
||||
out.println(new Date().toString());
|
||||
out.println("Hello World!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
startServer(1234);
|
||||
startServer(8443);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
This is line 1
|
||||
This is line 2
|
||||
This is line 3
|
||||
This is line 4
|
||||
This is line 5
|
||||
This is line 6
|
||||
This is line 7
|
||||
This is line 8
|
||||
This is line 9
|
||||
This is line 10
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.abstractclasses;
|
||||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LowercaseFileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLowercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
|
||||
String filePath = getClass().getClassLoader().getResource("files/test.txt").getPath().substring(1);
|
||||
BaseFileReader lowercaseFileReader = new LowercaseFileReader(filePath);
|
||||
|
||||
assertThat(lowercaseFileReader.readFile()).isInstanceOf(List.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.abstractclasses;
|
||||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.StandardFileReader;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StandardFileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStandardFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
|
||||
String filePath = getClass().getClassLoader().getResource("files/test.txt").getPath().substring(1);
|
||||
BaseFileReader standardFileReader = new StandardFileReader(filePath);
|
||||
|
||||
assertThat(standardFileReader.readFile()).isInstanceOf(List.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.abstractclasses;
|
||||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UppercaseFileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUppercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
|
||||
String filePath = getClass().getClassLoader().getResource("files/test.txt").getPath().substring(1);
|
||||
BaseFileReader uppercaseFileReader = new UppercaseFileReader(filePath);
|
||||
|
||||
assertThat(uppercaseFileReader.readFile()).isInstanceOf(List.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
package com.baeldung.properties;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MergePropertiesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoProperties_whenMergedUsingIteration_thenAllPropertiesInResult() {
|
||||
Properties globalProperties = mergePropertiesByIteratingKeySet(propertiesA(), propertiesB());
|
||||
|
||||
testMergedProperties(globalProperties);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoProperties_whenMergedUsingPutAll_thenAllPropertiesInResult() {
|
||||
Properties globalProperties = mergePropertiesByUsingPutAll(propertiesA(), propertiesB());
|
||||
|
||||
testMergedProperties(globalProperties);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoProperties_whenMergedUsingStreamAPI_thenAllPropertiesInResult() {
|
||||
Properties globalProperties = mergePropertiesByUsingStreamApi(propertiesB(), propertiesA());
|
||||
|
||||
testMergedProperties(globalProperties);
|
||||
}
|
||||
|
||||
private Properties mergePropertiesByIteratingKeySet(Properties... properties) {
|
||||
Properties mergedProperties = new Properties();
|
||||
for (Properties property : properties) {
|
||||
Set<String> propertyNames = property.stringPropertyNames();
|
||||
for (String name : propertyNames) {
|
||||
String propertyValue = property.getProperty(name);
|
||||
mergedProperties.setProperty(name, propertyValue);
|
||||
}
|
||||
}
|
||||
return mergedProperties;
|
||||
}
|
||||
|
||||
private Properties mergePropertiesByUsingPutAll(Properties... properties) {
|
||||
Properties mergedProperties = new Properties();
|
||||
for (Properties property : properties) {
|
||||
mergedProperties.putAll(property);
|
||||
}
|
||||
return mergedProperties;
|
||||
}
|
||||
|
||||
private Properties mergePropertiesByUsingStreamApi(Properties... properties) {
|
||||
return Stream.of(properties)
|
||||
.collect(Properties::new, Map::putAll, Map::putAll);
|
||||
}
|
||||
|
||||
private Properties propertiesA() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("application.name", "my-app");
|
||||
properties.setProperty("application.version", "1.0");
|
||||
return properties;
|
||||
}
|
||||
|
||||
private Properties propertiesB() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("property-1", "sample property");
|
||||
properties.setProperty("property-2", "another sample property");
|
||||
return properties;
|
||||
}
|
||||
|
||||
private void testMergedProperties(Properties globalProperties) {
|
||||
assertThat("There should be 4 properties", globalProperties.size(), equalTo(4));
|
||||
assertEquals("Property should be", globalProperties.getProperty("application.name"), "my-app");
|
||||
assertEquals("Property should be", globalProperties.getProperty("application.version"), "1.0");
|
||||
assertEquals("Property should be", globalProperties.getProperty("property-1"), "sample property");
|
||||
assertEquals("Property should be", globalProperties.getProperty("property-2"), "another sample property");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,91 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.6.RELEASE</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<groupId>com.baeldung.ddd</groupId>
|
||||
<artifactId>ddd</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>ddd</name>
|
||||
<description>DDD series examples</description>
|
||||
|
||||
<properties>
|
||||
<joda-money.version>1.0.1</joda-money.version>
|
||||
<maven-surefire-plugin.version>2.22.0</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-mongodb</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- JUnit platform launcher -->
|
||||
<!-- To be able to run tests from IDE directly -->
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-launcher</artifactId>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.joda</groupId>
|
||||
<artifactId>joda-money</artifactId>
|
||||
<version>${joda-money.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embed</groupId>
|
||||
<artifactId>de.flapdoodle.embed.mongo</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.ddd;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class PersistingDddAggregatesApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(PersistingDddAggregatesApplication.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.ddd.order;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.joda.money.Money;
|
||||
|
||||
public class Order {
|
||||
private final List<OrderLine> orderLines;
|
||||
private Money totalCost;
|
||||
|
||||
public Order(List<OrderLine> orderLines) {
|
||||
checkNotNull(orderLines);
|
||||
if (orderLines.isEmpty()) {
|
||||
throw new IllegalArgumentException("Order must have at least one order line item");
|
||||
}
|
||||
this.orderLines = new ArrayList<>(orderLines);
|
||||
totalCost = calculateTotalCost();
|
||||
}
|
||||
|
||||
public void addLineItem(OrderLine orderLine) {
|
||||
checkNotNull(orderLine);
|
||||
orderLines.add(orderLine);
|
||||
totalCost = totalCost.plus(orderLine.cost());
|
||||
}
|
||||
|
||||
public List<OrderLine> getOrderLines() {
|
||||
return new ArrayList<>(orderLines);
|
||||
}
|
||||
|
||||
public void removeLineItem(int line) {
|
||||
OrderLine removedLine = orderLines.remove(line);
|
||||
totalCost = totalCost.minus(removedLine.cost());
|
||||
}
|
||||
|
||||
public Money totalCost() {
|
||||
return totalCost;
|
||||
}
|
||||
|
||||
private Money calculateTotalCost() {
|
||||
return orderLines.stream()
|
||||
.map(OrderLine::cost)
|
||||
.reduce(Money::plus)
|
||||
.get();
|
||||
}
|
||||
|
||||
private static void checkNotNull(Object par) {
|
||||
if (par == null) {
|
||||
throw new NullPointerException("Parameter cannot be null");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.ddd.order;
|
||||
|
||||
import org.joda.money.Money;
|
||||
|
||||
public class OrderLine {
|
||||
private final Product product;
|
||||
private final int quantity;
|
||||
|
||||
public OrderLine(Product product, int quantity) {
|
||||
super();
|
||||
this.product = product;
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
OrderLine other = (OrderLine) obj;
|
||||
if (product == null) {
|
||||
if (other.product != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!product.equals(other.product)) {
|
||||
return false;
|
||||
}
|
||||
if (quantity != other.quantity) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((product == null) ? 0 : product.hashCode());
|
||||
result = prime * result + quantity;
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OrderLine [product=" + product + ", quantity=" + quantity + "]";
|
||||
}
|
||||
|
||||
Money cost() {
|
||||
return product.getPrice()
|
||||
.multipliedBy(quantity);
|
||||
}
|
||||
|
||||
Product getProduct() {
|
||||
return product;
|
||||
}
|
||||
|
||||
int getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.ddd.order;
|
||||
|
||||
import org.joda.money.Money;
|
||||
|
||||
public class Product {
|
||||
private final Money price;
|
||||
|
||||
public Product(Money price) {
|
||||
super();
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
Product other = (Product) obj;
|
||||
if (price == null) {
|
||||
if (other.price != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!price.equals(other.price)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((price == null) ? 0 : price.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Product [price=" + price + "]";
|
||||
}
|
||||
|
||||
Money getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
package com.baeldung.ddd.order.jpa;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.ElementCollection;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "order_table")
|
||||
class JpaOrder {
|
||||
private String currencyUnit;
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
@ElementCollection(fetch = FetchType.EAGER)
|
||||
private final List<JpaOrderLine> orderLines;
|
||||
private BigDecimal totalCost;
|
||||
|
||||
JpaOrder() {
|
||||
totalCost = null;
|
||||
orderLines = new ArrayList<>();
|
||||
}
|
||||
|
||||
JpaOrder(List<JpaOrderLine> orderLines) {
|
||||
checkNotNull(orderLines);
|
||||
if (orderLines.isEmpty()) {
|
||||
throw new IllegalArgumentException("Order must have at least one order line item");
|
||||
}
|
||||
this.orderLines = new ArrayList<>(orderLines);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
JpaOrder other = (JpaOrder) obj;
|
||||
if (id == null) {
|
||||
if (other.id != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!id.equals(other.id)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((id == null) ? 0 : id.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JpaOrder [currencyUnit=" + currencyUnit + ", id=" + id + ", orderLines=" + orderLines + ", totalCost=" + totalCost + "]";
|
||||
}
|
||||
|
||||
void addLineItem(JpaOrderLine orderLine) {
|
||||
checkNotNull(orderLine);
|
||||
orderLines.add(orderLine);
|
||||
}
|
||||
|
||||
String getCurrencyUnit() {
|
||||
return currencyUnit;
|
||||
}
|
||||
|
||||
Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
List<JpaOrderLine> getOrderLines() {
|
||||
return new ArrayList<>(orderLines);
|
||||
}
|
||||
|
||||
BigDecimal getTotalCost() {
|
||||
return totalCost;
|
||||
}
|
||||
|
||||
void removeLineItem(int line) {
|
||||
JpaOrderLine removedLine = orderLines.remove(line);
|
||||
}
|
||||
|
||||
void setCurrencyUnit(String currencyUnit) {
|
||||
this.currencyUnit = currencyUnit;
|
||||
}
|
||||
|
||||
void setTotalCost(BigDecimal totalCost) {
|
||||
this.totalCost = totalCost;
|
||||
}
|
||||
|
||||
private static void checkNotNull(Object par) {
|
||||
if (par == null) {
|
||||
throw new NullPointerException("Parameter cannot be null");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
package com.baeldung.ddd.order.jpa;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
import javax.persistence.Embedded;
|
||||
|
||||
@Embeddable
|
||||
class JpaOrderLine {
|
||||
@Embedded
|
||||
private final JpaProduct product;
|
||||
private final int quantity;
|
||||
|
||||
JpaOrderLine() {
|
||||
quantity = 0;
|
||||
product = null;
|
||||
}
|
||||
|
||||
JpaOrderLine(JpaProduct product, int quantity) {
|
||||
super();
|
||||
this.product = product;
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
JpaOrderLine other = (JpaOrderLine) obj;
|
||||
if (product == null) {
|
||||
if (other.product != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!product.equals(other.product)) {
|
||||
return false;
|
||||
}
|
||||
if (quantity != other.quantity) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((product == null) ? 0 : product.hashCode());
|
||||
result = prime * result + quantity;
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JpaOrderLine [product=" + product + ", quantity=" + quantity + "]";
|
||||
}
|
||||
|
||||
JpaProduct getProduct() {
|
||||
return product;
|
||||
}
|
||||
|
||||
int getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.ddd.order.jpa;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface JpaOrderRepository extends JpaRepository<JpaOrder, Long> {
|
||||
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
package com.baeldung.ddd.order.jpa;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
class JpaProduct {
|
||||
private String currencyUnit;
|
||||
private BigDecimal price;
|
||||
|
||||
public JpaProduct() {
|
||||
}
|
||||
|
||||
public JpaProduct(BigDecimal price, String currencyUnit) {
|
||||
super();
|
||||
this.price = price;
|
||||
currencyUnit = currencyUnit;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
JpaProduct other = (JpaProduct) obj;
|
||||
if (currencyUnit == null) {
|
||||
if (other.currencyUnit != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!currencyUnit.equals(other.currencyUnit)) {
|
||||
return false;
|
||||
}
|
||||
if (price == null) {
|
||||
if (other.price != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!price.equals(other.price)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getCurrencyUnit() {
|
||||
return currencyUnit;
|
||||
}
|
||||
|
||||
public BigDecimal getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((currencyUnit == null) ? 0 : currencyUnit.hashCode());
|
||||
result = prime * result + ((price == null) ? 0 : price.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
public void setCurrencyUnit(String currencyUnit) {
|
||||
this.currencyUnit = currencyUnit;
|
||||
}
|
||||
|
||||
public void setPrice(BigDecimal price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JpaProduct [currencyUnit=" + currencyUnit + ", price=" + price + "]";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.ddd.order.mongo;
|
||||
|
||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
|
||||
import com.baeldung.ddd.order.Order;
|
||||
|
||||
public interface OrderMongoRepository extends MongoRepository<Order, String> {
|
||||
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
package com.baeldung.ddd.order;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.joda.money.CurrencyUnit;
|
||||
import org.joda.money.Money;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class OrderTest {
|
||||
@DisplayName("given order with two items, when calculate total cost, then sum is returned")
|
||||
@Test
|
||||
void test0() throws Exception {
|
||||
// given
|
||||
OrderLine ol0 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 10.00)), 2);
|
||||
OrderLine ol1 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 5.00)), 10);
|
||||
Order order = new Order(Arrays.asList(ol0, ol1));
|
||||
|
||||
// when
|
||||
Money totalCost = order.totalCost();
|
||||
|
||||
// then
|
||||
assertThat(totalCost).isEqualTo(Money.of(CurrencyUnit.USD, 70.00));
|
||||
}
|
||||
|
||||
@DisplayName("when create order without line items, then exception is thrown")
|
||||
@Test
|
||||
void test1() throws Exception {
|
||||
// when
|
||||
Throwable throwable = catchThrowable(() -> new Order(new ArrayList<>()));
|
||||
|
||||
// then
|
||||
assertThat(throwable).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@DisplayName("given order with two line items, when add another line item, then total cost is updated")
|
||||
@Test
|
||||
void test2() throws Exception {
|
||||
// given
|
||||
OrderLine ol0 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 10.00)), 1);
|
||||
OrderLine ol1 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 5.00)), 1);
|
||||
Order order = new Order(Arrays.asList(ol0, ol1));
|
||||
|
||||
// when
|
||||
order.addLineItem(new OrderLine(new Product(Money.of(CurrencyUnit.USD, 20.00)), 2));
|
||||
|
||||
// then
|
||||
assertThat(order.totalCost()).isEqualTo(Money.of(CurrencyUnit.USD, 55));
|
||||
}
|
||||
|
||||
@DisplayName("given order with three line items, when remove item, then total cost is updated")
|
||||
@Test
|
||||
void test3() throws Exception {
|
||||
// given
|
||||
OrderLine ol0 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 10.00)), 1);
|
||||
OrderLine ol1 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 20.00)), 1);
|
||||
OrderLine ol2 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 30.00)), 1);
|
||||
Order order = new Order(Arrays.asList(ol0, ol1, ol2));
|
||||
|
||||
// when
|
||||
order.removeLineItem(1);
|
||||
|
||||
// then
|
||||
assertThat(order.totalCost()).isEqualTo(Money.of(CurrencyUnit.USD, 40.00));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.ddd.order.jpa;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
|
||||
|
||||
@SpringJUnitConfig
|
||||
@SpringBootTest
|
||||
public class PersistOrderIntegrationTest {
|
||||
@Autowired
|
||||
private JpaOrderRepository repository;
|
||||
|
||||
@DisplayName("given order with two line items, when persist, then order is saved")
|
||||
@Test
|
||||
public void test() throws Exception {
|
||||
// given
|
||||
JpaOrder order = prepareTestOrderWithTwoLineItems();
|
||||
|
||||
// when
|
||||
JpaOrder savedOrder = repository.save(order);
|
||||
|
||||
// then
|
||||
JpaOrder foundOrder = repository.findById(savedOrder.getId())
|
||||
.get();
|
||||
assertThat(foundOrder.getOrderLines()).hasSize(2);
|
||||
}
|
||||
|
||||
private JpaOrder prepareTestOrderWithTwoLineItems() {
|
||||
JpaOrderLine ol0 = new JpaOrderLine(new JpaProduct(BigDecimal.valueOf(10.00), "USD"), 2);
|
||||
JpaOrderLine ol1 = new JpaOrderLine(new JpaProduct(BigDecimal.valueOf(5.00), "USD"), 10);
|
||||
return new JpaOrder(Arrays.asList(ol0, ol1));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.ddd.order.jpa;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ViolateOrderBusinessRulesTest {
|
||||
@DisplayName("given two non-zero order line items, when create an order with them, it's possible to set total cost to zero")
|
||||
@Test
|
||||
void test() throws Exception {
|
||||
// given
|
||||
// available products
|
||||
JpaProduct lungChingTea = new JpaProduct(BigDecimal.valueOf(10.00), "USD");
|
||||
JpaProduct gyokuroMiyazakiTea = new JpaProduct(BigDecimal.valueOf(20.00), "USD");
|
||||
// Lung Ching tea order line
|
||||
JpaOrderLine orderLine0 = new JpaOrderLine(lungChingTea, 2);
|
||||
// Gyokuro Miyazaki tea order line
|
||||
JpaOrderLine orderLine1 = new JpaOrderLine(gyokuroMiyazakiTea, 3);
|
||||
|
||||
// when
|
||||
// create the order
|
||||
JpaOrder order = new JpaOrder();
|
||||
order.addLineItem(orderLine0);
|
||||
order.addLineItem(orderLine1);
|
||||
order.setTotalCost(BigDecimal.ZERO);
|
||||
order.setCurrencyUnit("USD");
|
||||
|
||||
// then
|
||||
// this doesn't look good...
|
||||
assertThat(order.getTotalCost()).isEqualTo(BigDecimal.ZERO);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue