This commit is contained in:
Jonathan Cook 2020-10-21 09:37:43 +02:00
commit 8be57c1a0f
631 changed files with 12517 additions and 1836 deletions

View File

@ -10,4 +10,4 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Introduction to Minimax Algorithm](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

@ -15,5 +15,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [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)
- More articles: [[<-- prev]](/algorithms-miscellaneous-4) [[next -->]](/algorithms-miscellaneous-6)

View File

@ -9,4 +9,5 @@
- [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)
- [Reversing a Linked List in Java](https://www.baeldung.com/java-reverse-linked-list)
- More articles: [[<-- prev]](/algorithms-miscellaneous-5)

View File

@ -0,0 +1,30 @@
package com.baeldung.algorithms.linkedlist;
public class LinkedListReversal {
ListNode reverseList(ListNode head) {
ListNode previous = null;
ListNode current = head;
while (current != null) {
ListNode nextElement = current.getNext();
current.setNext(previous);
previous = current;
current = nextElement;
}
return previous;
}
ListNode reverseListRecursive(ListNode head) {
if (head == null) {
return null;
}
if (head.getNext() == null) {
return head;
}
ListNode node = reverseListRecursive(head.getNext());
head.getNext().setNext(head);
head.setNext(null);
return node;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.algorithms.linkedlist;
public class ListNode {
private int data;
private ListNode next;
ListNode(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public ListNode getNext() {
return next;
}
public void setData(int data) {
this.data = data;
}
public void setNext(ListNode next) {
this.next = next;
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class LinkedListReversalUnitTest {
@Test
public void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() {
ListNode head = constructLinkedList();
ListNode node = head;
for (int i = 1; i <= 5; i++) {
assertNotNull(node);
assertEquals(i, node.getData());
node = node.getNext();
}
LinkedListReversal reversal = new LinkedListReversal();
node = reversal.reverseList(head);
for (int i = 5; i >= 1; i--) {
assertNotNull(node);
assertEquals(i, node.getData());
node = node.getNext();
}
}
@Test
public void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() {
ListNode head = constructLinkedList();
ListNode node = head;
for (int i = 1; i <= 5; i++) {
assertNotNull(node);
assertEquals(i, node.getData());
node = node.getNext();
}
LinkedListReversal reversal = new LinkedListReversal();
node = reversal.reverseListRecursive(head);
for (int i = 5; i >= 1; i--) {
assertNotNull(node);
assertEquals(i, node.getData());
node = node.getNext();
}
}
private ListNode constructLinkedList() {
ListNode head = null;
ListNode tail = null;
for (int i = 1; i <= 5; i++) {
ListNode node = new ListNode(i);
if (head == null) {
head = node;
} else {
tail.setNext(node);
}
tail = node;
}
return head;
}
}

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>

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

@ -5,3 +5,4 @@ This module contains articles about AWS Lambda
### Relevant Articles:
- [Using AWS Lambda with API Gateway](https://www.baeldung.com/aws-lambda-api-gateway)
- [Introduction to AWS Serverless Application Model](https://www.baeldung.com/aws-serverless)
- [How to Implement Hibernate in an AWS Lambda Function in Java](https://www.baeldung.com/java-aws-lambda-hibernate)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [How to Remove a Prefix From Strings in Groovy](https://www.baeldung.com/groovy-remove-string-prefix)

122
core-groovy-strings/pom.xml Normal file
View File

@ -0,0 +1,122 @@
<?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-groovy-strings</artifactId>
<version>1.0-SNAPSHOT</version>
<name>core-groovy-strings</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy-all.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-dateutil</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-sql</artifactId>
<version>${groovy-sql.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>${spock-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>${gmavenplus-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>compile</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>junit5</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*Test5.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>central</id>
<url>https://jcenter.bintray.com</url>
</repository>
</repositories>
<properties>
<junit.platform.version>1.0.0</junit.platform.version>
<groovy.version>2.5.6</groovy.version>
<groovy-all.version>2.5.6</groovy-all.version>
<groovy-sql.version>2.5.6</groovy-sql.version>
<hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version>
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,70 @@
package com.baeldung.removeprefix
import org.junit.Assert
import org.junit.Test
class RemovePrefixTest {
@Test
public void whenCasePrefixIsRemoved_thenReturnTrue() {
def trimPrefix = {
it.startsWith('Groovy-') ? it.minus('Groovy-') : it
}
def actual = trimPrefix("Groovy-Tutorials at Baeldung")
def expected = "Tutorials at Baeldung"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemoved_thenReturnTrue() {
String prefix = "groovy-"
String trimPrefix = "Groovy-Tutorials at Baeldung"
def actual;
if(trimPrefix.startsWithIgnoreCase(prefix)) {
actual = trimPrefix.substring(prefix.length())
}
def expected = "Tutorials at Baeldung"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemovedUsingRegex_thenReturnTrue() {
def regex = ~"^([Gg])roovy-"
String trimPrefix = "Groovy-Tutorials at Baeldung"
String actual = trimPrefix - regex
def expected = "Tutorials at Baeldung"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemovedUsingReplaceFirst_thenReturnTrue() {
def regex = ~"^groovy"
String trimPrefix = "groovyTutorials at Baeldung's groovy page"
String actual = trimPrefix.replaceFirst(regex, "")
def expected = "Tutorials at Baeldung's groovy page"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemovedUsingReplaceAll_thenReturnTrue() {
String trimPrefix = "groovyTutorials at Baeldung groovy"
String actual = trimPrefix.replaceAll(/^groovy/, "")
def expected = "Tutorials at Baeldung groovy"
Assert.assertEquals(expected, actual)
}
}

View File

@ -7,7 +7,7 @@ import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
public class AppUnitTest
extends TestCase
{
/**
@ -15,7 +15,7 @@ public class AppTest
*
* @param testName name of the test case
*/
public AppTest( String testName )
public AppUnitTest(String testName )
{
super( testName );
}
@ -25,7 +25,7 @@ public class AppTest
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
return new TestSuite( AppUnitTest.class );
}
/**

View File

@ -5,7 +5,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
public class StringAPITest {
public class StringAPIUnitTest {
@Test
public void whenPositiveArgument_thenReturnIndentedString() {

View File

@ -7,7 +7,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class PersonTest {
public class PersonUnitTest {
@Test
public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() {

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

@ -44,6 +44,16 @@
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
<build>
@ -77,6 +87,7 @@
<maven.compiler.target>1.9</maven.compiler.target>
<guava.version>25.1-jre</guava.version>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-collections3.version>3.2.2</commons-collections3.version>
</properties>
</project>

View File

@ -17,7 +17,7 @@ import org.junit.Test;
/**
* Test case for the {@link MethodHandles} API
*/
public class MethodHandlesTest {
public class MethodHandlesUnitTest {
@Test
public void givenConcatMethodHandle_whenInvoked_thenCorrectlyConcatenated() throws Throwable {

View File

@ -6,3 +6,4 @@ This module contains complete guides about arrays in Java
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)

View File

@ -13,3 +13,4 @@
- [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)

View File

@ -0,0 +1,103 @@
package com.baeldung.collections.removeallperformance;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.RandomStringUtils;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import com.baeldung.collections.containsperformance.Employee;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5)
public class HashSetBenchmark {
@State(Scope.Thread)
public static class MyState {
private Set<Employee> employeeSet1 = new HashSet<>();
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() {
for (long i = 0; i < set1Size; i++) {
employeeSet1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < list1Size; i++) {
employeeList1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < set2Size; i++) {
employeeSet2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
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)));
}
}
}
@Benchmark
public boolean given_SizeOfHashsetGreaterThanSizeOfCollection_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) {
return state.employeeSet1.removeAll(state.employeeList1);
}
@Benchmark
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())
.threads(1)
.forks(1)
.shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server")
.build();
new Runner(options).run();
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.collections.hashset;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
class HashSetUnitTest {
@Test
void whenRemoveAllFromHashset_thenRemovesAllElementsFromHashsetThatArePresentInCollection() {
Set<Integer> set = new HashSet<>();
Collection<Integer> collection = new ArrayList<>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
collection.add(1);
collection.add(3);
set.removeAll(collection);
assertEquals(2, set.size());
Integer[] actualElements = new Integer[set.size()];
Integer[] expectedElements = new Integer[] { 2, 4 };
assertArrayEquals(expectedElements, set.toArray(actualElements));
}
}

View File

@ -15,21 +15,24 @@ import org.junit.Test;
public class MapFirstPairUnitTest {
private Map.Entry<Integer, String> getFirstPairUsingIterator(Map<Integer, String> map) {
if (map == null || map.size() == 0)
if (map == null || map.size() == 0) {
return null;
}
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet()
.iterator();
if (iterator.hasNext())
if (iterator.hasNext()) {
return iterator.next();
}
return null;
}
private Map.Entry<Integer, String> getFirstPairUsingStream(Map<Integer, String> map) {
if (map == null || map.size() == 0)
if (map == null || map.size() == 0) {
return null;
}
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();

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

@ -1,6 +1,8 @@
package com.baeldung.date;
import static org.junit.Assert.assertEquals;
import org.joda.time.Days;
import org.joda.time.Minutes;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@ -16,7 +18,7 @@ import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import static org.junit.Assert.*;
public class DateDiffUnitTest {
@ -29,18 +31,39 @@ public class DateDiffUnitTest {
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
LocalDate now = LocalDate.now();
LocalDate sixDaysBehind = now.minusDays(6);
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenWorks() {
LocalDate aDate = LocalDate.of(2020, 9, 11);
LocalDate sixDaysBehind = aDate.minusDays(6);
Period period = Period.between(now, sixDaysBehind);
Period period = Period.between(aDate, sixDaysBehind);
int diff = Math.abs(period.getDays());
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenDoesNotWork() {
LocalDate aDate = LocalDate.of(2020, 9, 11);
LocalDate sixtyDaysBehind = aDate.minusDays(60);
Period period = Period.between(aDate, sixtyDaysBehind);
int diff = Math.abs(period.getDays());
//not equals
assertNotEquals(60, diff);
}
@Test
public void givenTwoDatesInJava8_whenUsingPeriod_thenWeGet0Year1Month29Days() {
LocalDate aDate = LocalDate.of(2020, 9, 11);
LocalDate sixtyDaysBehind = aDate.minusDays(60);
Period period = Period.between(aDate, sixtyDaysBehind);
int years = Math.abs(period.getYears());
int months = Math.abs(period.getMonths());
int days = Math.abs(period.getDays());
assertArrayEquals(new int[] { 0, 1, 29 }, new int[] { years, months, days });
}
@Test
@ -51,7 +74,7 @@ public class DateDiffUnitTest {
Duration duration = Duration.between(now, sixMinutesBehind);
long diff = Math.abs(duration.toMinutes());
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
@ -61,7 +84,7 @@ public class DateDiffUnitTest {
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
assertEquals(diff, 10);
assertEquals(10, diff);
}
@Test
@ -69,9 +92,9 @@ public class DateDiffUnitTest {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
.minusDays(6);
.minusDays(6);
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
@ -81,7 +104,7 @@ public class DateDiffUnitTest {
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
assertEquals(diff, 10);
assertEquals(10, diff);
}
@Test
@ -89,10 +112,9 @@ public class DateDiffUnitTest {
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
org.joda.time.Period period = new org.joda.time.Period(now, sixDaysBehind);
long diff = Math.abs(period.getDays());
long diff = Math.abs(Days.daysBetween(now, sixDaysBehind).getDays());
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
@ -100,8 +122,9 @@ public class DateDiffUnitTest {
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
org.joda.time.Period period = new org.joda.time.Period(now, sixMinutesBehind);
long diff = Math.abs(period.getDays());
long diff = Math.abs(Minutes.minutesBetween(now, sixMinutesBehind).getMinutes());
assertEquals(6, diff);
}
@Test
@ -111,6 +134,6 @@ public class DateDiffUnitTest {
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
assertEquals(diff, 6);
assertEquals(6, diff);
}
}
}

View File

@ -6,7 +6,7 @@ import org.junit.jupiter.api.Test;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
public class TimestampToStringConverterTest {
public class TimestampToStringConverterUnitTest {
@Test
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {

View File

@ -1,3 +1,5 @@
### Relevant Articles:
- [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)

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,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

@ -9,4 +9,7 @@ This module contains articles about core Java input and output (IO)
- [Check If a File or Directory Exists in Java](https://www.baeldung.com/java-file-directory-exists)
- [Copy a Directory in Java](https://www.baeldung.com/java-copy-directory)
- [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

@ -0,0 +1,61 @@
package com.baeldung.lastmodifiedfile;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Optional;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.FileFilterUtils;
public class LastModifiedFileApp {
public static File findUsingIOApi(String sdir) {
File dir = new File(sdir);
if (dir.isDirectory()) {
Optional<File> opFile = Arrays.stream(dir.listFiles(File::isFile))
.max((f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()));
if (opFile.isPresent()) {
return opFile.get();
}
}
return null;
}
public static Path findUsingNIOApi(String sdir) throws IOException {
Path dir = Paths.get(sdir);
if (Files.isDirectory(dir)) {
Optional<Path> opPath = Files.list(dir)
.filter(p -> !Files.isDirectory(p))
.sorted((p1, p2) -> Long.valueOf(p2.toFile().lastModified())
.compareTo(p1.toFile().lastModified()))
.findFirst();
if (opPath.isPresent()) {
return opPath.get();
}
}
return null;
}
public static File findUsingCommonsIO(String sdir) {
File dir = new File(sdir);
if (dir.isDirectory()) {
File[] dirFiles = dir.listFiles((FileFilter) FileFilterUtils.fileFileFilter());
if (dirFiles != null && dirFiles.length > 0) {
Arrays.sort(dirFiles, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
return dirFiles[0];
}
}
return null;
}
}

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

@ -4,6 +4,7 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
@ -20,8 +21,8 @@ public class DirectoryEmptinessUnitTest {
}
@Test
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException {
Path aFile = Paths.get(getClass().getResource("/notDir.txt").getPath());
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException, URISyntaxException {
Path aFile = Paths.get(getClass().getResource("/notDir.txt").toURI());
assertThat(isEmpty(aFile)).isFalse();
}

View File

@ -4,10 +4,7 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.*;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertFalse;
@ -47,8 +44,18 @@ public class ExistenceUnitTest {
public void givenSymbolicLink_whenTargetDoesNotExists_thenFollowOrNotBasedOnTheOptions() throws IOException {
Path target = Files.createTempFile("baeldung", "target");
Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt());
Path symbolicLink = null;
try {
symbolicLink = Files.createSymbolicLink(symbol, target);
} catch (FileSystemException ex) {
System.out.println("Your OS security policy prevents the current user from creating symbolic links.\n" +
"Most probably you're running Windows with UAC.\n" +
"If this is the case, please see - https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links\n" +
"You must change your security settings to run this test under Windows.");
return;
}
Path symbolicLink = Files.createSymbolicLink(symbol, target);
assertTrue(Files.exists(symbolicLink));
assertTrue(Files.isSymbolicLink(symbolicLink));
assertFalse(Files.isSymbolicLink(target));

View File

@ -0,0 +1,78 @@
package com.baeldung.lastmodifiedfile;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class LastModifiedFileAppUnitTest {
private final static String SOURCEDIRECTORY = "src/test/resources/lastmodfiles";
@BeforeAll
public static void setUpFiles() throws IOException, InterruptedException {
File srcDir = new File(SOURCEDIRECTORY);
if (!srcDir.exists()) {
srcDir.mkdir();
}
FileUtils.cleanDirectory(srcDir);
File file01 = new File(SOURCEDIRECTORY + "/file01.txt");
file01.createNewFile();
Thread.sleep(2000);
File file02 = new File(SOURCEDIRECTORY + "/file02.txt");
file02.createNewFile();
Thread.sleep(2000);
File file03 = new File(SOURCEDIRECTORY + "/file03.txt");
file03.createNewFile();
Thread.sleep(2000);
Files.write(Paths.get(SOURCEDIRECTORY + "/file02.txt"), "Hello File02".getBytes());
}
@Test
public void givenDirectory_whenUsingIoApi_thenFindLastModfile() throws IOException {
File lastModFile = LastModifiedFileApp.findUsingIOApi(SOURCEDIRECTORY);
assertThat(lastModFile).isNotNull();
assertThat(lastModFile.getName()).isEqualTo("file02.txt");
}
@Test
public void givenDirectory_whenUsingNioApi_thenFindLastModfile() throws IOException {
Path lastModPath = LastModifiedFileApp.findUsingNIOApi(SOURCEDIRECTORY);
assertThat(lastModPath).isNotNull();
assertThat(lastModPath.toFile().getName()).isEqualTo("file02.txt");
}
@Test
public void givenDirectory_whenUsingApacheCommons_thenFindLastModfile() throws IOException {
File lastModFile = LastModifiedFileApp.findUsingCommonsIO(SOURCEDIRECTORY);
assertThat(lastModFile).isNotNull();
assertThat(lastModFile.getName()).isEqualTo("file02.txt");
}
@AfterAll
public static void cleanUp() throws IOException {
File srcDir = new File(SOURCEDIRECTORY);
FileUtils.deleteDirectory(srcDir);
}
}

View File

@ -4,6 +4,7 @@ import org.apache.commons.io.FileUtils;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -66,10 +67,16 @@ public class TemporaryDirectoriesUnitTest {
@Test
public void givenTempDirWithPrefixWithFileAttrs_whenCreatePlainJava_thenAttributesAreSet() throws IOException {
final FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------"));
boolean isPosix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs);
assertThat(tmpdir.toFile().getPath()).startsWith("target");
assertThat(tmpdir.toFile().canWrite()).isFalse();
if(!isPosix){
System.out.println("You must be under a Posix Compliant Filesystem to run this test.");
} else {
final FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------"));
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs);
assertThat(tmpdir.toFile().getPath()).startsWith("target");
assertThat(tmpdir.toFile().canWrite()).isFalse();
}
}
}

View File

@ -17,7 +17,7 @@
<dependencies>
<dependency>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule</artifactId>
<artifactId>servicemodule1</artifactId>
<version>${servicemodule.version}</version>
</dependency>
</dependencies>

View File

@ -4,7 +4,8 @@
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>servicemodule</artifactId>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule1</artifactId>
<packaging>jar</packaging>
<parent>

View File

@ -17,7 +17,7 @@
<dependencies>
<dependency>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule</artifactId>
<artifactId>servicemodule2</artifactId>
<version>${servicemodule.version}</version>
</dependency>
</dependencies>

View File

@ -4,7 +4,8 @@
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>servicemodule</artifactId>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule2</artifactId>
<version>1.0</version>
<parent>

View File

@ -5,4 +5,6 @@ This module contains articles about core features in the Java language
- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom)
- [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)
- [[<-- 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,5 @@
package com.baeldung.getclassobject;
public class Animal {
protected int numberOfEyes;
}

View File

@ -0,0 +1,4 @@
package com.baeldung.getclassobject;
public class Monkey extends Animal {
}

View File

@ -0,0 +1,4 @@
package com.baeldung.getclassobject;
public abstract class SomeAbstractClass {
}

View File

@ -0,0 +1,4 @@
package com.baeldung.getclassobject;
interface SomeInterface {
}

View File

@ -0,0 +1,9 @@
package com.baeldung.getclassobject;
public class SomeUtils {
private SomeUtils() {
throw new RuntimeException("This Util class is not allowed to be instantiated!");
}
// public static utilMethods
// ...
}

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);
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.getclassobject;
import org.junit.Test;
import static org.junit.Assert.*;
public class GetClassObjectUnitTest {
@Test
public void givenObjectAndType_whenGettingClassObject_thenTwoMethodsHaveTheSameResult() {
String str = "I am an object of the String class";
Class fromStrObject = str.getClass();
Class clazz = String.class;
assertSame(fromStrObject, clazz);
}
@Test
public void givenClassInheritance_whenGettingRuntimeTypeAndStaticType_thenGetDifferentResult() {
Animal animal = new Monkey();
Class runtimeType = animal.getClass();
Class staticType = Animal.class;
//Not equals
assertNotEquals(staticType, runtimeType);
Class monkeyClass = Monkey.class;
assertSame(runtimeType, monkeyClass);
}
@Test
public void givenPrimitiveType_whenGettingClassObject_thenOnlyStaticTypeWorks() {
int number = 7;
// Class numberClass = number.getClass(); <-- compilation error
Class intType = int.class;
assertNotNull(intType);
assertEquals("int", intType.getName());
assertTrue(intType.isPrimitive());
}
@Test
public void givenTypeCannotInstantiate_whenGetTypeStatically_thenGetTypesSuccefully() {
Class interfaceType = SomeInterface.class;
Class abstractClassType = SomeAbstractClass.class;
Class utilClassType = SomeUtils.class;
assertNotNull(interfaceType);
assertTrue(interfaceType.isInterface());
assertEquals("SomeInterface", interfaceType.getSimpleName());
assertNotNull(abstractClassType);
assertEquals("SomeAbstractClass", abstractClassType.getSimpleName());
assertNotNull(utilClassType);
assertEquals("SomeUtils", utilClassType.getSimpleName());
}
}

View File

@ -13,4 +13,5 @@
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging)
- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication)
- [Largest Power of 2 That Is Less Than the Given Number](https://www.baeldung.com/java-largest-power-of-2-less-than-number)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math)

View File

@ -9,3 +9,4 @@ This module contains articles about methods in Java
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
- [Guide to hashCode() in Java](https://www.baeldung.com/java-hashcode)
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)
- [Does a Methods Signature Include the Return Type in Java?](https://www.baeldung.com/java-method-signature-return-type)

View File

@ -0,0 +1,72 @@
package com.baeldung.signature;
import java.io.Serializable;
public class OverloadingErrors<T extends Serializable> {
public void print() {
System.out.println("Signature is: print()");
}
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from return type
public int print() {
System.out.println("Signature is: print()");
return 0;
}
*/
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from modifiers
private final void print() {
System.out.println("Signature is: print()");
}
*/
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from thrown exception declaration
public void print() throws IllegalStateException {
System.out.println("Signature is: print()");
throw new IllegalStateException();
}
*/
public void print(int parameter) {
System.out.println("Signature is: print(int)");
}
/*
// Uncommenting this method will lead to a compilation error: java: method print(int) is already defined in class
// The method signature is independent from parameter names
public void print(int anotherParameter) {
System.out.println("Signature is: print(int)");
}
*/
public void printElement(T t) {
System.out.println("Signature is: printElement(T)");
}
/*
// Uncommenting this method will lead to a compilation error: java: name clash: printElement(java.io.Serializable) and printElement(T) have the same erasure
// Even though the signatures appear different, the compiler cannot statically bind the correct method after type erasure
public void printElement(Serializable o) {
System.out.println("Signature is: printElement(Serializable)");
}
*/
public void print(Object... parameter) {
System.out.println("Signature is: print(Object...)");
}
/*
// Uncommenting this method will lead to a compilation error: java cannot declare both sum(Object...) and sum(Object[])
// Even though the signatures appear different, after compilation they both resolve to sum(Object[])
public void print(Object[] parameter) {
System.out.println("Signature is: print(Object[])");
}
*/
}

View File

@ -0,0 +1,46 @@
package com.baeldung.signature;
public class StaticBinding {
public Number sum(Integer term1, Integer term2) {
System.out.println("Adding integers");
return term1 + term2;
}
public Number sum(Number term1, Number term2) {
System.out.println("Adding numbers");
return term1.doubleValue() + term2.doubleValue();
}
public Number sum(Object term1, Object term2) {
System.out.println("Adding objects");
return term1.hashCode() + term2.hashCode();
}
public Number sum(Object term1, Object... term2) {
System.out.println("Adding variable arguments: " + term2.length);
int result = term1.hashCode();
for (Object o : term2) {
result += o.hashCode();
}
return result;
}
public static void main(String[] args) {
StaticBinding obj = new StaticBinding();
obj.sum(2, 3); // "Adding integers" due to auto-boxing from int to Integer
obj.sum(Integer.valueOf(2), Integer.valueOf(3)); // "Adding integers" due to exact parameter types
obj.sum(2, 0x1); // "Adding integers" due to type promotion from byte to int
obj.sum((Number) 2, (Number) 3); // "Adding numbers" due to explicit cast to Number
obj.sum(2.0d, 3.0d); // "Adding numbers" due to auto-boxing from double to Double
obj.sum(Float.valueOf(2), Float.valueOf(3)); // "Adding numbers" due to polimorphism
obj.sum((Object) 2, (Object) 3); // "Adding objects" due to explicit cast to Object
obj.sum(2, "John"); // "Adding objects" due to polimorphism
obj.sum(new Object(), new Object(), new Object()); // "Adding variable arguments 2"
obj.sum(new Object(), new Object[]{new Object()}); // "Adding variable arguments 1"
}
}

View File

@ -13,4 +13,5 @@ This module contains articles about networking in Java
- [Download a File from an URL in Java](https://www.baeldung.com/java-download-file)
- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception)
- [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address)
- [Sending Emails with Attachments in Java](https://www.baeldung.com/java-send-emails-attachments)
- [[<-- Prev]](/core-java-modules/core-java-networking)

View File

@ -4,7 +4,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CurrentDirectoryFetcherTest {
public class CurrentDirectoryFetcherUnitTest {
private static final String CURRENT_DIR = "core-java-os";

View File

@ -2,3 +2,5 @@
- [Reading the Value of private Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value)
- [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value)
- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static)
- [Checking if a Java Class is abstract Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract)

View File

@ -0,0 +1,15 @@
package com.baeldung.reflection.check.abstractclass;
import java.time.LocalDate;
import java.time.LocalTime;
public abstract class AbstractExample {
public static String getAuthorName() {
return "Umang Budhwar";
}
public abstract LocalDate getLocalDate();
public abstract LocalTime getLocalTime();
}

View File

@ -0,0 +1,19 @@
package com.baeldung.reflection.check.staticmethods;
import java.time.LocalDate;
import java.time.LocalTime;
public class StaticUtility {
public static String getAuthorName() {
return "Umang Budhwar";
}
public static LocalDate getLocalDate() {
return LocalDate.now();
}
public static LocalTime getLocalTime() {
return LocalTime.now();
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.reflection.check.abstractclass;
import java.lang.reflect.Modifier;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class AbstractExampleUnitTest {
@Test
void givenAbstractClass_whenCheckModifierIsAbstract_thenTrue() throws Exception {
Class<AbstractExample> clazz = AbstractExample.class;
Assertions.assertTrue(Modifier.isAbstract(clazz.getModifiers()));
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.reflection.check.staticmethods;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class StaticUtilityUnitTest {
@Test
void whenCheckStaticMethod_ThenSuccess() throws Exception {
Method method = StaticUtility.class.getMethod("getAuthorName", null);
Assertions.assertTrue(Modifier.isStatic(method.getModifiers()));
}
@Test
void whenCheckAllStaticMethods_thenSuccess() {
List<Method> methodList = Arrays.asList(StaticUtility.class.getMethods())
.stream()
.filter(method -> Modifier.isStatic(method.getModifiers()))
.collect(Collectors.toList());
Assertions.assertEquals(3, methodList.size());
}
}

View File

@ -10,4 +10,6 @@ This module contains articles about core Java Security
- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)
- [Checksums in Java](https://www.baeldung.com/java-checksums)
- [How to Read PEM File to Get Public and Private Keys](https://www.baeldung.com/java-read-pem-file-keys)
- [Listing the Available Cipher Algorithms](https://www.baeldung.com/java-list-cipher-algorithms)
- [Get a List of Trusted Certificates in Java](https://www.baeldung.com/java-list-trusted-certificates)
- More articles: [[<-- prev]](/core-java-modules/core-java-security)

View File

@ -3,7 +3,7 @@ package com.baeldung.hashing;
class SHACommonUtils {
public static String bytesToHex(byte[] hash) {
StringBuffer hexString = new StringBuffer();
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (byte h : hash) {
String hex = Integer.toHexString(0xff & h);
if (hex.length() == 1)

View File

@ -0,0 +1,35 @@
package com.baeldung.cipher;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.Provider;
import java.security.Security;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class AvailableCiphersUnitTest {
private final Logger logger = LoggerFactory.getLogger(AvailableCiphersUnitTest.class);
@Test
public void whenGetServices_thenGetAllCipherAlgorithms() {
for (Provider provider : Security.getProviders()) {
for (Provider.Service service : provider.getServices()) {
logger.info(service.getAlgorithm());
}
}
}
@Test
public void whenGetServicesWithFilter_thenGetAllCompatibleCipherAlgorithms() {
List<String> algorithms = Arrays.stream(Security.getProviders())
.flatMap(provider -> provider.getServices().stream())
.filter(service -> "Cipher".equals(service.getType()))
.map(Provider.Service::getAlgorithm)
.collect(Collectors.toList());
algorithms.forEach(logger::info);
}
}

View File

@ -0,0 +1,94 @@
package com.baeldung.trustedcert;
import org.junit.jupiter.api.Test;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class CertificatesUnitTest {
private static final String GODADDY_CA_ALIAS = "godaddyrootg2ca [jdk]";
@Test
public void whenLoadingCacertsKeyStore_thenCertificatesArePresent() throws Exception {
KeyStore keyStore = loadKeyStore();
PKIXParameters params = new PKIXParameters(keyStore);
Set<TrustAnchor> trustAnchors = params.getTrustAnchors();
List<Certificate> certificates = trustAnchors.stream()
.map(TrustAnchor::getTrustedCert)
.collect(Collectors.toList());
assertFalse(certificates.isEmpty());
}
@Test
public void whenLoadingDefaultKeyStore_thenCertificatesArePresent() throws Exception {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore)null);
List<TrustManager> trustManagers = Arrays.asList(trustManagerFactory.getTrustManagers());
List<X509Certificate> certificates = trustManagers.stream()
.filter(X509TrustManager.class::isInstance)
.map(X509TrustManager.class::cast)
.map(trustManager -> Arrays.asList(trustManager.getAcceptedIssuers()))
.flatMap(Collection::stream)
.collect(Collectors.toList());
assertFalse(certificates.isEmpty());
}
@Test
public void whenLoadingKeyStore_thenGoDaddyCALabelIsPresent() throws Exception {
KeyStore keyStore = loadKeyStore();
Enumeration<String> aliasEnumeration = keyStore.aliases();
List<String> aliases = Collections.list(aliasEnumeration);
assertTrue(aliases.contains(GODADDY_CA_ALIAS));
}
@Test
public void whenLoadingKeyStore_thenGoDaddyCertificateIsPresent() throws Exception {
KeyStore keyStore = loadKeyStore();
Certificate goDaddyCertificate = keyStore.getCertificate(GODADDY_CA_ALIAS);
assertNotNull(goDaddyCertificate);
}
private KeyStore loadKeyStore() throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
String relativeCacertsPath = "/lib/security/cacerts".replace("/", File.separator);
String filename = System.getProperty("java.home") + relativeCacertsPath;
FileInputStream is = new FileInputStream(filename);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
String password = "changeit";
keystore.load(is, password.toCharArray());
return keystore;
}
}

View File

@ -20,6 +20,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -20,6 +20,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -38,6 +38,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -33,6 +33,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -18,20 +18,9 @@
<modules>
<module>core-java</module>
<!-- <module>core-java-10</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
<!-- <module>core-java-11</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
<!-- <module>core-java-12</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
<!-- <module>core-java-13</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
<!-- <module>core-java-14</module> --> <!-- We haven't upgraded to java 14.-->
<module>core-java-8</module>
<module>core-java-8-2</module>
<!-- <module>core-java-9</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>core-java-9-improvements</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>core-java-9-jigsaw</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>core-java-9-new-features</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>core-java-9-streams</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>core-java-annotations</module>
<module>core-java-arrays-sorting</module>
@ -51,7 +40,6 @@
<module>core-java-collections-maps</module>
<module>core-java-collections-maps-2</module>
<module>core-java-collections-maps-3</module>
<!-- <module>core-java-collections-set</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
<module>core-java-concurrency-2</module>
<module>core-java-concurrency-advanced</module>
@ -65,10 +53,7 @@
<!--<module>core-java-8-datetime</module>--> <!-- unit test case failure -->
<module>core-java-8-datetime-2</module>
<!-- <module>core-java-date-operations-1</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>core-java-date-operations-2</module>
<!-- We haven't upgraded to java 9. -->
<!-- <module>core-java-datetime-computations</module> <module>core-java-datetime-conversion</module> <module>core-java-datetime-java8</module> <module>core-java-datetime-string</module> -->
<module>core-java-8-datetime</module>
<module>core-java-exceptions</module>
@ -85,7 +70,6 @@
<module>core-java-jar</module>
<module>core-java-jndi</module>
<!-- <module>core-java-jpms</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
<module>core-java-jvm</module>
<module>core-java-jvm-2</module>
@ -113,7 +97,6 @@
<module>core-java-nio-2</module>
<module>core-java-optional</module>
<!--<module>core-java-os</module> --> <!-- We haven't upgraded to java 9. -->
<module>core-java-perf</module>
@ -138,9 +121,6 @@
<module>core-java-sun</module>
<module>core-java-regex</module>
<!-- <module>core-java-time-measurements</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>multimodulemavenproject</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>pre-jpms</module>
</modules>

View File

@ -2,6 +2,6 @@
This module contains articles about core Kotlin collections.
### Relevant articles:
## Relevant articles:
- [Aggregate Operations in Kotlin](https://www.baeldung.com/kotlin/aggregate-operations)

View File

@ -22,30 +22,6 @@ fun main() {
numbers.each { println(random * it) } // capturing the random variable
}
fun namedFunction(): Int {
return 42
}
fun anonymous(): () -> Int {
return fun(): Int {
return 42
}
}
inline fun <T> List<T>.eachIndexed(f: (Int, T) -> Unit) {
for (i in indices) {
f(i, this[i])
}
}
fun <T> List<T>.indexOf(x: T): Int {
eachIndexed { index, value ->
if (value == x) return index
}
return -1
}
/**
* Generates a random number.
*/

View File

@ -12,3 +12,4 @@ This module contains articles about Kotlin core features.
- [Sequences in Kotlin](https://www.baeldung.com/kotlin/sequences)
- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)
- [Exception Handling in Kotlin](https://www.baeldung.com/kotlin/exception-handling)
- [Quick Guide to Kotlin Default and Named Arguments](https://www.baeldung.com/kotlin/default-named-arguments)

View File

@ -0,0 +1,37 @@
package com.baeldung.arguments
fun main() {
// Skip both the connectTimeout and enableRetry arguments
connect("http://www.baeldung.com")
// Skip only the enableRetry argument:
connect("http://www.baeldung.com", 5000)
// Skip only the middle argument connectTimeout
// connect("http://www.baeldung.com", false) // This results in a compiler error
// Because we skipped the connectTimeout argument, we must pass the enableRetry as a named argument
connect("http://www.baeldung.com", enableRetry = false)
// Overriding Functions and Default Arguments
val realConnector = RealConnector()
realConnector.connect("www.baeldung.com")
realConnector.connect()
}
fun connect(url: String, connectTimeout: Int = 1000, enableRetry: Boolean = true) {
println("The parameters are url = $url, connectTimeout = $connectTimeout, enableRetry = $enableRetry")
}
open class AbstractConnector {
open fun connect(url: String = "localhost") {
// function implementation
}
}
class RealConnector : AbstractConnector() {
override fun connect(url: String) {
println("The parameter is url = $url")
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.arguments
fun main() {
resizePane(newSize = 10, forceResize = true, noAnimation = false)
// Swap the order of last two named arguments
resizePane(newSize = 11, noAnimation = false, forceResize = true)
// Named arguments can be passed in any order
resizePane(forceResize = true, newSize = 12, noAnimation = false)
// Mixing Named and Positional Arguments
// Kotlin 1.3 would allow us to name only the arguments after the positional ones
resizePane(20, true, noAnimation = false)
// Using a positional argument in the middle of named arguments (supported from Kotlin 1.4.0)
// resizePane(newSize = 20, true, noAnimation = false)
// Only the last argument as a positional argument (supported from Kotlin 1.4.0)
// resizePane(newSize = 30, forceResize = true, false)
// Use a named argument in the middle of positional arguments (supported from Kotlin 1.4.0)
// resizePane(40, forceResize = true, false)
}
fun resizePane(newSize: Int, forceResize: Boolean, noAnimation: Boolean) {
println("The parameters are newSize = $newSize, forceResize = $forceResize, noAnimation = $noAnimation")
}

View File

@ -104,16 +104,12 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<joda-money.version>1.0.1</joda-money.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
</project>

View File

@ -1,4 +1,3 @@
## Relevant Articles:
- [Introduction to Docker Compose](https://www.baeldung.com/docker-compose)
- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images)

View File

@ -16,11 +16,6 @@
</parent>
<dependencies>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
@ -44,21 +39,8 @@
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<feign.version>9.4.0</feign.version>
<spring-boot-maven-plugin.version>1.4.2.RELEASE</spring-boot-maven-plugin.version>
<feign.version>10.11</feign.version>
</properties>
</project>

View File

@ -6,8 +6,6 @@ import com.baeldung.feign.models.BookResource;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.List;
import java.util.UUID;
@ -22,7 +20,6 @@ import static org.junit.Assert.assertTrue;
* Consumes https://github.com/Baeldung/spring-hypermedia-api
*/
@Slf4j
@RunWith(JUnit4.class)
public class BookClientLiveTest {
private BookClient bookClient;

View File

@ -0,0 +1,3 @@
## Relevant Articles:
- [Passing Command Line Arguments in Gradle](https://www.baeldung.com/gradle-command-line-arguments)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Gradle Source Sets](https://www.baeldung.com/gradle-source-sets)

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