Merge pull request #2 from eugenp/master

Rebase
This commit is contained in:
Krzysztof Majewski 2020-11-18 13:11:04 +01:00 committed by GitHub
commit c5d164a30d
655 changed files with 11980 additions and 1547 deletions

View File

@ -1,5 +1,3 @@
**UPDATE**: The price of "Learn Spring Security OAuth" will permanently change on the 11th of December, along with the upcoming OAuth2 material: http://bit.ly/github-lss
The Courses
==============================

View File

@ -5,6 +5,6 @@ This module contains articles about genetic algorithms.
### Relevant articles:
- [Introduction to Jenetics Library](https://www.baeldung.com/jenetics)
- [Ant Colony Optimization](https://www.baeldung.com/java-ant-colony-optimization)
- [Ant Colony Optimization with a Java Example](https://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)

View File

@ -6,8 +6,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
### Relevant articles:
- [Validating Input With Finite Automata in Java](https://www.baeldung.com/java-finite-automata)
- [Example of Hill Climbing Algorithm](https://www.baeldung.com/java-hill-climbing-algorithm)
- [Introduction to Minimax Algorithm](https://www.baeldung.com/java-minimax-algorithm)
- [Example of Hill Climbing Algorithm in Java](https://www.baeldung.com/java-hill-climbing-algorithm)
- [Introduction to Minimax Algorithm with a Java Implementation](https://www.baeldung.com/java-minimax-algorithm)
- [How to Calculate Levenshtein Distance in Java?](https://www.baeldung.com/java-levenshtein-distance)
- [How to Find the Kth Largest Element in Java](https://www.baeldung.com/java-kth-largest-element)
- More articles: [[next -->]](/../algorithms-miscellaneous-2)
- More articles: [[next -->]](/algorithms-miscellaneous-2)

View File

@ -14,4 +14,4 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Displaying Money Amounts in Words](https://www.baeldung.com/java-money-into-words)
- [A Collaborative Filtering Recommendation System in Java](https://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Implementing A* Pathfinding in Java](https://www.baeldung.com/java-a-star-pathfinding)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-1) [[next -->]](/../algorithms-miscellaneous-3)
- More articles: [[<-- prev]](/algorithms-miscellaneous-1) [[next -->]](/algorithms-miscellaneous-3)

View File

@ -5,8 +5,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
### Relevant articles:
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm)
- [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](https://www.baeldung.com/java-linked-list-middle-element)
- [Check If a String Contains All The Letters of The Alphabet with Java](https://www.baeldung.com/java-string-contains-all-letters)
- [Find the Middle Element of a Linked List in Java](https://www.baeldung.com/java-linked-list-middle-element)
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)

View File

@ -9,11 +9,11 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
- [How to Determine if a Binary Tree is Balanced](https://www.baeldung.com/java-balanced-binary-tree)
- [How to Determine if a Binary Tree is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree)
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
- [Prims Algorithm](https://www.baeldung.com/java-prim-algorithm)
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays)
- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4) [[next -->]](/../algorithms-miscellaneous-6)
- [Prims Algorithm with a Java Implementation](https://www.baeldung.com/java-prim-algorithm)
- [Maximum Subarray Problem in Java](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays in Java](https://www.baeldung.com/java-merge-sorted-arrays)
- [Median of Stream of Integers using Heap in Java](https://www.baeldung.com/java-stream-integers-median-using-heap)
- More articles: [[<-- prev]](/algorithms-miscellaneous-4) [[next -->]](/algorithms-miscellaneous-6)

View File

@ -1,12 +1,13 @@
### Relevant Articles:
- [Boruvkas Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm)
- [Boruvkas Algorithm for Minimum Spanning Trees in Java](https://www.baeldung.com/java-boruvka-algorithm)
- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent)
- [Kruskals Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal)
- [Kruskals Algorithm for Spanning Trees with a Java Implementation](https://www.baeldung.com/java-spanning-trees-kruskal)
- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm)
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5)
- [Finding Top K Elements in a Java Array](https://www.baeldung.com/java-array-top-elements)
- [Reversing a Linked List in Java](https://www.baeldung.com/java-reverse-linked-list)
- More articles: [[<-- prev]](/algorithms-miscellaneous-5)

View File

@ -8,8 +8,8 @@ This module contains articles about searching algorithms.
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search)
- [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
- [String Search Algorithms for Large Texts with Java](https://www.baeldung.com/java-full-text-search-algorithms)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game in Java](https://www.baeldung.com/java-monte-carlo-tree-search)
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
- [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree)
- [Find the Kth Smallest Element in Two Sorted Arrays](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)
- [Fast Pattern Matching of Strings Using Suffix Tree in Java](https://www.baeldung.com/java-pattern-matching-suffix-tree)
- [Find the Kth Smallest Element in Two Sorted Arrays in Java](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)

View File

@ -2,6 +2,6 @@
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting)
- [Partitioning and Sorting Arrays with Many Repeated Entries](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
- [Guide to In-Place Sorting Algorithm Works with a Java Implementation](https://www.baeldung.com/java-in-place-sorting)
- [Partitioning and Sorting Arrays with Many Repeated Entries with Java Examples](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
- More articles: [[<-- prev]](/algorithms-sorting)

View File

@ -129,6 +129,11 @@
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>

View File

@ -8,3 +8,4 @@ This module contains articles about Apache Spark
- [Building a Data Pipeline with Kafka, Spark Streaming and Cassandra](https://www.baeldung.com/kafka-spark-data-pipeline)
- [Machine Learning with Spark MLlib](https://www.baeldung.com/spark-mlib-machine-learning)
- [Introduction to Spark Graph Processing with GraphFrames](https://www.baeldung.com/spark-graph-graphframes)
- [Apache Spark: Differences between Dataframes, Datasets and RDDs](https://www.baeldung.com/java-spark-dataframe-dataset-rdd)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,75 @@
package com.baeldung.differences.dataframe.dataset.rdd;
public class TouristData {
private String region;
private String country;
private String year;
private String series;
private Double value;
private String footnotes;
private String source;
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public String getFootnotes() {
return footnotes;
}
public void setFootnotes(String footnotes) {
this.footnotes = footnotes;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
@Override
public String toString() {
return "TouristData [region=" + region + ", country=" + country + ", year=" + year + ", series=" + series + ", value=" + value + ", footnotes=" + footnotes + ", source=" + source + "]";
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.differences.rdd;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import scala.Tuple2;
public class ActionsUnitTest {
private static JavaRDD<String> tourists;
private static JavaSparkContext sc;
public static final String COMMA_DELIMITER = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
@BeforeClass
public static void init() {
SparkConf conf = new SparkConf().setAppName("reduce")
.setMaster("local[*]");
sc = new JavaSparkContext(conf);
tourists = sc.textFile("data/Tourist.csv").filter(line -> !line.startsWith("Region"));
}
@AfterClass
public static void cleanup() {
sc.close();
}
@Test
public void whenDistinctCount_thenReturnDistinctNumRecords() {
JavaRDD<String> countries = tourists.map(line -> {
String[] columns = line.split(COMMA_DELIMITER);
return columns[1];
})
.distinct();
Long numberOfCountries = countries.count();
System.out.println("Count: " + numberOfCountries);
assertEquals(Long.valueOf(220), numberOfCountries);
}
@Test
public void whenReduceByKeySum_thenTotalValuePerKey() {
JavaRDD<String> touristsExpenditure = tourists.filter(line -> line.split(COMMA_DELIMITER)[3].contains("expenditure"));
JavaPairRDD<String, Double> expenditurePairRdd = touristsExpenditure.mapToPair(line -> {
String[] columns = line.split(COMMA_DELIMITER);
return new Tuple2<>(columns[1], Double.valueOf(columns[6]));
});
List<Tuple2<String, Double>> totalByCountry = expenditurePairRdd.reduceByKey((x, y) -> x + y)
.collect();
System.out.println("Total per Country: " + totalByCountry);
for(Tuple2<String, Double> tuple : totalByCountry) {
if (tuple._1.equals("Mexico")) {
assertEquals(Double.valueOf(99164), tuple._2);
}
}
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.differences.rdd;
import static org.apache.spark.sql.functions.col;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.apache.spark.sql.DataFrameReader;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class DataFrameUnitTest {
private static SparkSession session;
private static Dataset<Row> data;
@BeforeClass
public static void init() {
session = SparkSession.builder()
.appName("TouristDataFrameExample")
.master("local[*]")
.getOrCreate();
DataFrameReader dataFrameReader = session.read();
data = dataFrameReader.option("header", "true")
.csv("data/Tourist.csv");
}
@AfterClass
public static void cleanup() {
session.stop();
}
@Test
public void whenSelectSpecificColumns_thenColumnsFiltered() {
Dataset<Row> selectedData = data.select(col("country"), col("year"), col("value"));
selectedData.show();
List<String> resultList = Arrays.asList(selectedData.columns());
assertTrue(resultList.contains("country"));
assertTrue(resultList.contains("year"));
assertTrue(resultList.contains("value"));
assertFalse(resultList.contains("Series"));
}
@Test
public void whenFilteringByCountry_thenCountryRecordsSelected() {
Dataset<Row> filteredData = data.filter(col("country").equalTo("Mexico"));
filteredData.show();
filteredData.foreach(record -> {
assertEquals("Mexico", record.get(1));
});
}
@Test
public void whenGroupCountByCountry_thenContryTotalRecords() {
Dataset<Row> recordsPerCountry = data.groupBy(col("country"))
.count();
recordsPerCountry.show();
Dataset<Row> filteredData = recordsPerCountry.filter(col("country").equalTo("Sweden"));
assertEquals(new Long(12), filteredData.first()
.get(1));
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.differences.rdd;
import static org.apache.spark.sql.functions.col;
import static org.apache.spark.sql.functions.sum;
import static org.junit.Assert.assertEquals;
import org.apache.spark.api.java.function.FilterFunction;
import org.apache.spark.sql.DataFrameReader;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.differences.dataframe.dataset.rdd.TouristData;
public class DatasetUnitTest {
private static SparkSession session;
private static Dataset<TouristData> typedDataset;
@BeforeClass
public static void init() {
session = SparkSession.builder()
.appName("TouristDatasetExample")
.master("local[*]")
.getOrCreate();
DataFrameReader dataFrameReader = session.read();
Dataset<Row> data = dataFrameReader.option("header", "true")
.csv("data/Tourist.csv");
Dataset<Row> responseWithSelectedColumns = data.select(col("region"),
col("country"), col("year"), col("series"), col("value").cast("double"),
col("footnotes"), col("source"));
typedDataset = responseWithSelectedColumns.as(Encoders.bean(TouristData.class));
}
@AfterClass
public static void cleanup() {
session.stop();
}
@Test
public void whenFilteringByCountry_thenCountryRecordsSelected() {
Dataset<TouristData> selectedData = typedDataset
.filter((FilterFunction<TouristData>) record -> record.getCountry()
.equals("Norway"));
selectedData.show();
selectedData.foreach(record -> {
assertEquals("Norway", record.getCountry());
});
}
@Test
public void whenGroupCountByCountry_thenContryTotalRecords() {
Dataset<Row> countriesCount = typedDataset.groupBy(typedDataset.col("country"))
.count();
countriesCount.show();
assertEquals(Long.valueOf(220), Long.valueOf(countriesCount.count()));
}
@Test
public void whenFilteredByPropertyRange_thenRetreiveValidRecords() {
// Filter records with existing data for years between 2010 and 2017
typedDataset.filter((FilterFunction<TouristData>) record -> record.getYear() != null
&& (Long.valueOf(record.getYear()) > 2010 && Long.valueOf(record.getYear()) < 2017))
.show();
}
@Test
public void whenSumValue_thenRetreiveTotalValue() {
// Total tourist expenditure by country
typedDataset.filter((FilterFunction<TouristData>) record -> record.getValue() != null
&& record.getSeries()
.contains("expenditure"))
.groupBy("country")
.agg(sum("value"))
.show();
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.differences.rdd;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class TransformationsUnitTest {
public static final String COMMA_DELIMITER = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
private static JavaSparkContext sc;
private static JavaRDD<String> tourists;
@BeforeClass
public static void init() {
SparkConf conf = new SparkConf().setAppName("uppercaseCountries")
.setMaster("local[*]");
sc = new JavaSparkContext(conf);
tourists = sc.textFile("data/Tourist.csv")
.filter(line -> !line.startsWith("Region")); //filter header row
}
@AfterClass
public static void cleanup() {
sc.close();
}
@Test
public void whenMapUpperCase_thenCountryNameUppercased() {
JavaRDD<String> upperCaseCountries = tourists.map(line -> {
String[] columns = line.split(COMMA_DELIMITER);
return columns[1].toUpperCase();
})
.distinct();
upperCaseCountries.saveAsTextFile("data/output/uppercase.txt");
upperCaseCountries.foreach(country -> {
//replace non alphanumerical characters
country = country.replaceAll("[^a-zA-Z]", "");
assertTrue(StringUtils.isAllUpperCase(country));
});
}
@Test
public void whenFilterByCountry_thenShowRequestedCountryRecords() {
JavaRDD<String> touristsInMexico = tourists.filter(line -> line.split(COMMA_DELIMITER)[1].equals("Mexico"));
touristsInMexico.saveAsTextFile("data/output/touristInMexico.txt");
touristsInMexico.foreach(record -> {
assertEquals("Mexico", record.split(COMMA_DELIMITER)[1]);
});
}
}

View File

@ -10,3 +10,4 @@ This module contains articles about Java 10 core features
- [Deep Dive Into the New Java JIT Compiler Graal](https://www.baeldung.com/graal-java-jit-compiler)
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)
- [Converting between a List and a Set in Java](https://www.baeldung.com/convert-list-to-set-and-set-to-list)
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)

View File

@ -0,0 +1,30 @@
package com.baeldung.java14.character;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class IsLetterOrAlphabetUnitTest {
@Test
public void givenACharacter_whenLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isLetter(65));
}
@Test
public void givenACharacter_whenLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic(65));
}
@Test
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsLetterFalse() {
assertFalse(Character.isLetter(837));
}
@Test
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic(837));
}
}

View File

@ -0,0 +1 @@
--enable-preview

View File

@ -0,0 +1,7 @@
## Core Java 15
This module contains articles about Java 15.
### Relevant articles
- TODO: add article links here

View File

@ -0,0 +1,77 @@
<?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>core-java-15</artifactId>
<name>core-java-15</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache-commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>
<source>15</source>
<target>15</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.release>15</maven.compiler.release>
<apache-commons-lang3.version>3.11</apache-commons-lang3.version>
<assertj.version>3.17.2</assertj.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
</properties>
</project>

View File

@ -0,0 +1,49 @@
package com.baeldung.sealed.alternative;
public class Vehicles {
abstract static class Vehicle {
private final String registrationNumber;
public Vehicle(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
public static final class Car extends Vehicle {
private final int numberOfSeats;
public Car(int numberOfSeats, String registrationNumber) {
super(registrationNumber);
this.numberOfSeats = numberOfSeats;
}
public int getNumberOfSeats() {
return numberOfSeats;
}
}
public static final class Truck extends Vehicle {
private final int loadCapacity;
public Truck(int loadCapacity, String registrationNumber) {
super(registrationNumber);
this.loadCapacity = loadCapacity;
}
public int getLoadCapacity() {
return loadCapacity;
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.sealed.classes;
public non-sealed class Car extends Vehicle implements Service {
private final int numberOfSeats;
public Car(int numberOfSeats, String registrationNumber) {
super(registrationNumber);
this.numberOfSeats = numberOfSeats;
}
public int getNumberOfSeats() {
return numberOfSeats;
}
@Override
public int getMaxServiceIntervalInMonths() {
return 12;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.sealed.classes;
public sealed interface Service permits Car, Truck {
int getMaxServiceIntervalInMonths();
default int getMaxDistanceBetweenServicesInKilometers() {
return 100000;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.sealed.classes;
public final class Truck extends Vehicle implements Service {
private final int loadCapacity;
public Truck(int loadCapacity, String registrationNumber) {
super(registrationNumber);
this.loadCapacity = loadCapacity;
}
public int getLoadCapacity() {
return loadCapacity;
}
@Override
public int getMaxServiceIntervalInMonths() {
return 18;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.sealed.classes;
public abstract sealed class Vehicle permits Car, Truck {
protected final String registrationNumber;
public Vehicle(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.sealed.records;
public record Car(int numberOfSeats, String registrationNumber) implements Vehicle {
@Override
public String getRegistrationNumber() {
return registrationNumber;
}
public int getNumberOfSeats() {
return numberOfSeats;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.sealed.records;
public record Truck(int loadCapacity, String registrationNumber) implements Vehicle {
@Override
public String getRegistrationNumber() {
return registrationNumber;
}
public int getLoadCapacity() {
return loadCapacity;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.sealed.records;
public sealed interface Vehicle permits Car, Truck {
String getRegistrationNumber();
}

View File

@ -0,0 +1,76 @@
package com.baeldung.sealed.classes;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.lang.constant.ClassDesc;
public class VehicleUnitTest {
private static Vehicle car;
private static Vehicle truck;
@BeforeAll
public static void createInstances() {
car = new Car(5, "VZ500DA");
truck = new Truck(19000, "VZ600TA");
}
@Test
public void givenCar_whenUsingReflectionAPI_thenSuperClassIsSealed() {
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(car.getClass().getSuperclass().isSealed()).isEqualTo(true);
Assertions.assertThat(car.getClass().getSuperclass().permittedSubclasses())
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
}
@Test
public void givenTruck_whenUsingReflectionAPI_thenSuperClassIsSealed() {
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(truck.getClass().getSuperclass().isSealed()).isEqualTo(true);
Assertions.assertThat(truck.getClass().getSuperclass().permittedSubclasses())
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
}
@Test
public void givenCar_whenGettingPropertyTraditionalWay_thenNumberOfSeatsPropertyIsReturned() {
Assertions.assertThat(getPropertyTraditionalWay(car)).isEqualTo(5);
}
@Test
public void givenCar_whenGettingPropertyViaPatternMatching_thenNumberOfSeatsPropertyIsReturned() {
Assertions.assertThat(getPropertyViaPatternMatching(car)).isEqualTo(5);
}
@Test
public void givenTruck_whenGettingPropertyTraditionalWay_thenLoadCapacityIsReturned() {
Assertions.assertThat(getPropertyTraditionalWay(truck)).isEqualTo(19000);
}
@Test
public void givenTruck_whenGettingPropertyViaPatternMatching_thenLoadCapacityIsReturned() {
Assertions.assertThat(getPropertyViaPatternMatching(truck)).isEqualTo(19000);
}
private int getPropertyTraditionalWay(Vehicle vehicle) {
if (vehicle instanceof Car) {
return ((Car) vehicle).getNumberOfSeats();
} else if (vehicle instanceof Truck) {
return ((Truck) vehicle).getLoadCapacity();
} else {
throw new RuntimeException("Unknown instance of Vehicle");
}
}
private int getPropertyViaPatternMatching(Vehicle vehicle) {
if (vehicle instanceof Car car) {
return car.getNumberOfSeats();
} else if (vehicle instanceof Truck truck) {
return truck.getLoadCapacity();
} else {
throw new RuntimeException("Unknown instance of Vehicle");
}
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.sealed.records;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.lang.constant.ClassDesc;
public class VehicleUnitTest {
private static Vehicle car;
private static Vehicle truck;
@BeforeAll
public static void createInstances() {
car = new Car(4, "VZ500DA");
truck = new Truck(16000, "VZ600TA");
}
@Test
public void givenCar_whenUsingReflectionAPI_thenInterfaceIsSealed() {
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(car.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
Assertions.assertThat(car.getClass().getInterfaces()[0].permittedSubclasses())
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
}
@Test
public void givenTruck_whenUsingReflectionAPI_thenInterfaceIsSealed() {
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(truck.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
Assertions.assertThat(truck.getClass().getInterfaces()[0].permittedSubclasses())
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
}
@Test
public void givenCar_whenGettingPropertyTraditionalWay_thenNumberOfSeatsPropertyIsReturned() {
Assertions.assertThat(getPropertyTraditionalWay(car)).isEqualTo(4);
}
@Test
public void givenCar_whenGettingPropertyViaPatternMatching_thenNumberOfSeatsPropertyIsReturned() {
Assertions.assertThat(getPropertyViaPatternMatching(car)).isEqualTo(4);
}
@Test
public void givenTruck_whenGettingPropertyTraditionalWay_thenLoadCapacityIsReturned() {
Assertions.assertThat(getPropertyTraditionalWay(truck)).isEqualTo(16000);
}
@Test
public void givenTruck_whenGettingPropertyViaPatternMatching_thenLoadCapacityIsReturned() {
Assertions.assertThat(getPropertyViaPatternMatching(truck)).isEqualTo(16000);
}
private int getPropertyTraditionalWay(Vehicle vehicle) {
if (vehicle instanceof Car) {
return ((Car) vehicle).getNumberOfSeats();
} else if (vehicle instanceof Truck) {
return ((Truck) vehicle).getLoadCapacity();
} else {
throw new RuntimeException("Unknown instance of Vehicle");
}
}
private int getPropertyViaPatternMatching(Vehicle vehicle) {
if (vehicle instanceof Car car) {
return car.getNumberOfSeats();
} else if (vehicle instanceof Truck truck) {
return truck.getLoadCapacity();
} else {
throw new RuntimeException("Unknown instance of Vehicle");
}
}
}

View File

@ -19,12 +19,12 @@ public class StudentDbService implements StudentService {
}
public Student update(Student student) {
logger.log(Level.INFO, "Updating sutdent in DB...");
logger.log(Level.INFO, "Updating student in DB...");
return student;
}
public String delete(String registrationId) {
logger.log(Level.INFO, "Deleteing sutdent in DB...");
logger.log(Level.INFO, "Deleting student in DB...");
return registrationId;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.genericarrays;
import java.lang.reflect.Array;
public class MyStack<E> {
private E[] elements;
private int size = 0;
public MyStack(Class<E> clazz, int capacity) {
elements = (E[]) Array.newInstance(clazz, capacity);
}
public void push(E item) {
if (size == elements.length) {
throw new RuntimeException();
}
elements[size++] = item;
}
public E pop() {
if (size == 0) {
throw new RuntimeException();
}
return elements[--size];
}
public E[] getAllElements() {
return elements;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.genericarrays;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class ListToArrayUnitTest {
@Test
public void givenListOfItems_whenToArray_thenReturnArrayOfItems() {
List<String> items = new LinkedList<>();
items.add("first item");
items.add("second item");
String[] itemsAsArray = items.toArray(new String[0]);
assertEquals("first item", itemsAsArray[0]);
assertEquals("second item", itemsAsArray[1]);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.genericarrays;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MyStackUnitTest {
@Test
public void givenStackWithTwoItems_whenPop_thenReturnLastAdded() {
MyStack<String> myStack = new MyStack<>(String.class, 2);
myStack.push("hello");
myStack.push("example");
assertEquals("example", myStack.pop());
}
@Test (expected = RuntimeException.class)
public void givenStackWithFixedCapacity_whenExceedCapacity_thenThrowException() {
MyStack<Integer> myStack = new MyStack<>(Integer.class, 2);
myStack.push(100);
myStack.push(200);
myStack.push(300);
}
@Test(expected = RuntimeException.class)
public void givenStack_whenPopOnEmptyStack_thenThrowException() {
MyStack<Integer> myStack = new MyStack<>(Integer.class, 1);
myStack.push(100);
myStack.pop();
myStack.pop();
}
@Test
public void givenStackWithItems_whenGetAllElements_thenSizeShouldEqualTotal() {
MyStack<String> myStack = new MyStack<>(String.class, 2);
myStack.push("hello");
myStack.push("example");
String[] items = myStack.getAllElements();
assertEquals(2, items.length);
}
}

View File

@ -13,3 +13,5 @@
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)
- [A Guide to BitSet in Java](https://www.baeldung.com/java-bitset)
- [Get the First Key and Value From a HashMap](https://www.baeldung.com/java-hashmap-get-first-entry)
- [Performance of removeAll() in a HashSet](https://www.baeldung.com/java-hashset-removeall-performance)

View File

@ -33,11 +33,15 @@ public class HashSetBenchmark {
private List<Employee> employeeList1 = new ArrayList<>();
private Set<Employee> employeeSet2 = new HashSet<>();
private List<Employee> employeeList2 = new ArrayList<>();
private Set<Employee> employeeSet3 = new HashSet<>();
private Set<Employee> employeeSet4 = new HashSet<>();
private long set1Size = 60000;
private long list1Size = 50000;
private long set2Size = 50000;
private long list2Size = 60000;
private long set3Size = 50000;
private long set4Size = 60000;
@Setup(Level.Trial)
public void setUp() {
@ -57,6 +61,14 @@ public class HashSetBenchmark {
for (long i = 0; i < list2Size; i++) {
employeeList2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < set3Size; i++) {
employeeSet3.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < set4Size; i++) {
employeeSet4.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
}
@ -71,6 +83,11 @@ public class HashSetBenchmark {
public boolean given_SizeOfHashsetSmallerThanSizeOfCollection_When_RemoveAllFromHashSet_Then_BadPerformance(MyState state) {
return state.employeeSet2.removeAll(state.employeeList2);
}
@Benchmark
public boolean given_SizeOfHashsetSmallerThanSizeOfAnotherHashSet_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) {
return state.employeeSet3.removeAll(state.employeeSet4);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder().include(HashSetBenchmark.class.getSimpleName())

View File

@ -13,7 +13,7 @@ This module contains articles about advanced topics about multithreading with co
- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock)
- [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference)
- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency)
- [Introduction to Lock-Free Data Structures](https://www.baeldung.com/lock-free-programming)
- [Introduction to Lock-Free Data Structures with Java Examples](https://www.baeldung.com/lock-free-programming)
- [Introduction to Exchanger in Java](https://www.baeldung.com/java-exchanger)
- [Why Not To Start A Thread In The Constructor?](https://www.baeldung.com/java-thread-constructor)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@ -73,7 +73,7 @@ public class LivelockExample {
public void tryLock(Lock lock, long millis) {
try {
lock.tryLock(10, TimeUnit.MILLISECONDS);
lock.tryLock(millis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}

View File

@ -11,4 +11,5 @@ This module contains articles about basic Java concurrency
- [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle)
- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference)
- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
- [How to Stop Execution After a Certain Time in Java](https://www.baeldung.com/java-stop-execution-after-certain-time)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)

View File

@ -0,0 +1,263 @@
package com.baeldung.concurrent.stopexecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class StopExecution {
private static final Logger LOG = LoggerFactory.getLogger(StopExecution.class);
public static void main(String[] args) {
StopExecution stopExecution = new StopExecution();
//stopExecution.testUsingLoop();
//stopExecution.testTimer();
stopExecution.testScheduledExecutor();
LOG.info("done");
}
public void testUsingLoop() {
long start = System.currentTimeMillis();
long end = start + 5000;
List<String> items = new ArrayList<>();
int counter = 0;
// Let this loop run only upto 5 seconds
while (System.currentTimeMillis() < end && counter < items.size()) {
// Fetch the item from the list.
// Some expensive operation on the item.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
}
}
public static void testThreads() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
LOG.info("inside run");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LOG.info("exit run");
}
});
thread.start();
while (thread.getState() != Thread.State.TERMINATED) {
LOG.info(thread.getState().name());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void testExecutor() {
final ExecutorService service = Executors.newSingleThreadExecutor();
Future<String> f = null;
try {
f = service.submit(() -> {
// Do you long running calculation here
try {
Thread.sleep(2737); // Simulate some delay
} catch (InterruptedException e) {
LOG.info("Interrupted");
return "interrupted";
}
LOG.info("Sleep finished");
return "42";
});
LOG.info(f.get(2, TimeUnit.SECONDS));
} catch (TimeoutException e) {
f.cancel(true);
LOG.error("Calculation took to long");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
service.shutdown();
}
}
public void testExecutor2() {
final ExecutorService service = Executors.newSingleThreadExecutor();
Future f = null;
try {
f = service.submit(new LongRunningTask());
LOG.info("testExecutor2");
f.get(1, TimeUnit.SECONDS);
} catch (final TimeoutException e) {
f.cancel(true);
LOG.error("Calculation took to long");
} catch (final Exception e) {
throw new RuntimeException(e);
} finally {
service.shutdownNow();
}
}
public void testScheduledExecutor() {
LOG.info("testScheduledExecutor");
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
Future future = executor.submit(new LongRunningTask());
executor.schedule(new Runnable() {
public void run() {
future.cancel(true);
}
}, 1000, TimeUnit.MILLISECONDS);
executor.shutdown();
}
public void testThreadAndInterrupt() {
Thread t;
try {
t = new Thread(new LongRunningTask());
LOG.info("testExecutor3");
long end = System.currentTimeMillis() + 2000;
t.start();
while (t.isAlive() && System.currentTimeMillis() < end) {
Thread.sleep(50);
}
t.interrupt();
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
public void testTimer() {
LOG.info("Timer test");
Thread t = new Thread(new LongRunningTask());
Timer timeoutTimer = new Timer();
timeoutTimer.schedule(new TimeOutTask(t, timeoutTimer), 1000);
t.start();
}
class MyRunnableTask implements Runnable {
public void run() {
try {
LOG.info("MyRunnable...");
Thread.sleep(10000);
} catch (InterruptedException ie) {
LOG.info("MyRunnable interrupted...");
}
}
}
class TimeOutTask extends TimerTask {
private Thread t;
private Timer timer;
TimeOutTask(Thread t, Timer timer) {
this.t = t;
this.timer = timer;
}
public void run() {
if (t != null && t.isAlive()) {
t.interrupt();
timer.cancel();
}
}
}
class LongRunningTask implements Runnable {
@Override
public void run() {
longRunningSort();
}
private void longRunningOperation() {
LOG.info("long Running operation started");
try {
//Thread.sleep(500);
longFileRead();
LOG.info("long running operation finished");
} catch (InterruptedException e) {
LOG.info("long Running operation interrupted");
}
}
private void longRunningSort() {
LOG.info("long Running task started");
// Do you long running calculation here
int len = 100000;
List<Integer> numbers = new ArrayList<>();
try {
for (int i = len; i > 0; i--) {
//Thread.sleep(5)
numbers.add(i);
}
int i = 0;
for (i = 0; i < len; i++) {
int minIndex = i;
for (int j = i + 1; j < len; j++) {
if (numbers.get(minIndex) > numbers.get(j))
minIndex = j;
}
if (minIndex != i) {
int temp = numbers.get(i);
numbers.set(i, numbers.get(minIndex));
numbers.set(minIndex, temp);
}
throwExceptionOnThreadInterrupt();
}
LOG.info("Index position: " + i);
LOG.info("Long running task finished");
} catch (InterruptedException e) {
LOG.info("long Running operation interrupted");
}
}
private void longFileRead() throws InterruptedException {
String file = "input.txt";
ClassLoader classloader = getClass().getClassLoader();
try (InputStream inputStream = classloader.getResourceAsStream(file)) {
Reader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
char theChar = (char) data;
data = inputStreamReader.read();
throwExceptionOnThreadInterrupt();
}
} catch (IOException e) {
LOG.error("Exception: ", e);
}
}
private void throwExceptionOnThreadInterrupt() throws InterruptedException {
if (Thread.currentThread().interrupted()) {
throw new InterruptedException();
}
}
}
}

View File

@ -3,3 +3,6 @@
- [NoSuchMethodError in Java](https://www.baeldung.com/java-nosuchmethod-error)
- [IllegalArgumentException or NullPointerException for a Null Parameter?](https://www.baeldung.com/java-illegalargumentexception-or-nullpointerexception)
- [IllegalMonitorStateException in Java](https://www.baeldung.com/java-illegalmonitorstateexception)
- [AbstractMethodError in Java](https://www.baeldung.com/java-abstractmethoderror)
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)
- [Localizing Exception Messages in Java](https://www.baeldung.com/java-localize-exception-messages)

View File

@ -17,6 +17,14 @@
</parent>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.191</version>
<scope>test</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>

View File

@ -0,0 +1,14 @@
package com.baeldung.exception.indexoutofbounds;
import java.util.ArrayList;
import java.util.List;
public class CopyListUsingAddAllMethodDemo {
static List<Integer> copyList(List<Integer> source) {
List<Integer> destination = new ArrayList<>();
destination.addAll(source);
return destination;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.exception.indexoutofbounds;
import java.util.Collections;
import java.util.List;
public class CopyListUsingCollectionsCopyMethodDemo {
static void copyList(List<Integer> source, List<Integer> destination) {
Collections.copy(destination, source);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.exception.indexoutofbounds;
import java.util.ArrayList;
import java.util.List;
public class CopyListUsingConstructorDemo {
static List<Integer> copyList(List<Integer> source) {
return new ArrayList<>(source);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.exception.indexoutofbounds;
import java.util.List;
import java.util.stream.Collectors;
public class CopyListUsingJava8StreamDemo {
static List<Integer> copyList(List<Integer> source) {
return source
.stream()
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.exception.indexoutofbounds;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class IndexOutOfBoundsExceptionDemo {
static List<Integer> copyList(List<Integer> source) {
List<Integer> destination = new ArrayList<>(source.size());
Collections.copy(destination, source);
return destination;
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.exceptions.classcastexception;
public interface Animal {
String getName();
}

View File

@ -0,0 +1,14 @@
package com.baeldung.exceptions.classcastexception;
public class Box<T> {
private T content;
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.exceptions.classcastexception;
public class Frog extends Reptile {
@Override
public String getName() {
return super.getName() + ": Frog";
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.exceptions.classcastexception;
public class Mammal implements Animal {
@Override
public String getName() {
return "Mammal";
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.exceptions.classcastexception;
public class Reptile implements Animal {
@Override
public String getName() {
return "Reptile";
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.exceptions.localization;
import java.util.Locale;
public class LocalizedException extends Exception {
private static final long serialVersionUID = 1L;
private final String messageKey;
private final Locale locale;
public LocalizedException(String messageKey) {
this(messageKey, Locale.getDefault());
}
public LocalizedException(String messageKey, Locale locale) {
this.messageKey = messageKey;
this.locale = locale;
}
/**
* @return a localized message based on the messageKey provided at instantiation.
*/
public String getMessage() {
/*
* This is a deliberate role reversal of the default implementation of getLocalizedMessage.
* some logging frameworks like Log4J 1 & 2 and Logback will use getMessage instead of
* getLocalizedMessage when logging Throwables. If we want to use these frameworks in client
* applications to log localized messages, then we'll need to override getMessage in a
* similar fashion to return the appropriate content. Or, you can call getLocalizedMessage
* on your own to create the log content.
*/
return getLocalizedMessage();
}
/**
* @return a localized message based on the messageKey provided at instantiation.
*/
public String getLocalizedMessage() {
/*
* java.util.logging uses getLocalizedMessage when logging Throwables.
*/
return Messages.getMessageForLocale(messageKey, locale);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.exceptions.localization;
import java.util.Locale;
import java.util.ResourceBundle;
public class Messages {
/**
* Retrieves the value for the messageKey from the locale-specific messages.properties, or from
* the base messages.properties for unsupported locales.
*
* @param messageKey The key for the message in the messages.properties ResourceBundle.
* @param locale The locale to search the message key.
* @return The value defined for the messageKey in the provided locale.
*/
public static String getMessageForLocale(String messageKey, Locale locale) {
/*
* For more complex implementations, you will want a var-args parameter for MessageFormat
* substitutions. Then we can read the value from the bundle and pass the value with the
* substitutions to MessageFormat to create the final message value.
*/
return ResourceBundle.getBundle("messages", locale)
.getString(messageKey);
}
}

View File

@ -0,0 +1 @@
message.exception = I am an exception.

View File

@ -0,0 +1 @@
message.exception = Je suis une exception.

View File

@ -0,0 +1,18 @@
package com.baeldung.exception.indexoutofbounds;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class CopyListUsingAddAllMethodDemoUnitTest {
@Test
void whenPassValidArrayList_thenCopyListUsingAddAllMethod() {
List<Integer> source = Arrays.asList(11, 22, 33);
assertEquals(source, CopyListUsingAddAllMethodDemo.copyList(source));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.exception.indexoutofbounds;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class CopyListUsingCollectionsCopyMethodDemoUnitTest {
@Test
void whenCopyListUsingCollectionsCopy_thenOverrideAllDestinationListValues() {
List<Integer> source = Arrays.asList(11, 22, 33);
List<Integer> destination = Arrays.asList(1, 2, 3);
CopyListUsingCollectionsCopyMethodDemo.copyList(source, destination);
assertEquals(source, destination);
}
@Test
void whenCopyListUsingCollectionsCopy_thenOverrideInitialDestinationValuesAndOthersShouldBeUnchanged(){
List<Integer> source = Arrays.asList(11, 22, 33);
List<Integer> destination = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> expectedList = Arrays.asList(11, 22, 33, 4, 5);
CopyListUsingCollectionsCopyMethodDemo.copyList(source, destination);
assertEquals(expectedList, destination);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.exception.indexoutofbounds;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class CopyListUsingConstructorDemoUnitTest {
@Test
void whenCopyListUsingConstructor_thenMakeACopyOfList() {
List<Integer> source = Arrays.asList(11, 22, 33);
assertEquals(source, CopyListUsingConstructorDemo.copyList(source));
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.exception.indexoutofbounds;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class CopyListUsingJava8StreamDemoUnitTest {
@Test
void whenCopyListUsingStream_thenMakeACopyOfArrayList() {
List<Integer> source = Arrays.asList(11, 22, 33);
assertEquals(source, CopyListUsingJava8StreamDemo.copyList(source));
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.exception.indexoutofbounds;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class IndexOutOfBoundsExceptionDemoUnitTest {
@Test
void givenDestinationArrayListSizeIsZero_whenCopySourceArrayListToDestination_thenShouldThrowIndexOutOfBoundsException() {
List<Integer> source = Arrays.asList(1, 2, 3, 4, 5);
assertThrows(IndexOutOfBoundsException.class, () -> IndexOutOfBoundsExceptionDemo.copyList(source));
}
@Test
void givenSourceAndDestinationListSizeIsEqual_whenCopySourceArrayListToDestination_thenShouldNotThrowIndexOutOfBoundsException() {
List<Integer> source = Collections.emptyList();
assertEquals(source, IndexOutOfBoundsExceptionDemo.copyList(source));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.exceptions.abstractmethoderror;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class AbstractMethodErrorUnitTest {
private static final String url = "jdbc:h2:mem:A-DATABASE;INIT=CREATE SCHEMA IF NOT EXISTS myschema";
private static final String username = "sa";
@Test
void givenOldH2Database_whenCallgetSchemaMethod_thenThrowAbstractMethodError() throws SQLException {
Connection conn = DriverManager.getConnection(url, username, "");
assertNotNull(conn);
Assertions.assertThrows(AbstractMethodError.class, () -> conn.getSchema());
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.exceptions.classcastexception;
import org.junit.Test;
import java.io.Serializable;
public class CheckedCastsUnitTest {
@Test(expected = ClassCastException.class)
public void givenBaseTypeVariableReferencingChildInstance_whenCastToIncompatibleSubtype_thenClassCastException() {
Animal animal = new Frog();
//A checked downcast to Mammal is incompatible from Frog because Frog is not a subtype of Mammal.
Mammal mammal = (Mammal) animal;
}
@Test(expected = ClassCastException.class)
public void givenBaseTypeVariableReferencingChildInstance_whenCastToIncompatibleInterface_thenClassCastException() {
Animal animal = new Frog();
//A checked cast to Serializable is incompatible from Frog because Frog is not a subtype of Serializable.
Serializable serial = (Serializable) animal;
}
@Test(expected = ClassCastException.class)
public void givenObjectVariableReferencingPrimitiveArray_whenCastToBoxedTypeArray_thenClassCastException() {
Object primitives = new int[1];
//A checked cast to Integer[] is incompatible from primitive arrays. Auto-boxing does not work for arrays.
Integer[] integers = (Integer[]) primitives;
}
@Test(expected = ClassCastException.class)
public void givenObjectVariableReferencingPrimitiveArray_whenCastToPromotedTypeArray_thenClassCastException() {
Object primitives = new int[1];
//A checked cast to long[] is incompatible from int[]. Type promotion does not work for arrays.
long[] longs = (long[]) primitives;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.exceptions.classcastexception;
import org.junit.Test;
public class GenericConversionUnitTest {
@Test(expected = ClassCastException.class)
public void givenIncompatibleType_whenConvertInstanceOfObject_thenClassCastException() {
// Should have been null, but due to type erasure, inside convertInstanceOfObject,
// it will attempt to cast to Object instead of String, so it casts to Object, which is always possible.
String shouldBeNull = convertInstanceOfObject(123);
}
public static <T> T convertInstanceOfObject(Object o) {
try {
return (T) o; // Casts to Object due to type erasure
} catch (ClassCastException e) {
return null; // Will never reach this
}
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.exceptions.classcastexception;
import org.junit.Test;
public class UncheckedConversionUnitTest {
@Test(expected = ClassCastException.class)
public void givenPollutedGenericType_whenGetProperty_thenClassCastException() {
Box<Long> originalBox = new Box<>();
Box raw = originalBox;
raw.setContent(2.5);
Box<Long> bound = (Box<Long>) raw;
//An incompatible element was found in the raw box.
Long content = bound.getContent();
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.exceptions.localization;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
public class LocalizedExceptionUnitTest {
private Locale originalDefaultLocale;
@Before
public void saveOriginalDefaultLocale() {
originalDefaultLocale = Locale.getDefault();
}
@After
public void restoreOriginalDefaultLocale() {
Locale.setDefault(originalDefaultLocale);
}
@Test
public void givenUsEnglishDefaultLocale_whenLocalizingMessage_thenMessageComesFromDefaultMessages() {
Locale.setDefault(Locale.US);
LocalizedException localizedException = new LocalizedException("message.exception");
String usEnglishLocalizedExceptionMessage = localizedException.getLocalizedMessage();
assertThat(usEnglishLocalizedExceptionMessage).isEqualTo("I am an exception.");
}
@Test
public void givenFranceFrenchDefaultLocale_whenLocalizingMessage_thenMessageComesFromFrenchTranslationMessages() {
Locale.setDefault(Locale.FRANCE);
LocalizedException localizedException = new LocalizedException("message.exception");
String franceFrenchLocalizedExceptionMessage = localizedException.getLocalizedMessage();
assertThat(franceFrenchLocalizedExceptionMessage).isEqualTo("Je suis une exception.");
}
@Test
public void givenUsEnglishProvidedLocale_whenLocalizingMessage_thenMessageComesFromDefaultMessage() {
LocalizedException localizedException = new LocalizedException("message.exception", Locale.US);
String usEnglishLocalizedExceptionMessage = localizedException.getLocalizedMessage();
assertThat(usEnglishLocalizedExceptionMessage).isEqualTo("I am an exception.");
}
@Test
public void givenFranceFrenchProvidedLocale_whenLocalizingMessage_thenMessageComesFromFrenchTranslationMessages() {
LocalizedException localizedException = new LocalizedException("message.exception", Locale.FRANCE);
String franceFrenchLocalizedExceptionMessage = localizedException.getLocalizedMessage();
assertThat(franceFrenchLocalizedExceptionMessage).isEqualTo("Je suis une exception.");
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.exceptions.localization;
import org.junit.Test;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
public class MessagesUnitTest {
@Test
public void givenUsEnglishLocale_whenRetrievingMessage_thenEnglishTranslationIsReturned() {
String translatedMessage = Messages.getMessageForLocale("message.exception", Locale.US);
assertThat(translatedMessage).isEqualTo("I am an exception.");
}
@Test
public void givenFranceFrenchLocale_whenRetrievingMessage_thenFrenchTranslationIsReturned() {
String translatedMessage = Messages.getMessageForLocale("message.exception", Locale.FRANCE);
assertThat(translatedMessage).isEqualTo("Je suis une exception.");
}
}

View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Functional Programming in Java](https://www.baeldung.com/java-functional-programming)

View File

@ -0,0 +1,18 @@
<?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>core-java-functional</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-functional</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.functional;
import java.util.function.Function;
public class Currying {
private static Function<Double, Function<Double, Double>> weight = mass -> gravity -> mass * gravity;
private static Function<Double, Double> weightOnEarth = weight.apply(9.81);
private static Function<Double, Double> weightOnMars = weight.apply(3.75);
public static Double weightOnEarth(Double mass) {
return weightOnEarth.apply(mass);
}
public static Double weightOnMars(Double mass) {
return weightOnMars.apply(mass);
}
public static Function<Double, Double> weightOnEarth() {
final double gravity = 9.81;
return mass -> mass * gravity;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.functional;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class FirstClassFunctions {
public static List<Integer> sortWithoutLambda(List<Integer> numbers) {
Collections.sort(numbers, new Comparator<Integer>() {
@Override
public int compare(Integer n1, Integer n2) {
return n1.compareTo(n2);
}
});
return numbers;
}
public static List<Integer> sortWithLambda(List<Integer> numbers) {
Collections.sort(numbers, (n1, n2) -> n1.compareTo(n2));
return numbers;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.functional;
import java.util.function.Function;
public class FunctionComposition {
private static Function<Double, Double> log = (value) -> Math.log(value);
private static Function<Double, Double> sqrt = (value) -> Math.sqrt(value);
public static Double logThenSqrt(Double number) {
Function<Double, Double> logThenSqrt = sqrt.compose(log);
return (logThenSqrt.apply(3.14));
}
public static Double sqrtThenLog(Double number) {
Function<Double, Double> sqrtThenLog = sqrt.andThen(log);
return (sqrtThenLog.apply(3.14));
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.functional;
public class ImmutableData {
private final String someData;
private final AnotherImmutableData anotherImmutableData;
public ImmutableData(final String someData, final AnotherImmutableData anotherImmutableData) {
this.someData = someData;
this.anotherImmutableData = anotherImmutableData;
}
public String getSomeData() {
return someData;
}
public AnotherImmutableData getAnotherImmutableData() {
return anotherImmutableData;
}
public class AnotherImmutableData {
private final Integer someOtherData;
public AnotherImmutableData(final Integer someData) {
this.someOtherData = someData;
}
public Integer getSomeOtherData() {
return someOtherData;
}
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.functional;
import java.util.Optional;
public class Monads {
public static Optional<Integer> add(Optional<Integer> val1, Optional<Integer> val2) {
return val1.flatMap(first -> val2.flatMap(second -> Optional.of(first + second)));
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.functional;
import java.util.List;
import java.util.stream.Collectors;
public class PureFunctions {
public static Integer sum(List<Integer> numbers) {
return numbers.stream()
.collect(Collectors.summingInt(Integer::intValue));
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.functional;
public class Recursion {
public static Integer headRecursion(Integer number) {
return (number == 1) ? 1 : number * headRecursion(number - 1);
}
public static Integer tailRecursion(Integer number, Integer result) {
return (number == 1) ? result : tailRecursion(number - 1, result * number);
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.functional;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ReferentialTransparency {
private static Logger logger = Logger.getGlobal();
public void main() {
String data = new SimpleData().setData("Baeldung")
.getData();
logger.log(Level.INFO, new SimpleData().setData("Baeldung")
.getData());
logger.log(Level.INFO, data);
logger.log(Level.INFO, "Baeldung");
}
public class SimpleData {
private Logger logger = Logger.getGlobal();
private String data;
public String getData() {
logger.log(Level.INFO, "Get data called for SimpleData");
return data;
}
public SimpleData setData(String data) {
logger.log(Level.INFO, "Set data called for SimpleData");
this.data = data;
return this;
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class CurryingUnitTest {
@Test
public void testWeightOnEarth() {
assertEquals(588.6, Currying.weightOnEarth(60.0), 0.1);
}
@Test
public void testWeightOnMars() {
assertEquals(225.0, Currying.weightOnMars(60.0), 0.1);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import org.junit.Test;
public class FirstClassFunctionsUnitTest {
@Test
public void testSortingWithoutLambda() {
assertEquals(new Integer(8), FirstClassFunctions.sortWithoutLambda(Arrays.asList(new Integer(10), new Integer(8)))
.get(0));
}
@Test
public void testSortingWithLambda() {
assertEquals(new Integer(8), FirstClassFunctions.sortWithLambda(Arrays.asList(new Integer(10), new Integer(8)))
.get(0));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class FunctionCompositionUnitTest {
@Test
public void testLogThenSqrt() {
assertEquals(1.07, FunctionComposition.logThenSqrt(3.14), 0.01);
}
@Test
public void testSqrtThenLog() {
assertEquals(0.57, FunctionComposition.sqrtThenLog(3.14), 0.01);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Optional;
import org.junit.Test;
public class MonadsUnitTest {
@Test
public void testOptionalAdd() {
assertEquals(5, Monads.add(Optional.of(new Integer(2)), Optional.of(new Integer(3)))
.get());
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import org.junit.Test;
public class PureFunctionsUnitTets {
@Test
public void testSortingWithoutLambda() {
assertEquals(new Integer(18), PureFunctions.sum(Arrays.asList(new Integer(10), new Integer(8))));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class RecursionUnitTest {
@Test
public void testHeadRecursion() {
assertEquals(120, Recursion.headRecursion(5));
}
@Test
public void testTailRecursion() {
assertEquals(120, Recursion.tailRecursion(5, 1));
}
}

View File

@ -11,4 +11,5 @@ This module contains articles about core Java input and output (IO)
- [Java Files Open Options](https://www.baeldung.com/java-file-options)
- [Creating Temporary Directories in Java](https://www.baeldung.com/java-temp-directories)
- [Reading a Line at a Given Line Number From a File in Java](https://www.baeldung.com/java-read-line-at-number)
- [Find the Last Modified File in a Directory with Java](https://www.baeldung.com/java-last-modified-file)
- [[<-- Prev]](/core-java-modules/core-java-io-2)

View File

@ -6,6 +6,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@ -37,6 +38,12 @@ public class CreateFileUnitTest {
assertTrue(success);
}
@Test
void givenUsingFileOutputStream_whenCreatingFile_thenCorrect() throws IOException {
try(FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME)){
}
}
@Test
public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
com.google.common.io.Files.touch(new File(FILE_NAME));

View File

@ -0,0 +1 @@
!src/test/resources/example-jar/stripe-0.0.1-SNAPSHOT.jar

View File

@ -7,3 +7,4 @@ This module contains articles about JAR files
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
- [Get Names of Classes Inside a JAR File](https://www.baeldung.com/jar-file-get-class-names)

View File

@ -0,0 +1,43 @@
package com.baeldung.jar;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class GetClassNamesFromJar {
public static Set<String> getClassNamesFromJarFile(File givenFile) throws IOException {
Set<String> classNames = new HashSet<>();
try (JarFile jarFile = new JarFile(givenFile)) {
Enumeration<JarEntry> e = jarFile.entries();
while (e.hasMoreElements()) {
JarEntry jarEntry = e.nextElement();
if (jarEntry.getName().endsWith(".class")) {
String className = jarEntry.getName()
.replace("/", ".")
.replace(".class", "");
classNames.add(className);
}
}
return classNames;
}
}
public static Set<Class> getClassesFromJarFile(File jarFile) throws IOException, ClassNotFoundException {
Set<String> classNames = getClassNamesFromJarFile(jarFile);
Set<Class> classes = new HashSet<>(classNames.size());
try (URLClassLoader cl = URLClassLoader.newInstance(new URL[] { new URL("jar:file:" + jarFile + "!/") })) {
for (String name : classNames) {
Class clazz = cl.loadClass(name); // Loading the class by its name
classes.add(clazz);
}
}
return classes;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.jar;
import com.google.common.collect.Sets;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
public class GetClassNamesFromJarUnitTest {
private static final String JAR_PATH = "example-jar/stripe-0.0.1-SNAPSHOT.jar";
private static final Set<String> EXPECTED_CLASS_NAMES = Sets.newHashSet(
"com.baeldung.stripe.StripeApplication",
"com.baeldung.stripe.ChargeRequest",
"com.baeldung.stripe.StripeService",
"com.baeldung.stripe.ChargeRequest$Currency",
"com.baeldung.stripe.ChargeController",
"com.baeldung.stripe.CheckoutController");
@Test
public void givenJarFilePath_whenLoadClassNames_thenGetClassNames() throws IOException, URISyntaxException {
File jarFile = new File(Objects.requireNonNull(getClass().getClassLoader().getResource(JAR_PATH)).toURI());
Set<String> classNames = GetClassNamesFromJar.getClassNamesFromJarFile(jarFile);
Assert.assertEquals(EXPECTED_CLASS_NAMES, classNames);
}
@Test
public void givenJarFilePath_whenLoadClass_thenGetClassObjects() throws IOException, ClassNotFoundException, URISyntaxException {
File jarFile = new File(Objects.requireNonNull(getClass().getClassLoader().getResource(JAR_PATH)).toURI());
Set<Class> classes = GetClassNamesFromJar.getClassesFromJarFile(jarFile);
Set<String> names = classes.stream().map(Class::getName).collect(Collectors.toSet());
Assert.assertEquals(EXPECTED_CLASS_NAMES, names);
}
}

View File

@ -6,4 +6,7 @@ This module contains articles about core features in the Java language
- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean)
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
- [Checking if a Class Exists in Java](https://www.baeldung.com/java-check-class-exists)
- [The Difference Between a.getClass() and A.class in Java](https://www.baeldung.com/java-getclass-vs-class)
- [Constants in Java: Patterns and Anti-Patterns](https://www.baeldung.com/java-constants-good-practices)
- [The transient Keyword in Java](https://www.baeldung.com/java-transient-keyword)
- [[<-- Prev]](/core-java-modules/core-java-lang-2)

View File

@ -0,0 +1,37 @@
package com.baeldung.constantspatterns;
public class Calculator {
public static final double PI = 3.14159265359;
private static final double UPPER_LIMIT = 0x1.fffffffffffffP+1023;
public enum Operation {
ADD, SUBTRACT, DIVIDE, MULTIPLY
}
public double operateOnTwoNumbers(double numberOne, double numberTwo, Operation operation) {
if (numberOne > UPPER_LIMIT) {
throw new IllegalArgumentException("'numberOne' is too large");
}
if (numberTwo > UPPER_LIMIT) {
throw new IllegalArgumentException("'numberTwo' is too large");
}
double answer = 0;
switch (operation) {
case ADD:
answer = numberOne + numberTwo;
break;
case SUBTRACT:
answer = numberOne - numberTwo;
break;
case DIVIDE:
answer = numberOne / numberTwo;
break;
case MULTIPLY:
answer = numberOne * numberTwo;
break;
}
return answer;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.constantspatterns;
public interface CalculatorConstants {
double PI = 3.14159265359;
double UPPER_LIMIT = 0x1.fffffffffffffP+1023;
enum Operation {
ADD, SUBTRACT, MULTIPLY, DIVIDE
};
}

View File

@ -0,0 +1,32 @@
package com.baeldung.constantspatterns;
public class GeometryCalculator implements CalculatorConstants {
public static final double UPPER_LIMIT = 100000000000000000000.0;
public double operateOnTwoNumbers(double numberOne, double numberTwo, Operation operation) {
if (numberOne > UPPER_LIMIT) {
throw new IllegalArgumentException("'numberOne' is too large");
}
if (numberTwo > UPPER_LIMIT) {
throw new IllegalArgumentException("'numberTwo' is too large");
}
double answer = 0;
switch (operation) {
case ADD:
answer = numberOne + numberTwo;
break;
case SUBTRACT:
answer = numberOne - numberTwo;
break;
case DIVIDE:
answer = numberOne / numberTwo;
break;
case MULTIPLY:
answer = numberOne * numberTwo;
break;
}
return answer;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.constantspatterns.calculations;
public final class MathConstants {
public static final double PI = 3.14159265359;
static final double GOLDEN_RATIO = 1.6180;
static final double GRAVITATIONAL_ACCELERATION = 9.8;
static final double EULERS_NUMBER = 2.7182818284590452353602874713527;
public enum Operation {
ADD, SUBTRACT, DIVIDE, MULTIPLY
}
private MathConstants() {
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.transientkw;
import java.io.Serializable;
public class Book implements Serializable {
private static final long serialVersionUID = -2936687026040726549L;
private String bookName;
private transient String description;
private transient int copies;
private final transient String bookCategory = "Fiction";
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getCopies() {
return copies;
}
public void setCopies(int copies) {
this.copies = copies;
}
public String getBookCategory() {
return bookCategory;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.transientkw;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class BookSerDe {
static String fileName = "book.ser";
/**
* Method to serialize Book objects to the file
* @throws FileNotFoundException
*/
public static void serialize(Book book) throws Exception {
FileOutputStream file = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(book);
out.close();
file.close();
}
/**
* Method to deserialize the person object
* @return book
* @throws IOException, ClassNotFoundException
*/
public static Book deserialize() throws Exception {
FileInputStream file = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(file);
Book book = (Book) in.readObject();
in.close();
file.close();
return book;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.constantspatterns;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class ConstantPatternUnitTest {
@Test
public void givenTwoNumbersAndAdd_whenCallingCalculatorOperatOneTwoNumbers_thenCorrectAnswerReturned() {
Calculator calculator = new Calculator();
double expected = 4;
double answer = calculator.operateOnTwoNumbers(2, 2, Calculator.Operation.ADD);
assertEquals(expected, answer);
}
@Test
public void givenTwoNumbersAndAdd_whenCallingGeometryCalculatorOperatOneTwoNumbers_thenCorrectAnswerReturned() {
GeometryCalculator calculator = new GeometryCalculator();
double expected = 4;
double answer = calculator.operateOnTwoNumbers(2, 2, GeometryCalculator.Operation.ADD);
assertEquals(expected, answer);
}
}

Some files were not shown because too many files have changed in this diff Show More