Merge branch 'eugenp:master' into master

This commit is contained in:
press0
2023-04-26 17:02:40 -05:00
committed by GitHub
1040 changed files with 14610 additions and 2156 deletions
+1
View File
@@ -1,3 +1,4 @@
## Relevant Articles
- [Record Patterns in Java 19](https://www.baeldung.com/java-19-record-patterns)
- [Structured Concurrency in Java 19](https://www.baeldung.com/java-structured-concurrency)
- [Possible Root Causes for High CPU Usage in Java](https://www.baeldung.com/java-high-cpu-usage-causes)
@@ -11,4 +11,6 @@ This module contains articles about Java 8 core features
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
- [Create a Simple “Rock-Paper-Scissors” Game in Java](https://www.baeldung.com/java-rock-paper-scissors)
- [VarArgs vs Array Input Parameters in Java](https://www.baeldung.com/varargs-vs-array)
- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)
- [Java Helper vs. Utility Classes](https://www.baeldung.com/java-helper-vs-utility-classes)
- [[<-- Prev]](/core-java-modules/core-java-8)
@@ -2,4 +2,5 @@
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)
- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
- [Parsing Date Strings with Varying Formats](https://www.baeldung.com/java-parsing-dates-many-formats)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
@@ -0,0 +1,20 @@
package com.baeldung.parsingDates;
import java.util.Arrays;
import java.util.List;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
public class SimpleDateTimeFormat {
public static LocalDate parseDate(String date) {
List<String> patternList = Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd");
for (String pattern : patternList) {
try {
return DateTimeFormat.forPattern(pattern).parseLocalDate(date);
} catch (IllegalArgumentException e) {
}
}
return null;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.parsingDates;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
public class SimpleDateTimeFormater {
public static LocalDate parseDate(String date) {
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("[MM/dd/yyyy]" + "[dd-MM-yyyy]" + "[yyyy-MM-dd]"));
DateTimeFormatter dateTimeFormatter = dateTimeFormatterBuilder.toFormatter();
return LocalDate.parse(date, dateTimeFormatter);
}
}
@@ -0,0 +1,18 @@
package com.baeldung.parsingDates;
import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
public class SimpleDateUtils {
public static Date parseDate(String date) {
try {
return DateUtils.parseDateStrictly(date,
new String[]{"yyyy/MM/dd", "dd/MM/yyyy", "yyyy-MM-dd"});
} catch (ParseException ex) {
return null;
}
}
}
@@ -0,0 +1,19 @@
package com.baeldung.parsingDates;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class SimpleParseDate {
public Date parseDate(String dateString, List<String> formatStrings) {
for (String formatString : formatStrings) {
try {
return new SimpleDateFormat(formatString).parse(dateString);
} catch (ParseException e) {
}
}
return null;
}
}
@@ -0,0 +1,43 @@
package com.baeldung.parsingDates;
import com.baeldung.parsingDates.SimpleDateTimeFormat;
import com.baeldung.parsingDates.SimpleDateTimeFormater;
import com.baeldung.parsingDates.SimpleDateUtils;
import com.baeldung.parsingDates.SimpleParseDate;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import org.junit.*;
import static org.junit.Assert.*;
import org.joda.time.LocalDate;
public class SimpleParseDateUnitTest {
@Test
public void whenInvalidInput_thenGettingUnexpectedResult() {
SimpleParseDate simpleParseDate = new SimpleParseDate();
String date = "2022-40-40";
assertEquals("Sat May 10 00:00:00 UTC 2025", simpleParseDate.parseDate(date, Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd")).toString());
}
@Test
public void whenInvalidDate_thenAssertThrows() {
SimpleDateTimeFormater simpleDateTimeFormater = new SimpleDateTimeFormater();
assertEquals(java.time.LocalDate.parse("2022-12-04"), simpleDateTimeFormater.parseDate("2022-12-04"));
assertThrows(DateTimeParseException.class, () -> simpleDateTimeFormater.parseDate("2022-13-04"));
}
@Test
public void whenDateIsCorrect_thenParseCorrect() {
SimpleDateUtils simpleDateUtils = new SimpleDateUtils();
assertNull(simpleDateUtils.parseDate("53/10/2014"));
assertEquals("Wed Sep 10 00:00:00 UTC 2014", simpleDateUtils.parseDate("10/09/2014").toString());
}
@Test
public void whenDateIsCorrect_thenResultCorrect() {
SimpleDateTimeFormat simpleDateTimeFormat = new SimpleDateTimeFormat();
assertNull(simpleDateTimeFormat.parseDate("53/10/2014"));
assertEquals(LocalDate.parse("2014-10-10"), simpleDateTimeFormat.parseDate("2014-10-10"));
}
}
@@ -8,5 +8,5 @@ This module contains articles about Project Jigsaw and the Java Platform Module
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api)
- [Java 9 Illegal Reflective Access Warning](https://www.baeldung.com/java-illegal-reflective-access)
- [Java Modularity and Unit Testing](https://www.baeldung.com/java-modularity-unit-testing)
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
javac -d mods/com.baeldung.library.core $(find library-core/src/main -name "*.java")
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
javac --class-path outDir/library-core/:\
libs/junit-jupiter-engine-5.9.2.jar:\
libs/junit-platform-engine-1.9.2.jar:\
libs/apiguardian-api-1.1.2.jar:\
libs/junit-jupiter-params-5.9.2.jar:\
libs/junit-jupiter-api-5.9.2.jar:\
libs/opentest4j-1.2.0.jar:\
libs/junit-platform-commons-1.9.2.jar \
-d outDir/library-test library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
javac --class-path libs/junit-jupiter-engine-5.9.2.jar:\
libs/junit-platform-engine-1.9.2.jar:\
libs/apiguardian-api-1.1.2.jar:\
libs/junit-jupiter-params-5.9.2.jar:\
libs/junit-jupiter-api-5.9.2.jar:\
libs/opentest4j-1.2.0.jar:\
libs/junit-platform-commons-1.9.2.jar \
-d outDir/library-core \
library-core/src/main/java/com/baeldung/library/core/Book.java \
library-core/src/main/java/com/baeldung/library/core/Library.java \
library-core/src/main/java/com/baeldung/library/core/Main.java \
library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
javac --class-path libs/junit-jupiter-engine-5.9.2.jar:\
libs/junit-platform-engine-1.9.2.jar:\
libs/apiguardian-api-1.1.2.jar:\
libs/junit-jupiter-params-5.9.2.jar:\
libs/junit-jupiter-api-5.9.2.jar:\
libs/opentest4j-1.2.0.jar:\
libs/junit-platform-commons-1.9.2.jar \
-d outDir/library-core \
library-core/src/main/java/com/baeldung/library/core/Book.java \
library-core/src/main/java/com/baeldung/library/core/Library.java \
library-core/src/main/java/com/baeldung/library/core/Main.java
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
javac --module-path mods:libs -d mods/com.baeldung.library.test $(find library-test/src/test -name "*.java")
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
wget -P libs/ https://repo1.maven.org/maven2/org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-commons/1.9.2/junit-platform-commons-1.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-engine/1.9.2/junit-platform-engine-1.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-reporting/1.9.2/junit-platform-reporting-1.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-console/1.9.2/junit-platform-console-1.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/1.9.2/junit-platform-launcher-1.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/jupiter/junit-jupiter-engine/5.9.2/junit-jupiter-engine-5.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/jupiter/junit-jupiter-params/5.9.2/junit-jupiter-params-5.9.2.jar
@@ -0,0 +1,55 @@
<?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>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>core-java-9-jigsaw</artifactId>
<version>0.2-SNAPSHOT</version>
</parent>
<artifactId>library-core</artifactId>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>9</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<useModulePath>false</useModulePath>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,52 @@
package com.baeldung.library.core;
import java.util.Objects;
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
@Override
public String toString() {
return "Book [title=" + title + ", author=" + author + "]";
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Book book = (Book) o;
if (!Objects.equals(title, book.title)) {
return false;
}
return Objects.equals(author, book.author);
}
@Override
public int hashCode() {
int result = title != null ? title.hashCode() : 0;
result = 31 * result + (author != null ? author.hashCode() : 0);
return result;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.library.core;
import java.util.ArrayList;
import java.util.List;
public class Library {
private List<Book> books = new ArrayList<>();
public void addBook(Book book) {
books.add(book);
}
public List<Book> getBooks() {
return books;
}
void removeBook(Book book) {
books.remove(book);
}
protected void removeBookByAuthor(String author) {
books.removeIf(book -> book.getAuthor().equals(author));
}
}
@@ -0,0 +1,16 @@
package com.baeldung.library.core;
public class Main {
public static void main(String[] args) {
Library library = new Library();
library.addBook(new Book("The Lord of the Rings", "J.R.R. Tolkien"));
library.addBook(new Book("The Hobbit", "J.R.R. Tolkien"));
library.addBook(new Book("The Silmarillion", "J.R.R. Tolkien"));
library.addBook(new Book("The Chronicles of Narnia", "C.S. Lewis"));
library.addBook(new Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis"));
System.out.println("Welcome to our library!");
System.out.println("We have the following books:");
library.getBooks().forEach(System.out::println);
}
}
@@ -0,0 +1,3 @@
module com.baeldung.library.core {
exports com.baeldung.library.core;
}
@@ -0,0 +1,47 @@
package com.baeldung.library.core;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class LibraryUnitTest {
@Test
void givenEmptyLibrary_whenAddABook_thenLibraryHasOneBook() {
Library library = new Library();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
library.addBook(theLordOfTheRings);
int expected = 1;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
@Test
void givenTheLibraryWithABook_whenRemoveABook_thenLibraryIsEmpty() {
Library library = new Library();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
library.addBook(theLordOfTheRings);
library.removeBook(theLordOfTheRings);
int expected = 0;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
@Test
void givenTheLibraryWithSeveralBook_whenRemoveABookByAuthor_thenLibraryHasNoBooksByTheAuthor() {
Library library = new Library();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
Book theHobbit = new Book("The Hobbit", "J.R.R. Tolkien");
Book theSilmarillion = new Book("The Silmarillion", "J.R.R. Tolkien");
Book theHungerGames = new Book("The Hunger Games", "Suzanne Collins");
library.addBook(theLordOfTheRings);
library.addBook(theHobbit);
library.addBook(theSilmarillion);
library.addBook(theHungerGames);
library.removeBookByAuthor("J.R.R. Tolkien");
int expected = 1;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
}
@@ -0,0 +1,53 @@
package com.baeldung.library.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.baeldung.library.core.Book;
import com.baeldung.library.core.Library;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
class LibraryUnitTest {
@Test
void givenEmptyLibrary_whenAddABook_thenLibraryHasOneBook() {
Library library = new Library();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
library.addBook(theLordOfTheRings);
int expected = 1;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
@Test
void givenTheLibraryWithABook_whenRemoveABook_thenLibraryIsEmpty()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Library library = new Library();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
library.addBook(theLordOfTheRings);
Method removeBook = Library.class.getDeclaredMethod("removeBook", Book.class);
removeBook.setAccessible(true);
removeBook.invoke(library, theLordOfTheRings);
int expected = 0;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
@Test
void givenTheLibraryWithSeveralBook_whenRemoveABookByAuthor_thenLibraryHasNoBooksByTheAuthor() {
TestLibrary library = new TestLibrary();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
Book theHobbit = new Book("The Hobbit", "J.R.R. Tolkien");
Book theSilmarillion = new Book("The Silmarillion", "J.R.R. Tolkien");
Book theHungerGames = new Book("The Hunger Games", "Suzanne Collins");
library.addBook(theLordOfTheRings);
library.addBook(theHobbit);
library.addBook(theSilmarillion);
library.addBook(theHungerGames);
library.removeBookByAuthor("J.R.R. Tolkien");
int expected = 1;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.library.test;
import com.baeldung.library.core.Library;
public class TestLibrary extends Library {
@Override
public void removeBookByAuthor(final String author) {
super.removeBookByAuthor(author);
}
}
@@ -0,0 +1,5 @@
module com.baeldung.library.test {
requires com.baeldung.library.core;
requires org.junit.jupiter.api;
opens com.baeldung.library.test to org.junit.platform.commons;
}
@@ -5,6 +5,10 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-9-jigsaw</artifactId>
<name>core-java-9-jigsaw</name>
<packaging>pom</packaging>
<modules>
<module>library-core</module>
</modules>
<parent>
<groupId>com.baeldung</groupId>
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
java --module-path mods:libs \
--add-modules com.baeldung.library.core \
--add-opens com.baeldung.library.core/com.baeldung.library.core=org.junit.platform.commons \
--add-reads com.baeldung.library.core=org.junit.jupiter.api \
--patch-module com.baeldung.library.core=outDir/library-test \
--module org.junit.platform.console --select-class com.baeldung.library.core.LibraryUnitTest
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
java --module-path mods --module com.baeldung.library.core/com.baeldung.library.core.Main
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
java --module-path libs \
org.junit.platform.console.ConsoleLauncher \
--classpath ./outDir/library-core \
--select-class com.baeldung.library.core.LibraryUnitTest
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
java --module-path mods:libs \
--add-modules com.baeldung.library.test \
--add-opens com.baeldung.library.core/com.baeldung.library.core=com.baeldung.library.test \
org.junit.platform.console.ConsoleLauncher --select-class com.baeldung.library.test.LibraryUnitTest
@@ -1,84 +1,126 @@
package com.baeldung.map;
import com.google.common.collect.ImmutableMap;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import org.hamcrest.collection.IsMapContaining;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableMap;
public class ImmutableMapUnitTest {
class ImmutableMapUnitTest {
@Test
public void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() {
@Test
void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() {
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(mutableMap);
assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America"));
mutableMap.remove("USA");
assertFalse(unmodifiableMap.containsKey("USA"));
mutableMap.put("Mexico", "North America");
assertTrue(unmodifiableMap.containsKey("Mexico"));
}
@Test
@SuppressWarnings("deprecation")
public void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(mutableMap);
assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America"));
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
mutableMap.remove("USA");
assertFalse(unmodifiableMap.containsKey("USA"));
ImmutableMap<String, String> immutableMap = ImmutableMap.copyOf(mutableMap);
assertTrue(immutableMap.containsKey("USA"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
mutableMap.remove("USA");
assertTrue(immutableMap.containsKey("USA"));
mutableMap.put("Mexico", "North America");
assertFalse(immutableMap.containsKey("Mexico"));
}
@Test
@SuppressWarnings("deprecation")
public void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
mutableMap.put("Mexico", "North America");
assertTrue(unmodifiableMap.containsKey("Mexico"));
}
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
@Test
@SuppressWarnings("deprecation")
void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
ImmutableMap<String, String> immutableMap = ImmutableMap.<String, String>builder()
.putAll(mutableMap)
.put("Costa Rica", "North America")
.build();
assertTrue(immutableMap.containsKey("USA"));
assertTrue(immutableMap.containsKey("Costa Rica"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
mutableMap.remove("USA");
assertTrue(immutableMap.containsKey("USA"));
mutableMap.put("Mexico", "North America");
assertFalse(immutableMap.containsKey("Mexico"));
}
@Test
@SuppressWarnings("deprecation")
public void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
ImmutableMap<String, String> immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America");
assertTrue(immutableMap.containsKey("USA"));
assertTrue(immutableMap.containsKey("Costa Rica"));
ImmutableMap<String, String> immutableMap = ImmutableMap.copyOf(mutableMap);
assertTrue(immutableMap.containsKey("USA"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
mutableMap.remove("USA");
assertTrue(immutableMap.containsKey("USA"));
mutableMap.put("Mexico", "North America");
assertFalse(immutableMap.containsKey("Mexico"));
}
@Test
@SuppressWarnings("deprecation")
void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
ImmutableMap<String, String> immutableMap = ImmutableMap.<String, String>builder()
.putAll(mutableMap)
.put("Costa Rica", "North America")
.build();
assertTrue(immutableMap.containsKey("USA"));
assertTrue(immutableMap.containsKey("Costa Rica"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
mutableMap.remove("USA");
assertTrue(immutableMap.containsKey("USA"));
mutableMap.put("Mexico", "North America");
assertFalse(immutableMap.containsKey("Mexico"));
}
@Test
@SuppressWarnings("deprecation")
void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
ImmutableMap<String, String> immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America");
assertTrue(immutableMap.containsKey("USA"));
assertTrue(immutableMap.containsKey("Costa Rica"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
}
@Test
@SuppressWarnings("deprecation")
void givenGuavaImmutableMapFromOfEntriesMethodwhenModifyEntry_thenThrowUnsupportedOperationException() {
ImmutableMap<Integer, String> immutableMap = ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, "USA"), new AbstractMap.SimpleEntry<>(2, "Canada"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put(2, "Mexico"));
}
@Test
void givenEntrieswhenCreatingGuavaImmutableMapFromOfEntriesMethod_thenCorrect() {
ImmutableMap<Integer, String> immutableMap = ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, "USA"));
assertEquals(1, immutableMap.size());
assertThat(immutableMap, IsMapContaining.hasEntry(1, "USA"));
}
@Test
void givenGuavaImmutableMapFromOfEntriesMethodwhenEntryKeyExists_thenThrowIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, "USA"), new AbstractMap.SimpleEntry<>(1, "Canada")));
}
@Test
void givenGuavaImmutableMapFromOfEntriesMethodwhenEntryKeyIsNull_thenThrowNullPointerException() {
assertThrows(NullPointerException.class, () -> ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(null, "USA")));
}
@Test
void givenGuavaImmutableMapFromOfEntriesMethodwhenEntryValueIsNull_thenThrowNullPointerException() {
assertThrows(NullPointerException.class, () -> ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, null)));
}
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
}
}
@@ -0,0 +1,6 @@
## Core Java Compiler
### Relevant Articles:
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error)
@@ -0,0 +1,29 @@
<?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-compiler</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-compiler</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.google.gdata</groupId>
<artifactId>core</artifactId>
<version>${gdata.version}</version>
</dependency>
</dependencies>
<properties>
<gdata.version>1.47.1</gdata.version>
</properties>
</project>
@@ -0,0 +1,6 @@
## Core Java Documentation
### Relevant Articles:
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
@@ -0,0 +1,41 @@
<?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-documentation</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-documentation</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>${source.version}</source>
<target>${target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- maven plugins -->
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
</properties>
</project>
@@ -5,3 +5,5 @@ This module contains articles about core Java input/output(IO) APIs.
### Relevant Articles:
- [Constructing a Relative Path From Two Absolute Paths in Java](https://www.baeldung.com/java-relative-path-absolute)
- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input)
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
@@ -0,0 +1,85 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.InputMismatchException;
import java.util.Scanner;
import org.junit.jupiter.api.Test;
public class NextLineVsNextIntUnitTest {
@Test
void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() {
String input = "42\n";
//nextLine()
Scanner sc1 = new Scanner(input);
int num1 = Integer.parseInt(sc1.nextLine());
assertEquals(42, num1);
//nextInt()
Scanner sc2 = new Scanner(input);
int num2 = sc2.nextInt();
assertEquals(42, num2);
}
@Test
void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() {
String input = "Nan\n";
//nextLine() -> NumberFormatException
Scanner sc1 = new Scanner(input);
assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine()));
//nextInt() -> InputMismatchException
Scanner sc2 = new Scanner(input);
assertThrows(InputMismatchException.class, sc2::nextInt);
}
@Test
void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() {
String input = "42 is a magic number\n";
//nextInt() to read '42'
Scanner sc2 = new Scanner(input);
int num2 = sc2.nextInt();
assertEquals(42, num2);
// call nextInt() again on "is"
assertThrows(InputMismatchException.class, sc2::nextInt);
String theNextToken = sc2.next();
assertEquals("is", theNextToken);
theNextToken = sc2.next();
assertEquals("a", theNextToken);
}
@Test
void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() {
String input = new StringBuilder().append("42\n")
.append("It is a magic number.\n")
.toString();
//nextLine()
Scanner sc1 = new Scanner(input);
int num1 = Integer.parseInt(sc1.nextLine());
String nextLineText1 = sc1.nextLine();
assertEquals(42, num1);
assertEquals("It is a magic number.", nextLineText1);
//nextInt()
Scanner sc2 = new Scanner(input);
int num2 = sc2.nextInt();
assertEquals(42, num2);
// nextInt() leaves the newline character (\n) behind
String nextLineText2 = sc2.nextLine();
assertEquals("", nextLineText2);
}
}
+2 -3
View File
@@ -4,7 +4,6 @@
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-jpms</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>core-java-jpms</name>
<packaging>pom</packaging>
@@ -15,8 +14,8 @@
</parent>
<modules>
<module>decoupling-pattern1</module>
<module>decoupling-pattern2</module>
<module>service-provider-factory-pattern</module>
<module>service-loader-api-pattern</module>
</modules>
<build>
@@ -8,8 +8,8 @@
<version>1.0</version>
<parent>
<groupId>com.baeldung.decoupling-pattern2</groupId>
<artifactId>decoupling-pattern2</artifactId>
<groupId>com.baeldung.service-loader-api-pattern</groupId>
<artifactId>service-loader-api-pattern</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
@@ -3,8 +3,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>
<groupId>com.baeldung.decoupling-pattern2</groupId>
<artifactId>decoupling-pattern2</artifactId>
<groupId>com.baeldung.service-loader-api-pattern</groupId>
<artifactId>service-loader-api-pattern</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
@@ -8,8 +8,8 @@
<version>1.0</version>
<parent>
<groupId>com.baeldung.decoupling-pattern2</groupId>
<artifactId>decoupling-pattern2</artifactId>
<groupId>com.baeldung.service-loader-api-pattern</groupId>
<artifactId>service-loader-api-pattern</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
@@ -8,8 +8,8 @@
<version>1.0</version>
<parent>
<groupId>com.baeldung.decoupling-pattern2</groupId>
<artifactId>decoupling-pattern2</artifactId>
<groupId>com.baeldung.service-loader-api-pattern</groupId>
<artifactId>service-loader-api-pattern</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
@@ -8,8 +8,8 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.decoupling-pattern1</groupId>
<artifactId>decoupling-pattern1</artifactId>
<groupId>com.baeldung.service-provider-factory-pattern</groupId>
<artifactId>service-provider-factory-pattern</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
@@ -3,8 +3,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>
<groupId>com.baeldung.decoupling-pattern1</groupId>
<artifactId>decoupling-pattern1</artifactId>
<groupId>com.baeldung.service-provider-factory-pattern</groupId>
<artifactId>service-provider-factory-pattern</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
@@ -9,8 +9,8 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.decoupling-pattern1</groupId>
<artifactId>decoupling-pattern1</artifactId>
<groupId>com.baeldung.service-provider-factory-pattern</groupId>
<artifactId>service-provider-factory-pattern</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
@@ -10,4 +10,3 @@
- [Serialize a Lambda in Java](https://www.baeldung.com/java-serialize-lambda)
- [Convert Anonymous Class into Lambda in Java](https://www.baeldung.com/java-from-anonymous-class-to-lambda)
- [When to Use Callable and Supplier in Java](https://www.baeldung.com/java-callable-vs-supplier)
- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)
@@ -10,4 +10,5 @@
- [Create a BMI Calculator in Java](https://www.baeldung.com/java-body-mass-index-calculator)
- [Java Program to Calculate the Standard Deviation](https://www.baeldung.com/java-calculate-standard-deviation)
- [Java Program to Print Pascals Triangle](https://www.baeldung.com/java-pascal-triangle)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)
@@ -23,11 +23,17 @@
<artifactId>javaluator</artifactId>
<version>${javaluator.version}</version>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>${javamoney.moneta.version}</version>
</dependency>
</dependencies>
<properties>
<exp4j.version>0.4.8</exp4j.version>
<javaluator.version>3.0.3</javaluator.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version>
</properties>
</project>
@@ -0,0 +1,98 @@
package com.baeldung.methods;
public class Car {
private final String make;
private final String model;
private final int year;
private final String color;
private final boolean automatic;
private final int numDoors;
private final String features;
private Car(CarBuilder carBuilder) {
this.make = carBuilder.make;
this.model = carBuilder.model;
this.year = carBuilder.year;
this.color = carBuilder.color;
this.automatic = carBuilder.automatic;
this.numDoors = carBuilder.numDoors;
this.features = carBuilder.features;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public String getColor() {
return color;
}
public boolean isAutomatic() {
return automatic;
}
public int getNumDoors() {
return numDoors;
}
public String getFeatures() {
return features;
}
public static class CarBuilder {
private final String make;
private final String model;
private final int year;
private String color = "unknown";
private boolean automatic = false;
private int numDoors = 4;
private String features = "";
public CarBuilder(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public CarBuilder color(String color) {
this.color = color;
return this;
}
public CarBuilder automatic(boolean automatic) {
this.automatic = automatic;
return this;
}
public CarBuilder numDoors(int numDoors) {
this.numDoors = numDoors;
return this;
}
public CarBuilder features(String features) {
this.features = features;
return this;
}
public Car build() {
return new Car(this);
}
}
@Override
public String toString() {
return "Car [make=" + make + ", model=" + model + ", year=" + year + ", color=" + color + ", automatic=" + automatic + ", numDoors=" + numDoors + ", features=" + features + "]";
}
}
@@ -0,0 +1,52 @@
package com.baeldung.methods;
import java.io.Serializable;
public class Motorcycle extends Vehicle implements Serializable {
private static final long serialVersionUID = 5973661295933599929L;
private int year;
private String features = "";
public Motorcycle() {
super();
}
public Motorcycle(String make, String model, String color, int weight, boolean statusNew, int year) {
super(make, model, color, weight, statusNew);
this.year = year;
}
public Motorcycle(Vehicle vehicle, int year) {
super(vehicle);
this.year = year;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public void setFeatures(String features) {
this.features = features;
}
public String getFeatures() {
return features;
}
public void addMotorcycleFeatures(String... features) {
StringBuilder str = new StringBuilder(this.getFeatures());
for (String feature : features) {
if (!str.toString().isEmpty())
str.append(", ");
str.append(feature);
}
this.setFeatures(str.toString());
}
}
@@ -0,0 +1,33 @@
package com.baeldung.methods;
public class Vehicle {
static String defaultValue = "DEFAULT";
private String make = defaultValue;
private String model = defaultValue;
private String color = defaultValue;
private int weight = 0;
private boolean statusNew = true;
public Vehicle() {
super();
}
public Vehicle(String make, String model, String color, int weight, boolean statusNew) {
this.make = make;
this.model = model;
this.color = color;
this.weight = weight;
this.statusNew = statusNew;
}
public Vehicle(Vehicle vehicle) {
this(vehicle.make, vehicle.model, vehicle.color, vehicle.weight, vehicle.statusNew);
}
@Override
public String toString() {
return "Vehicle [make=" + make + ", model=" + model + ", color=" + color + ", weight=" + weight + ", statusNew=" + statusNew + "]";
}
}
@@ -0,0 +1,20 @@
package com.baeldung.methods;
public class VehicleProcessor {
Vehicle processVehicle(String make, String model, String color, int weight, boolean status) {
return new Vehicle(make, model, color, weight, status);
}
Vehicle processVehicle(Vehicle vehicle) {
return new Vehicle(vehicle);
}
Car processCar(Car car) {
return new Car.CarBuilder(car.getMake(), car.getModel(), car.getYear()).color(car.getColor())
.automatic(car.isAutomatic())
.features(car.getFeatures())
.build();
}
}
@@ -0,0 +1,58 @@
package com.baeldung.methods;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class VehicleProcessorUnitTest {
VehicleProcessor vehicleProcessor = new VehicleProcessor();
Vehicle vehicle = new Vehicle("Ford", "Focus", "red", 2200, true);
@Test
void givenAllArguments_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
Vehicle veh = vehicleProcessor.processVehicle("Ford", "Focus", "red", 2200, true);
assertThat(veh.toString()).hasToString(vehicle.toString());
}
@Test
void givenParameterObject_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
Vehicle veh = vehicleProcessor.processVehicle(vehicle);
assertThat(veh.toString()).hasToString(vehicle.toString());
}
@Test
void givenJavaBeanPattern_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
Motorcycle motorcycle = new Motorcycle("Ducati", "Monster", "yellow", 235, true, 2023);
motorcycle.setFeatures("GPS");
vehicleProcessor.processVehicle(motorcycle);
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("GPS");
}
@Test
void givenJavaVarargs_whenMethodCall_thenAssertTheReturnedConcatenatedString() {
Motorcycle motorcycle = new Motorcycle("Ducati", "Monster", "red", 350, true, 2023);
motorcycle.addMotorcycleFeatures("abs");
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs");
motorcycle.addMotorcycleFeatures("navi", "charger");
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs, navi, charger");
motorcycle.addMotorcycleFeatures("wifi", "phone", "satellite");
assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs, navi, charger, wifi, phone, satellite");
}
@Test
void givenJavaBuilderPattern_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
Car car = new Car.CarBuilder("Ford", "Focus", 2023).color("blue")
.automatic(true)
.features("abs, navi, charger, wifi, phone, satellite")
.build();
Car result = vehicleProcessor.processCar(car);
assertThat(result.toString()).hasToString(car.toString());
}
}
@@ -15,9 +15,9 @@
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
@@ -52,11 +52,11 @@
</build>
<properties>
<httpclient.version>4.5.9</httpclient.version>
<angus.mail.version>2.0.1</angus.mail.version>
<async-http-client.version>2.4.5</async-http-client.version>
<jakarta.bind.version>2.3.3</jakarta.bind.version>
<greenmail.version>2.0.0-alpha-3</greenmail.version>
<commons-codec.version>1.15</commons-codec.version>
</properties>
</project>
@@ -21,7 +21,7 @@ public class HttpClient {
this.password = password;
}
public int sendRquestWithAuthHeader(String url) throws IOException {
public int sendRequestWithAuthHeader(String url) throws IOException {
HttpURLConnection connection = null;
try {
connection = createConnection(url);
@@ -34,7 +34,7 @@ public class HttpClient {
}
}
public int sendRquestWithAuthenticator(String url) throws IOException {
public int sendRequestWithAuthenticator(String url) throws IOException {
setAuthenticator();
HttpURLConnection connection = null;
@@ -7,28 +7,28 @@ import org.junit.Test;
public class HttpClientLiveTest {
@Test
public void sendRquestWithAuthHeader() throws Exception {
public void sendRequestWithAuthHeader() throws Exception {
HttpClient httpClient = new HttpClient("user1", "pass1");
int status = httpClient.sendRquestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
int status = httpClient.sendRequestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
assertTrue(isSuccess(status));
}
@Test
public void sendRquestWithAuthHeader_whenIncorrectCredentials_thenNotSuccessful() throws Exception {
public void sendRequestWithAuthHeader_whenIncorrectCredentials_thenNotSuccessful() throws Exception {
HttpClient httpClient = new HttpClient("John", "Smith");
int status = httpClient.sendRquestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
int status = httpClient.sendRequestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
assertTrue(isUnauthorized(status));
}
@Test
public void sendRquestWithAuthenticator() throws Exception {
public void sendRequestWithAuthenticator() throws Exception {
HttpClient httpClient = new HttpClient("user2", "pass2");
int status = httpClient.sendRquestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
int status = httpClient.sendRequestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
assertTrue(isSuccess(status));
}
@@ -37,7 +37,7 @@ public class HttpClientLiveTest {
public void sendRquestWithAuthenticator_whenIncorrectCredentials_thenNotSuccessful() throws Exception {
HttpClient httpClient = new HttpClient("John", "Smith");
int status = httpClient.sendRquestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
int status = httpClient.sendRequestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
assertTrue(isUnauthorized(status));
}
@@ -24,6 +24,30 @@
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>2.22.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies>
<build>
@@ -0,0 +1,53 @@
package com.baeldung.urlquerymanipulation;
import static junit.framework.TestCase.assertEquals;
import java.net.URI;
import java.net.URISyntaxException;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.junit.Test;
import org.springframework.web.util.UriComponentsBuilder;
public class UrlQueryManipulationUnitTest {
@Test
public void whenUsingApacheUriBuilder_thenParametersAreCorrectlyAdded() throws URISyntaxException {
String url = "baeldung.com";
String key = "article";
String value = "alpha";
URI uri = new URIBuilder(url).addParameter(key, value)
.build();
assertEquals("baeldung.com?article=alpha", uri.toString());
}
@Test
public void whenUsingJavaUriBuilder_thenParametersAreCorrectlyAdded() {
String url = "baeldung.com";
String key = "article";
String value = "beta";
URI uri = UriBuilder.fromUri(url)
.queryParam(key, value)
.build();
assertEquals("baeldung.com?article=beta", uri.toString());
}
@Test
public void whenUsingSpringUriComponentsBuilder_thenParametersAreCorrectlyAdded() {
String url = "baeldung.com";
String key = "article";
String value = "charlie";
URI uri = UriComponentsBuilder.fromUriString(url)
.queryParam(key, value)
.build()
.toUri();
assertEquals("baeldung.com?article=charlie", uri.toString());
}
}
@@ -1,7 +1,7 @@
<?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">
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-networking</artifactId>
<name>core-java-networking</name>
@@ -19,6 +19,11 @@
<artifactId>spring-web</artifactId>
<version>${springframework.spring-web.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${apache.httpclient.version}</version>
</dependency>
</dependencies>
<build>
@@ -27,6 +32,7 @@
<properties>
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
<apache.httpclient.version>4.5.14</apache.httpclient.version>
</properties>
</project>
@@ -1,11 +1,19 @@
package com.baeldung.networking.url;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;
import org.springframework.web.util.UriComponentsBuilder;
import com.google.common.collect.ImmutableMap;
public class UrlUnitTest {
@@ -101,4 +109,44 @@ public class UrlUnitTest {
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
}
}
@Test
public void givenUrlParameters_whenBuildUrlWithURIBuilder_thenSuccess() throws URISyntaxException, MalformedURLException {
URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
uriBuilder.setPort(9090);
uriBuilder.addParameter("topic", "java");
uriBuilder.addParameter("version", "8");
URL url = uriBuilder.build().toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}
@Test
public void givenUrlParametersInMap_whenBuildUrlWithURIBuilder_thenSuccess() throws URISyntaxException, MalformedURLException {
Map<String, String> paramMap = ImmutableMap.of("topic", "java", "version", "8");
URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
uriBuilder.setPort(9090);
uriBuilder.addParameters(paramMap.entrySet()
.stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(toList()));
URL url = uriBuilder.build().toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}
@Test
public void givenUrlParameters_whenBuildUrlWithSpringUriComponentsBuilder_thenSuccess() throws MalformedURLException {
URL url = UriComponentsBuilder.newInstance()
.scheme("http")
.host("baeldung.com")
.port(9090)
.path("articles")
.queryParam("topic", "java")
.queryParam("version", "8")
.build()
.toUri()
.toURL();
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}
}
@@ -14,5 +14,4 @@ This module contains articles about core Java non-blocking input and output (IO)
- [What Is the Difference Between NIO and NIO.2?](https://www.baeldung.com/java-nio-vs-nio-2)
- [Guide to ByteBuffer](https://www.baeldung.com/java-bytebuffer)
- [Find Files that Match Wildcard Strings in Java](https://www.baeldung.com/java-files-match-wildcard-strings)
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
- [[<-- Prev]](/core-java-modules/core-java-nio)
@@ -45,8 +45,9 @@ public class EchoServer {
private static void answerWithEcho(ByteBuffer buffer, SelectionKey key) throws IOException {
SocketChannel client = (SocketChannel) key.channel();
client.read(buffer);
if (new String(buffer.array()).trim().equals(POISON_PILL)) {
int r = client.read(buffer);
if (r == -1 || new String(buffer.array()).trim()
.equals(POISON_PILL)) {
client.close();
System.out.println("Not accepting client messages anymore");
} else {
@@ -1,2 +1,4 @@
### Relevant Articles:
- [Java Program to Calculate Pi](https://www.baeldung.com/java-monte-carlo-compute-pi)
- [Convert Integer to Hexadecimal in Java](https://www.baeldung.com/java-convert-int-to-hex)
- More articles: [[<-- prev]](../core-java-numbers-5)
@@ -12,6 +12,21 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-numbers-6</finalName>
<resources>
@@ -22,4 +37,7 @@
</resources>
</build>
<properties>
<commons-codec>1.15</commons-codec>
</properties>
</project>
@@ -0,0 +1,16 @@
package com.baeldung.integertohex;
class IntegerToHex {
static final String digits = "0123456789ABCDEF";
static String integerToHex(int input) {
if (input <= 0)
return "0";
StringBuilder hex = new StringBuilder();
while (input > 0) {
int digit = input % 16;
hex.insert(0, digits.charAt(digit));
input = input / 16;
}
return hex.toString();
}
}
@@ -0,0 +1,75 @@
package com.baeldung.integertohex;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.commons.codec.binary.Hex;
import org.junit.jupiter.api.Test;
class IntegerToHexUnitTest {
@Test
void givenIntegerValue_whenUseRawMethod_thenWillGetHexValue() {
String result = IntegerToHex.integerToHex(1055);
assertEquals("41F", result);
}
@Test
void givenIntegerNegativeValue_whenUseRawMethod_thenZeroValue() {
String result = IntegerToHex.integerToHex(-1055);
assertEquals("0", result);
}
@Test
void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValue() {
String result = String.format("%02x", 255);
assertEquals("ff", result);
}
@Test
void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValueWithLeftZeros() {
String result = String.format("%04x", 255);
assertEquals("00ff", result);
}
@Test
void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValueWithLeftZerosAndUpperLetter() {
String result = String.format("%04X", 255);
assertEquals("00FF", result);
}
@Test
void givenIntegerValue_whenUseIntegerToHexString_thenWillGetHexValue() {
String result = Integer.toHexString(1000);
assertEquals("3e8", result);
}
@Test
void givenIntegerValue_whenUseLongToHexString_thenWillGetHexValue() {
String result = Long.toHexString(255L);
assertEquals("ff", result);
}
@Test
public void givenNegativeIntegerValue_whenUseIntegerToString_thenWillGetHexValue() {
String result = Integer.toString(-1458, 16);
assertEquals("-5b2", result);
}
@Test
public void givenIntegerValue_whenUseIntegerToString_thenWillGetHexValue() {
String result = Integer.toString(1458, 16);
assertEquals("5b2", result);
}
@Test
public void givenLongValue_whenUseLongToString_thenWillGetHexValue() {
String result = Long.toString(158, 16);
assertEquals("9e", result);
}
@Test
public void givenIntegerValue_whenUseApacheCommons_thenWillGetHexSignedValue() {
String result = Hex.encodeHexString(new byte[] { (byte) 254 });
assertEquals("fe", result);
}
}
@@ -0,0 +1 @@
## Relevant Articles
@@ -0,0 +1,16 @@
<?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-perf-2</artifactId>
<name>core-java-perf-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>
@@ -0,0 +1,20 @@
package com.baeldung.highcpu;
import java.util.LinkedList;
import java.util.List;
import java.util.function.IntUnaryOperator;
import java.util.stream.IntStream;
public class Application {
static List<Integer> generateList() {
return IntStream.range(0, 10000000).parallel().map(IntUnaryOperator.identity()).collect(LinkedList::new, List::add, List::addAll);
}
public static void main(String[] args) {
List<Integer> list = generateList();
long start = System.nanoTime();
int value = list.get(9500000);
System.out.printf("Found value %d in %d nanos\n", value, (System.nanoTime() - start));
}
}
@@ -0,0 +1,16 @@
package com.baeldung.jmxterm;
import java.util.UUID;
public abstract class AbstractPlayerMBean implements PlayerMBean{
private final UUID id;
protected AbstractPlayerMBean() {
this.id = UUID.randomUUID();
}
String getId() {
return getName() + id.toString();
}
}
@@ -0,0 +1,42 @@
package com.baeldung.jmxterm;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.Notification;
import javax.management.NotificationBroadcaster;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
public abstract class BroadcastingGuessGame implements NotificationBroadcaster, GuessGameMBean {
private final NotificationBroadcasterSupport broadcaster =
new NotificationBroadcasterSupport();
private long notificationSequence = 0;
private final MBeanNotificationInfo[] notificationInfo;
protected BroadcastingGuessGame() {
this.notificationInfo = new MBeanNotificationInfo[]{
new MBeanNotificationInfo(new String[]{"game"}, Notification.class.getName(), "Game notification")
};
}
protected void notifyAboutWinner(Player winner) {
String message = "Winner is " + winner.getName() + " with score " + winner.getScore();
Notification notification = new Notification("game.winner", this, notificationSequence++, message);
broadcaster.sendNotification(notification);
}
public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) {
broadcaster.addNotificationListener(listener, filter, handback);
}
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
broadcaster.removeNotificationListener(listener);
}
public MBeanNotificationInfo[] getNotificationInfo() {
return notificationInfo;
}
}

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