Merge branch 'master' into BAEL-16646

# Conflicts:
#	java-dates/README.md
#	pom.xml
This commit is contained in:
Alessio Stalla
2019-10-13 09:03:44 +02:00
267 changed files with 1710 additions and 506 deletions

View File

@@ -0,0 +1,72 @@
package com.baeldung.findastring;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.collections4.IteratorUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class FindAStringInGivenList {
public List<String> findUsingLoopWithRegex(String search, List<String> list) {
List<String> matches = new ArrayList<String>();
String pattern = ".*"+search+".*";
Pattern p = Pattern.compile(pattern);
for(String str: list) {
if (p.matcher(str).matches()) {
matches.add(str);
}
}
return matches;
}
public List<String> findUsingLoop(String search, List<String> list) {
List<String> matches = new ArrayList<String>();
for(String str: list) {
if (str.contains(search)) {
matches.add(str);
}
}
return matches;
}
public List<String> findUsingStream(String search, List<String> list) {
List<String> matchingElements =
list.stream()
.filter(str -> str.trim().contains(search))
.collect(Collectors.toList());
return matchingElements;
}
public List<String> findUsingGuava(String search, List<String> list) {
Iterable<String> result = Iterables.filter(list, Predicates.containsPattern(search));
return Lists.newArrayList(result.iterator());
}
public List<String> findUsingCommonsCollection(String search, List<String> list) {
Iterable<String> result = IterableUtils.filteredIterable(list, new org.apache.commons.collections4.Predicate<String>() {
public boolean evaluate(String listElement) {
return listElement.contains(search);
}
});
return IteratorUtils.toList(result.iterator());
}
}

View File

@@ -0,0 +1,62 @@
package com.baeldung.findastring;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class FindAStringInListUnitTest {
private static List<String> list = new ArrayList<>();
static {
list.add("Jack and Jill");
list.add("James and Sarah");
list.add("Sam and Louise");
list.add("Jack");
list.add("");
}
private static FindAStringInGivenList findAStringInGivenList = new FindAStringInGivenList();
@Test
public void givenAString_whenFoundUsingLoopWithRegex_thenReturnList() {
List matchingElements = findAStringInGivenList.findUsingLoopWithRegex("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingLoop_thenReturnList() {
List matchingElements = findAStringInGivenList.findUsingLoop("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingStream_thenReturnList(){
List matchingElements = findAStringInGivenList.findUsingStream("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingCommonsCollection_thenReturnList(){
List matchingElements = findAStringInGivenList.findUsingCommonsCollection("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingGuava_thenReturnList(){
List matchingElements = findAStringInGivenList.findUsingGuava("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
}

View File

@@ -0,0 +1,19 @@
=========
## Core Java Concurrency Advanced Examples
This module contains articles about advanced topics about multithreading with core Java.
### Relevant Articles:
- [Semaphores in Java](https://www.baeldung.com/java-semaphore)
- [Daemon Threads in Java](https://www.baeldung.com/java-daemon-thread)
- [Priority-based Job Scheduling in Java](https://www.baeldung.com/java-priority-job-schedule)
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)
- [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads)
- [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch)
- [Guide to the Fork/Join Framework in Java](https://www.baeldung.com/java-fork-join)
- [Guide to ThreadLocalRandom in Java](https://www.baeldung.com/java-thread-local-random)
- [The Thread.join() Method in Java](https://www.baeldung.com/java-thread-join)
- [Passing Parameters to Java Threads](https://www.baeldung.com/java-thread-parameters)
[[<-- previous]](/core-java-modules/core-java-concurrency-advanced)[[next -->]](/core-java-modules/core-java-concurrency-advanced-3)

View File

@@ -0,0 +1,59 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-concurrency-advanced-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-advanced-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-concurrency-advanced-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@@ -4,6 +4,7 @@ import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class CyclicBarrierResetExample {
@@ -36,6 +37,11 @@ public class CyclicBarrierResetExample {
});
}
es.shutdown();
try {
es.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return updateCount.get();
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.concurrent.daemon;
public class NewThread extends Thread {
public void run() {
long startTime = System.currentTimeMillis();
while (true) {
for (int i = 0; i < 10; i++) {
System.out.println(this.getName() + ": New Thread is running..." + i);
try {
//Wait for one sec so it doesn't print too fast
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// prevent the Thread to run forever. It will finish it's execution after 2 seconds
if (System.currentTimeMillis() - startTime > 2000) {
Thread.currentThread().interrupt();
break;
}
}
}
}

View File

@@ -1,4 +1,4 @@
package com.baeldung.concurrent.parameter;
package com.baeldung.concurrent.parameters;
import java.util.concurrent.Callable;
import java.util.stream.IntStream;

View File

@@ -1,4 +1,4 @@
package com.baeldung.concurrent.parameter;
package com.baeldung.concurrent.parameters;
import java.util.concurrent.Callable;
import java.util.stream.IntStream;

View File

@@ -1,14 +1,13 @@
package com.baeldung.parameters;
package com.baeldung.concurrent.parameters;
import com.baeldung.concurrent.parameter.AverageCalculator;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ParameterizedThreadUnitTest {

View File

@@ -1,4 +1,4 @@
package com.baeldung.java8;
package com.baeldung.forkjoin;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

View File

@@ -0,0 +1,9 @@
=========
## Core Java Concurrency Advanced Examples
This module contains articles about advanced topics about multithreading with core Java.
### Relevant Articles:
[[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@@ -0,0 +1,33 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-concurrency-advanced-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-advanced-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
</dependencies>
<build>
<finalName>core-java-concurrency-advanced-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
</properties>
</project>

View File

@@ -1,26 +0,0 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

View File

@@ -1,25 +1,16 @@
## Core Java Concurrency Advanced Examples
This module contains articles about advanced concurrency in core Java.
This module contains articles about advanced topics about multithreading with core Java.
### Relevant Articles:
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)
- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks)
- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal)
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
- [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers)
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
- [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables)
- [CyclicBarrier in Java](http://www.baeldung.com/java-cyclic-barrier)
- [Guide to the Volatile Keyword in Java](http://www.baeldung.com/java-volatile)
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
- [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule)
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)
- [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads)
- [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch)
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
- [Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)
- [Passing Parameters to Java Threads](https://www.baeldung.com/java-thread-parameters)
- [Introduction to Thread Pools in Java](https://www.baeldung.com/thread-pool-java-and-guava)
- [Guide to CountDownLatch in Java](https://www.baeldung.com/java-countdown-latch)
- [Guide to java.util.concurrent.Locks](https://www.baeldung.com/java-concurrent-locks)
- [An Introduction to ThreadLocal in Java](https://www.baeldung.com/java-threadlocal)
- [LongAdder and LongAccumulator in Java](https://www.baeldung.com/java-longadder-and-longaccumulator)
- [The Dining Philosophers Problem in Java](https://www.baeldung.com/java-dining-philoshophers)
- [Guide to the Java Phaser](https://www.baeldung.com/java-phaser)
- [An Introduction to Atomic Variables in Java](https://www.baeldung.com/java-atomic-variables)
- [CyclicBarrier in Java](https://www.baeldung.com/java-cyclic-barrier)
- [Guide to the Volatile Keyword in Java](https://www.baeldung.com/java-volatile)
- More Articles: [[next -->]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@@ -47,16 +47,6 @@
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
</dependencies>
<build>
@@ -78,8 +68,6 @@
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
</properties>
</project>

View File

@@ -4,6 +4,7 @@ import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class CyclicBarrierCompletionMethodExample {
@@ -35,6 +36,11 @@ public class CyclicBarrierCompletionMethodExample {
});
}
es.shutdown();
try {
es.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return updateCount.get();
}

View File

@@ -12,9 +12,11 @@ public class SemaPhoreDemo {
System.out.println("Number of threads waiting to acquire: " + semaphore.getQueueLength());
if (semaphore.tryAcquire()) {
semaphore.acquire();
try {
// perform some critical operations
semaphore.release();
} finally {
semaphore.release();
}
}
}

View File

@@ -35,9 +35,9 @@ public class MethodReferenceUnitTest {
public void referenceToInstanceMethodOfArbitratyObjectOfParticularType() {
List<Integer> numbers = Arrays.asList(5, 3, 50, 24, 40, 2, 9, 18);
numbers.stream()
.sorted((a, b) -> Integer.compare(a, b));
.sorted((a, b) -> a.compareTo(b));
numbers.stream()
.sorted(Integer::compare);
.sorted(Integer::compareTo);
}
@Test

View File

@@ -5,3 +5,4 @@
### Relevant Articles:
- [Java 8 Math New Methods](https://www.baeldung.com/java-8-math)
- [Java 8 Unsigned Arithmetic Support](https://www.baeldung.com/java-unsigned-arithmetic)
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)

View File

@@ -9,4 +9,9 @@ This module contains articles about Object-oriented programming (OOP) in Java
- [Guide to the this Java Keyword](https://www.baeldung.com/java-this)
- [Java Public Access Modifier](https://www.baeldung.com/java-public-keyword)
- [Composition, Aggregation and Association in Java](https://www.baeldung.com/java-composition-aggregation-association)
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
- [A Guide to Inner Interfaces in Java](https://www.baeldung.com/java-inner-interfaces)
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)
- [Java Interfaces](https://www.baeldung.com/java-interfaces)
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
- [[<-- Prev]](/core-java-modules/core-java-lang-oop-2)

View File

@@ -1,7 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-lang-oop-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-oop-3</name>
@@ -15,6 +14,24 @@
</parent>
<dependencies>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
@@ -23,4 +40,18 @@
</dependency>
</dependencies>
<build>
<finalName>core-java-lang-oop-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@@ -1,4 +1,4 @@
package com.baeldung.interfaces;
package com.baeldung.innerinterfaces;
import java.util.ArrayList;
import java.util.List;

View File

@@ -1,4 +1,4 @@
package com.baeldung.interfaces;
package com.baeldung.innerinterfaces;
public class Customer {
public interface List {

View File

@@ -14,13 +14,13 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.LoggerFactory;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.List;
/**
* Created by madhumita.g on 01-08-2018.
*/

View File

@@ -1,11 +1,13 @@
package com.baeldung.interfaces;
import static org.junit.Assert.assertEquals;
package com.baeldung.innerinterfaces;
import com.baeldung.innerinterfaces.CommaSeparatedCustomers;
import com.baeldung.innerinterfaces.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static org.junit.Assert.assertEquals;
@RunWith(JUnit4.class)
public class InnerInterfaceUnitTest {
@Test

View File

@@ -15,7 +15,7 @@ public class Enclosing {
@Test
public void test() {
Enclosing.StaticNested nested = new Enclosing.StaticNested();
StaticNested nested = new StaticNested();
nested.run();
}
}

View File

@@ -23,7 +23,7 @@ public class NewOuter {
@Test
public void test() {
NewOuter outer = new NewOuter();
NewOuter.InnerClass inner = outer.new InnerClass();
InnerClass inner = outer.new InnerClass();
inner.run();
}

View File

@@ -14,7 +14,7 @@ public class Outer {
@Test
public void test() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
Inner inner = outer.new Inner();
inner.run();
}
}

View File

@@ -1,11 +1,11 @@
package com.baeldung.objects;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class CarUnitTest {
import static org.junit.Assert.*;
public class ObjectsUnitTest {
private Car car;

View File

@@ -3,22 +3,14 @@
This module contains articles about core features in the Java language
### Relevant Articles:
- [Generate equals() and hashCode() with Eclipse](https://www.baeldung.com/java-eclipse-equals-and-hashcode)
- [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
- [Comparator and Comparable in Java](https://www.baeldung.com/java-comparator-comparable)
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
- [A Guide to Inner Interfaces in Java](https://www.baeldung.com/java-inner-interfaces)
- [Recursion In Java](https://www.baeldung.com/java-recursion)
- [A Guide to the finalize Method in Java](https://www.baeldung.com/java-finalize)
- [Quick Guide to java.lang.System](https://www.baeldung.com/java-lang-system)
- [Using Java Assertions](https://www.baeldung.com/java-assert)
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
- [Java Interfaces](https://www.baeldung.com/java-interfaces)
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
- [[More --> ]](/core-java-modules/core-java-lang-2)

View File

@@ -1,4 +1,4 @@
package com.baeldung.java.enumiteration;
package com.baeldung.enums.iteration;
import java.util.stream.Stream;

View File

@@ -1,4 +1,4 @@
package com.baeldung.java.enumiteration;
package com.baeldung.enums.iteration;
import java.util.ArrayList;
import java.util.Arrays;

View File

@@ -1,10 +1,15 @@
package com.baeldung.encoding;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
public class CharacterEncodingExamples {
@@ -29,4 +34,12 @@ public class CharacterEncodingExamples {
}
return buffer.toString();
}
static String decodeText(String input, Charset charset, CodingErrorAction codingErrorAction) throws IOException {
CharsetDecoder charsetDecoder = charset.newDecoder();
charsetDecoder.onMalformedInput(codingErrorAction);
return new BufferedReader(
new InputStreamReader(
new ByteArrayInputStream(input.getBytes()), charsetDecoder)).readLine();
}
}

View File

@@ -1,9 +1,24 @@
package com.baeldung.encoding;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
public class CharacterEncodingExamplesUnitTest {
@@ -58,4 +73,52 @@ public class CharacterEncodingExamplesUnitTest {
"0 0 10001010 10011110 ");
}
@Test
public void givenUTF8String_whenDecodeByUS_ASCII_thenIgnoreMalformedInputSequence() throws IOException {
Assertions.assertEquals("The faade pattern is a software design pattern.", CharacterEncodingExamples.decodeText("The façade pattern is a software design pattern.", StandardCharsets.US_ASCII, CodingErrorAction.IGNORE));
}
@Test
public void givenUTF8String_whenDecodeByUS_ASCII_thenReplaceMalformedInputSequence() throws IOException {
Assertions.assertEquals(
"The fa<66><61>ade pattern is a software design pattern.",
CharacterEncodingExamples.decodeText(
"The façade pattern is a software design pattern.",
StandardCharsets.US_ASCII,
CodingErrorAction.REPLACE));
}
@Test
public void givenUTF8String_whenDecodeByUS_ASCII_thenReportMalformedInputSequence() {
Assertions.assertThrows(
MalformedInputException.class,
() -> CharacterEncodingExamples.decodeText(
"The façade pattern is a software design pattern.",
StandardCharsets.US_ASCII,
CodingErrorAction.REPORT));
}
@Test
public void givenTextFile_whenLoopOverAllCandidateEncodings_thenProduceSuitableCandidateEncodings() {
Path path = Paths.get("src/test/resources/encoding.txt");
List<Charset> allCandidateCharSets = Arrays.asList(
StandardCharsets.US_ASCII, StandardCharsets.UTF_8, StandardCharsets.ISO_8859_1);
List<Charset> suitableCharsets = new ArrayList<>();
allCandidateCharSets.forEach(charset -> {
try {
CharsetDecoder charsetDecoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPORT);
Reader reader = new InputStreamReader(Files.newInputStream(path), charsetDecoder);
BufferedReader bufferedReader = new BufferedReader(reader);
bufferedReader.readLine();
suitableCharsets.add(charset);
} catch (MalformedInputException ignored) {
} catch (IOException ex) {
ex.printStackTrace();
}
});
Assertions.assertEquals(suitableCharsets, Arrays.asList(StandardCharsets.UTF_8, StandardCharsets.ISO_8859_1));
}
}