Merge branch 'master' of github.com:eugenp/tutorials
This commit is contained in:
commit
852762f014
|
@ -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));
|
|
@ -4,4 +4,4 @@
|
|||
- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort)
|
||||
- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort)
|
||||
- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort)
|
||||
|
||||
- [Heap Sort in Java](https://www.baeldung.com/java-heap-sort)
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Apache Pulsar](https://www.baeldung.com/apache-pulsar)
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,15 @@
|
|||
=========
|
||||
|
||||
## Core Java Arrays Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
|
||||
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
|
||||
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
|
||||
- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays)
|
||||
- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
|
||||
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
|
||||
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
|
||||
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
|
||||
- [Array Operations in Java](http://www.baeldung.com/java-common-array-operations)
|
||||
|
|
@ -0,0 +1,412 @@
|
|||
<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>core-java-arrays</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-arrays</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator-annprocess.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${springframework.spring-web.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-arrays</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*IntTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>${maven-jar-plugin.version}</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${maven-shade-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<version>${onejar-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>one-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<configuration>
|
||||
<executable>java</executable>
|
||||
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||
<arguments>
|
||||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>${maven-javadoc-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
<include>**/*IntTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>run-benchmarks</id>
|
||||
<!-- <phase>integration-test</phase> -->
|
||||
<phase>none</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classpathScope>test</classpathScope>
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<!-- java instrumentation profiles to build jars -->
|
||||
<profile>
|
||||
<id>buildAgentLoader</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>agentLoader</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/application/AgentLoader.class</include>
|
||||
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>buildApplication</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>application</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/application/MyAtm.class</include>
|
||||
<include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
|
||||
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>buildAgent</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>agent</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
|
||||
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
|
||||
<jmh-core.version>1.19</jmh-core.version>
|
||||
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
|
||||
<!-- maven and spring plugins -->
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
|
||||
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
||||
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -2,7 +2,7 @@ package com.baeldung.array;
|
|||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.commons.lang.ArrayUtils;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
public class ArrayInitializer {
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -39,3 +39,7 @@
|
|||
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
|
||||
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
|
||||
- [Removing Elements from Java Collections](https://www.baeldung.com/java-collection-remove-elements)
|
||||
- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist)
|
||||
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
|
||||
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
|
||||
|
|
|
@ -61,7 +61,7 @@
|
|||
<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>
|
||||
|
|
|
@ -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,75 @@
|
|||
package com.baeldung.concurrent.evenandodd;
|
||||
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
public class PrintEvenOddSemaphore {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SharedPrinter sp = new SharedPrinter();
|
||||
Thread odd = new Thread(new Odd(sp, 10), "Odd");
|
||||
Thread even = new Thread(new Even(sp, 10), "Even");
|
||||
|
||||
odd.start();
|
||||
even.start();
|
||||
}
|
||||
}
|
||||
|
||||
class SharedPrinter {
|
||||
|
||||
private final Semaphore semEven = new Semaphore(0);
|
||||
private final Semaphore semOdd = new Semaphore(1);
|
||||
|
||||
void printEvenNum(int num) {
|
||||
try {
|
||||
semEven.acquire();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
System.out.println(Thread.currentThread().getName() + ":"+num);
|
||||
semOdd.release();
|
||||
}
|
||||
|
||||
void printOddNum(int num) {
|
||||
try {
|
||||
semOdd.acquire();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
System.out.println(Thread.currentThread().getName() + ":"+ num);
|
||||
semEven.release();
|
||||
}
|
||||
}
|
||||
|
||||
class Even implements Runnable {
|
||||
private final SharedPrinter sp;
|
||||
private final 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 {
|
||||
private SharedPrinter sp;
|
||||
private 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,68 @@
|
|||
package com.baeldung.concurrent.evenandodd;
|
||||
|
||||
public class PrintEvenOddWaitNotify {
|
||||
|
||||
public static void main(String... args) {
|
||||
Printer print = new Printer();
|
||||
Thread t1 = new Thread(new TaskEvenOdd(print, 10, false), "Odd");
|
||||
Thread t2 = new Thread(new TaskEvenOdd(print, 10, true), "Even");
|
||||
t1.start();
|
||||
t2.start();
|
||||
}
|
||||
}
|
||||
|
||||
class TaskEvenOdd implements Runnable {
|
||||
private final int max;
|
||||
private final Printer print;
|
||||
private final 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 ? 2 : 1;
|
||||
while (number <= max) {
|
||||
if (isEvenNumber) {
|
||||
print.printEven(number);
|
||||
} else {
|
||||
print.printOdd(number);
|
||||
}
|
||||
number += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Printer {
|
||||
private volatile boolean isOdd;
|
||||
|
||||
synchronized void printEven(int number) {
|
||||
while (!isOdd) {
|
||||
try {
|
||||
wait();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
System.out.println(Thread.currentThread().getName() + ":" + number);
|
||||
isOdd = false;
|
||||
notify();
|
||||
}
|
||||
|
||||
synchronized void printOdd(int number) {
|
||||
while (isOdd) {
|
||||
try {
|
||||
wait();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
System.out.println(Thread.currentThread().getName() + ":" + number);
|
||||
isOdd = true;
|
||||
notify();
|
||||
}
|
||||
|
||||
}
|
|
@ -33,3 +33,4 @@
|
|||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
|
||||
- [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream)
|
||||
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,59 @@
|
|||
=========
|
||||
|
||||
## Core Java Lang Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||
- [Introduction to Java Generics](http://www.baeldung.com/java-generics)
|
||||
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
|
||||
- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions)
|
||||
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
|
||||
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
|
||||
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
|
||||
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
|
||||
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
|
||||
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
|
||||
- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode)
|
||||
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
|
||||
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
|
||||
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
|
||||
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
|
||||
- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization)
|
||||
- [Nested Classes in Java](http://www.baeldung.com/java-nested-classes)
|
||||
- [A Guide to Java Loops](http://www.baeldung.com/java-loops)
|
||||
- [Varargs in Java](http://www.baeldung.com/java-varargs)
|
||||
- [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces)
|
||||
- [Polymorphism in Java](http://www.baeldung.com/java-polymorphism)
|
||||
- [Recursion In Java](http://www.baeldung.com/java-recursion)
|
||||
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
|
||||
- [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override)
|
||||
- [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy)
|
||||
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
|
||||
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
|
||||
- [The "final" Keyword in Java](http://www.baeldung.com/java-final)
|
||||
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
|
||||
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
|
||||
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
|
||||
- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
|
||||
- [Using Java Assertions](http://www.baeldung.com/java-assert)
|
||||
- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
|
||||
- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding)
|
||||
- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers)
|
||||
- [Guide to the super Java Keyword](http://www.baeldung.com/java-super)
|
||||
- [Guide to the this Java Keyword](http://www.baeldung.com/java-this)
|
||||
- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object)
|
||||
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
|
||||
- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
|
||||
- [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception)
|
||||
- [Exception Handling in Java](http://www.baeldung.com/java-exceptions)
|
||||
- [Differences Between Final, Finally and Finalize in Java](https://www.baeldung.com/java-final-finally-finalize)
|
||||
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
|
||||
- [Difference Between Throw and Throws in Java](https://www.baeldung.com/java-throw-throws)
|
||||
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
|
||||
- [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)
|
||||
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
|
||||
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
|
||||
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
|
||||
|
|
@ -0,0 +1,429 @@
|
|||
<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>core-java-lang</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-lang</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
<!-- marshalling -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${springframework.spring-web.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.mail</groupId>
|
||||
<artifactId>mail</artifactId>
|
||||
<version>${javax.mail.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-lang</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*IntTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>${maven-jar-plugin.version}</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${maven-shade-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<version>${onejar-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>one-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<configuration>
|
||||
<executable>java</executable>
|
||||
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||
<arguments>
|
||||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>${maven-javadoc-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
<include>**/*IntTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>run-benchmarks</id>
|
||||
<!-- <phase>integration-test</phase> -->
|
||||
<phase>none</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classpathScope>test</classpathScope>
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<!-- java instrumentation profiles to build jars -->
|
||||
<profile>
|
||||
<id>buildAgentLoader</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>agentLoader</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/application/AgentLoader.class</include>
|
||||
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>buildApplication</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>application</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/application/MyAtm.class</include>
|
||||
<include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
|
||||
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>buildAgent</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>agent</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
|
||||
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
|
||||
<javax.mail.version>1.5.0-b01</javax.mail.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
|
||||
<!-- maven and spring plugins -->
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
|
||||
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
||||
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue