Merge branch 'master' of github.com:eugenp/tutorials
This commit is contained in:
commit
5aef6d9d6b
|
@ -4,7 +4,7 @@ before_install:
|
|||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
install: skip
|
||||
script: travis_wait 60 mvn -q install -Pdefault-first,default-second
|
||||
script: travis_wait 60 mvn -q install -Pdefault-first,default-second -Dgib.enabled=true
|
||||
|
||||
sudo: required
|
||||
|
||||
|
|
|
@ -17,3 +17,4 @@
|
|||
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
|
||||
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
|
||||
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
|
||||
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
|
||||
|
|
|
@ -4,3 +4,4 @@
|
|||
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
|
||||
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler)
|
||||
|
|
|
@ -33,3 +33,4 @@
|
|||
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
|
||||
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
|
||||
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
||||
- [How to Replace Many if Statements in Java](https://www.baeldung.com/java-replace-if-statements)
|
||||
|
|
|
@ -4,11 +4,13 @@ import java.lang.reflect.Array;
|
|||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
|
@ -194,4 +196,16 @@ public class ArrayOperations {
|
|||
public static <T> T getRandomFromObjectArray(T[] array) {
|
||||
return array[new Random().nextInt(array.length)];
|
||||
}
|
||||
|
||||
public static Integer[] intersectionSimple(final Integer[] a, final Integer[] b){
|
||||
return Stream.of(a).filter(Arrays.asList(b)::contains).toArray(Integer[]::new);
|
||||
}
|
||||
|
||||
public static Integer[] intersectionSet(final Integer[] a, final Integer[] b){
|
||||
return Stream.of(a).filter(Arrays.asList(b)::contains).distinct().toArray(Integer[]::new);
|
||||
}
|
||||
|
||||
public static Integer[] intersectionMultiSet(final Integer[] a, final Integer[] b){
|
||||
return Stream.of(a).filter(new LinkedList<>(Arrays.asList(b))::remove).toArray(Integer[]::new);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,66 @@
|
|||
package com.baeldung.array.operations;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.baeldung.array.operations.ArrayOperations.intersectionMultiSet;
|
||||
import static com.baeldung.array.operations.ArrayOperations.intersectionSet;
|
||||
import static com.baeldung.array.operations.ArrayOperations.intersectionSimple;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class IntersectionUnitTest {
|
||||
private static final Integer[] a = { 1, 3, 2 };
|
||||
private static final Integer[] b = { 4, 3, 2, 4, 2, 3, 4, 4, 3 };
|
||||
private static final Integer[] c = { 1, 3, 2, 3, 3, 2 };
|
||||
|
||||
@Test
|
||||
void whenIntersectionSimpleIsUsed_thenCommonEntriesAreInTheResult() {
|
||||
assertThat(intersectionSimple(a, b)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionSimple(b, a)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSimpleIsUsedWithAnArrayAndItself_thenTheResultIsTheIdentity() {
|
||||
assertThat(intersectionSimple(b, b)).isEqualTo(b);
|
||||
assertThat(intersectionSimple(a, a)).isEqualTo(a);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsed_thenCommonEntriesAreInTheResult() {
|
||||
assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
|
||||
assertThat(intersectionSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasNoDuplicateEntries_ThenTheResultIsTheIdentity() {
|
||||
assertThat(intersectionSet(a, a)).isEqualTo(a);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasDuplicateEntries_ThenTheResultIsNotTheIdentity() {
|
||||
assertThat(intersectionSet(b, b)).isNotEqualTo(b);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMultiSetIsUsed_thenCommonEntriesAreInTheResult() {
|
||||
assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionMultiSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
|
||||
assertThat(intersectionMultiSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionMultiSet(b, c)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
|
||||
assertThat(intersectionMultiSet(c, b)).isEqualTo(new Integer[] { 3, 2, 3, 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionMultiSetIsUsedWithAnArrayAndWithItself_ThenTheResultIsTheIdentity() {
|
||||
assertThat(intersectionMultiSet(b, b)).isEqualTo(b);
|
||||
assertThat(intersectionMultiSet(a, a)).isEqualTo(a);
|
||||
}
|
||||
}
|
|
@ -43,3 +43,11 @@
|
|||
- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist)
|
||||
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
|
||||
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
|
||||
- [Sorting in Java](http://www.baeldung.com/java-sorting)
|
||||
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
|
||||
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
||||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
|
||||
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
||||
- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map)
|
||||
|
|
|
@ -56,6 +56,12 @@
|
|||
<artifactId>commons-exec</artifactId>
|
||||
<version>1.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
@ -67,5 +73,6 @@
|
|||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<eclipse.collections.version>7.1.0</eclipse.collections.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -34,3 +34,4 @@
|
|||
- [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
|
||||
- [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream)
|
||||
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
|
||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||
|
|
|
@ -56,4 +56,5 @@
|
|||
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
|
||||
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
|
||||
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
|
||||
- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
|
||||
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung.constructors;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
class BankAccount {
|
||||
String name;
|
||||
LocalDateTime opened;
|
||||
double balance;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s, %s, %f", this.name, this.opened.toString(), this.balance);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public LocalDateTime getOpened() {
|
||||
return opened;
|
||||
}
|
||||
|
||||
public double getBalance() {
|
||||
return this.balance;
|
||||
}
|
||||
}
|
||||
|
||||
class BankAccountEmptyConstructor extends BankAccount {
|
||||
public BankAccountEmptyConstructor() {
|
||||
this.name = "";
|
||||
this.opened = LocalDateTime.now();
|
||||
this.balance = 0.0d;
|
||||
}
|
||||
}
|
||||
|
||||
class BankAccountParameterizedConstructor extends BankAccount {
|
||||
public BankAccountParameterizedConstructor(String name, LocalDateTime opened, double balance) {
|
||||
this.name = name;
|
||||
this.opened = opened;
|
||||
this.balance = balance;
|
||||
}
|
||||
}
|
||||
|
||||
class BankAccountCopyConstructor extends BankAccount {
|
||||
public BankAccountCopyConstructor(String name, LocalDateTime opened, double balance) {
|
||||
this.name = name;
|
||||
this.opened = opened;
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
public BankAccountCopyConstructor(BankAccount other) {
|
||||
this.name = other.name;
|
||||
this.opened = LocalDateTime.now();
|
||||
this.balance = 0.0f;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.constructors;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
class Transaction {
|
||||
final BankAccountEmptyConstructor bankAccount;
|
||||
final LocalDateTime date;
|
||||
final double amount;
|
||||
|
||||
public Transaction(BankAccountEmptyConstructor account, LocalDateTime date, double amount) {
|
||||
this.bankAccount = account;
|
||||
this.date = date;
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
/*
|
||||
* Compilation Error :'(, all final variables must be explicitly initialised.
|
||||
* public Transaction() {
|
||||
* }
|
||||
*/
|
||||
|
||||
public void invalidMethod() {
|
||||
// this.amount = 102.03; // Results in a compiler error. You cannot change the value of a final variable.
|
||||
}
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.constructors;
|
||||
|
||||
import com.baeldung.constructors.*;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class ConstructorUnitTest {
|
||||
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
|
||||
|
||||
@Test
|
||||
public void givenNoExplicitContructor_whenUsed_thenFails() {
|
||||
BankAccount account = new BankAccount();
|
||||
assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoArgumentConstructor_whenUsed_thenSucceeds() {
|
||||
BankAccountEmptyConstructor account = new BankAccountEmptyConstructor();
|
||||
assertThatCode(() -> {
|
||||
account.toString();
|
||||
}).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParameterisedConstructor_whenUsed_thenSucceeds() {
|
||||
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
|
||||
BankAccountParameterizedConstructor account =
|
||||
new BankAccountParameterizedConstructor("Tom", opened, 1000.0f);
|
||||
|
||||
assertThatCode(() -> {
|
||||
account.toString();
|
||||
}).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCopyContructor_whenUser_thenMaintainsLogic() {
|
||||
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
|
||||
BankAccountCopyConstructor account = new BankAccountCopyConstructor("Tim", opened, 1000.0f);
|
||||
BankAccountCopyConstructor newAccount = new BankAccountCopyConstructor(account);
|
||||
|
||||
assertThat(account.getName()).isEqualTo(newAccount.getName());
|
||||
assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened());
|
||||
|
||||
assertThat(newAccount.getBalance()).isEqualTo(0.0f);
|
||||
}
|
||||
}
|
|
@ -10,7 +10,6 @@
|
|||
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
||||
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
|
||||
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
|
||||
- [Sorting in Java](http://www.baeldung.com/java-sorting)
|
||||
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
||||
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
|
||||
- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding)
|
||||
|
@ -39,7 +38,6 @@
|
|||
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
|
||||
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
|
||||
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
|
||||
- [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree)
|
||||
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
|
||||
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
|
||||
|
@ -49,15 +47,10 @@
|
|||
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
|
||||
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
|
||||
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
|
||||
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
|
||||
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
|
||||
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||
- [Class Loaders in Java](http://www.baeldung.com/java-classloaders)
|
||||
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
||||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Sending Emails with Java](http://www.baeldung.com/java-email)
|
||||
- [Introduction to SSL in Java](http://www.baeldung.com/java-ssl)
|
||||
- [Java KeyStore API](http://www.baeldung.com/java-keystore)
|
||||
|
@ -80,8 +73,6 @@
|
|||
- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
|
||||
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
|
||||
- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods)
|
||||
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
|
||||
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
||||
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
||||
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
|
||||
- [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root)
|
||||
|
@ -93,3 +84,7 @@
|
|||
- [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks)
|
||||
- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format)
|
||||
- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures)
|
||||
- [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree)
|
||||
- [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order)
|
||||
- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
|
||||
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
|
||||
|
|
|
@ -2,29 +2,28 @@ package com.baeldung.abstractclasses.application;
|
|||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.StandardFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
|
||||
public static void main(String[] args) throws IOException, URISyntaxException {
|
||||
|
||||
Application application = new Application();
|
||||
String filePath = application.getFilePathFromResourcesFolder("files/test.txt");
|
||||
|
||||
BaseFileReader lowercaseFileReader = new LowercaseFileReader(filePath);
|
||||
Path path = application.getPathFromResourcesFile("files/test.txt");
|
||||
BaseFileReader lowercaseFileReader = new LowercaseFileReader(path);
|
||||
lowercaseFileReader.readFile().forEach(line -> System.out.println(line));
|
||||
|
||||
BaseFileReader uppercaseFileReader = new UppercaseFileReader(path);
|
||||
uppercaseFileReader.readFile().forEach(line -> System.out.println(line));
|
||||
|
||||
BaseFileReader upperCaseFileReader = new UppercaseFileReader(filePath);
|
||||
upperCaseFileReader.readFile().forEach(line -> System.out.println(line));
|
||||
|
||||
BaseFileReader standardFileReader = new StandardFileReader(filePath);
|
||||
standardFileReader.readFile().forEach(line -> System.out.println(line));
|
||||
|
||||
}
|
||||
|
||||
private String getFilePathFromResourcesFolder(String fileName) {
|
||||
return getClass().getClassLoader().getResource(fileName).getPath().substring(1);
|
||||
private Path getPathFromResourcesFile(String filePath) throws URISyntaxException {
|
||||
return Paths.get(getClass().getClassLoader().getResource(filePath).toURI());
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,19 +1,27 @@
|
|||
package com.baeldung.abstractclasses.filereaders;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public abstract class BaseFileReader {
|
||||
|
||||
protected String filePath;
|
||||
protected Path filePath;
|
||||
|
||||
protected BaseFileReader(String filePath) {
|
||||
protected BaseFileReader(Path filePath) {
|
||||
this.filePath = filePath;
|
||||
}
|
||||
|
||||
public String getFilePath() {
|
||||
public Path getFilePath() {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public abstract List<String> readFile() throws IOException;
|
||||
public List<String> readFile() throws IOException {
|
||||
return Files.lines(filePath)
|
||||
.map(this::mapFileLine).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
protected abstract String mapFileLine(String line);
|
||||
}
|
||||
|
|
|
@ -1,21 +1,15 @@
|
|||
package com.baeldung.abstractclasses.filereaders;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class LowercaseFileReader extends BaseFileReader {
|
||||
|
||||
public LowercaseFileReader(String filePath) {
|
||||
public LowercaseFileReader(Path filePath) {
|
||||
super(filePath);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<String> readFile() throws IOException {
|
||||
return Files.lines(Paths.get(filePath))
|
||||
.map(String::toLowerCase)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
public String mapFileLine(String line) {
|
||||
return line.toLowerCase();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,19 +0,0 @@
|
|||
package com.baeldung.abstractclasses.filereaders;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StandardFileReader extends BaseFileReader {
|
||||
|
||||
public StandardFileReader(String filePath) {
|
||||
super(filePath);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> readFile() throws IOException {
|
||||
return Files.lines(Paths.get(filePath)).collect(Collectors.toList());
|
||||
}
|
||||
}
|
|
@ -1,21 +1,15 @@
|
|||
package com.baeldung.abstractclasses.filereaders;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class UppercaseFileReader extends BaseFileReader {
|
||||
|
||||
public UppercaseFileReader(String filePath) {
|
||||
|
||||
public UppercaseFileReader(Path filePath) {
|
||||
super(filePath);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<String> readFile() throws IOException {
|
||||
return Files.lines(Paths.get(filePath))
|
||||
.map(String::toUpperCase)
|
||||
.collect(Collectors.toList());
|
||||
public String mapFileLine(String line) {
|
||||
return line.toUpperCase();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.className;
|
||||
|
||||
public class RetrievingClassName {
|
||||
|
||||
public class InnerClass {
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
public class CommandLineProxyDemo {
|
||||
|
||||
public static final String RESOURCE_URL = "http://www.google.com";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
URL url = new URL(RESOURCE_URL);
|
||||
URLConnection con = url.openConnection();
|
||||
System.out.println(UrlConnectionUtils.contentAsString(con));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.Proxy;
|
||||
import java.net.URL;
|
||||
|
||||
public class DirectProxyDemo {
|
||||
|
||||
private static final String URL_STRING = "http://www.google.com";
|
||||
|
||||
public static void main(String... args) throws IOException {
|
||||
|
||||
URL weburl = new URL(URL_STRING);
|
||||
HttpURLConnection directConnection
|
||||
= (HttpURLConnection) weburl.openConnection(Proxy.NO_PROXY);
|
||||
System.out.println(UrlConnectionUtils.contentAsString(directConnection));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Proxy;
|
||||
import java.net.Socket;
|
||||
import java.net.URL;
|
||||
|
||||
public class SocksProxyDemo {
|
||||
|
||||
private static final String URL_STRING = "http://www.google.com";
|
||||
private static final String SOCKET_SERVER_HOST = "someserver.baeldung.com";
|
||||
private static final int SOCKET_SERVER_PORT = 1111;
|
||||
|
||||
public static void main(String... args) throws IOException {
|
||||
|
||||
URL weburl = new URL(URL_STRING);
|
||||
Proxy socksProxy
|
||||
= new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 1080));
|
||||
HttpURLConnection socksConnection
|
||||
= (HttpURLConnection) weburl.openConnection(socksProxy);
|
||||
System.out.println(UrlConnectionUtils.contentAsString(socksConnection));
|
||||
|
||||
Socket proxySocket = new Socket(socksProxy);
|
||||
InetSocketAddress socketHost
|
||||
= new InetSocketAddress(SOCKET_SERVER_HOST, SOCKET_SERVER_PORT);
|
||||
proxySocket.connect(socketHost);
|
||||
// do stuff with the socket
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
public class SystemPropertyProxyDemo {
|
||||
|
||||
public static final String RESOURCE_URL = "http://www.google.com";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
System.setProperty("http.proxyHost", "127.0.0.1");
|
||||
System.setProperty("http.proxyPort", "3128");
|
||||
|
||||
URL url = new URL(RESOURCE_URL);
|
||||
URLConnection con = url.openConnection();
|
||||
System.out.println(UrlConnectionUtils.contentAsString(con));
|
||||
|
||||
System.setProperty("http.proxyHost", null);
|
||||
// proxy will no longer be used for http connections
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URLConnection;
|
||||
|
||||
class UrlConnectionUtils {
|
||||
|
||||
public static String contentAsString(URLConnection con) throws IOException {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
try (BufferedReader reader
|
||||
= new BufferedReader(new InputStreamReader(con.getInputStream()))){
|
||||
while (reader.ready()) {
|
||||
builder.append(reader.readLine());
|
||||
}
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Proxy;
|
||||
import java.net.URL;
|
||||
|
||||
public class WebProxyDemo {
|
||||
|
||||
private static final String URL_STRING = "http://www.google.com";
|
||||
|
||||
public static void main(String... args) throws IOException {
|
||||
|
||||
URL weburl = new URL(URL_STRING);
|
||||
Proxy webProxy
|
||||
= new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128));
|
||||
HttpURLConnection webProxyConnection
|
||||
= (HttpURLConnection) weburl.openConnection(webProxy);
|
||||
System.out.println(UrlConnectionUtils.contentAsString(webProxyConnection));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,25 +0,0 @@
|
|||
package com.baeldung.abstractclasses;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.net.URL;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.StandardFileReader;
|
||||
|
||||
public class StandardFileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStandardFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
|
||||
// We'll transform the resource URL path to URI to load the file correctly in Windows
|
||||
URL url = getClass().getClassLoader().getResource("files/test.txt");
|
||||
String filePath = Paths.get(url.toURI()).toString();
|
||||
BaseFileReader standardFileReader = new StandardFileReader(filePath);
|
||||
|
||||
assertThat(standardFileReader.readFile()).isInstanceOf(List.class);
|
||||
}
|
||||
}
|
|
@ -1,23 +1,20 @@
|
|||
package com.baeldung.abstractclasses;
|
||||
package com.baeldung.abstractclasses.test;
|
||||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
|
||||
|
||||
import java.net.URL;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LowercaseFileReaderUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void givenLowercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
|
||||
// We'll transform the resource URL path to URI to load the file correctly in Windows
|
||||
URL url = getClass().getClassLoader().getResource("files/test.txt");
|
||||
String filePath = Paths.get(url.toURI()).toString();
|
||||
BaseFileReader lowercaseFileReader = new LowercaseFileReader(filePath);
|
||||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
|
||||
BaseFileReader lowercaseFileReader = new LowercaseFileReader(path);
|
||||
|
||||
assertThat(lowercaseFileReader.readFile()).isInstanceOf(List.class);
|
||||
}
|
||||
}
|
|
@ -1,9 +1,8 @@
|
|||
package com.baeldung.abstractclasses;
|
||||
package com.baeldung.abstractclasses.test;
|
||||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
|
||||
|
||||
import java.net.URL;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
@ -13,11 +12,9 @@ public class UppercaseFileReaderUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenUppercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
|
||||
// We'll transform the resource URL path to URI to load the file correctly in Windows
|
||||
URL url = getClass().getClassLoader().getResource("files/test.txt");
|
||||
String filePath = Paths.get(url.toURI()).toString();
|
||||
BaseFileReader uppercaseFileReader = new UppercaseFileReader(filePath);
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
|
||||
BaseFileReader uppercaseFileReader = new UppercaseFileReader(path);
|
||||
|
||||
assertThat(uppercaseFileReader.readFile()).isInstanceOf(List.class);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,156 @@
|
|||
package com.baeldung.className;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
public class RetrievingClassNameUnitTest {
|
||||
|
||||
// Retrieving Simple Name
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetSimpleName_thenRetrievingClassName() {
|
||||
assertEquals("RetrievingClassName", RetrievingClassName.class.getSimpleName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetSimpleName_thenInt() {
|
||||
assertEquals("int", int.class.getSimpleName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetSimpleName_thenRetrievingClassNameWithBrackets() {
|
||||
assertEquals("RetrievingClassName[]", RetrievingClassName[].class.getSimpleName());
|
||||
assertEquals("RetrievingClassName[][]", RetrievingClassName[][].class.getSimpleName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetSimpleName_thenEmptyString() {
|
||||
assertEquals("", new RetrievingClassName() {}.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
// Retrieving Other Names
|
||||
// - Primitive Types
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetName_thenInt() {
|
||||
assertEquals("int", int.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetTypeName_thenInt() {
|
||||
assertEquals("int", int.class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetCanonicalName_thenInt() {
|
||||
assertEquals("int", int.class.getCanonicalName());
|
||||
}
|
||||
|
||||
// - Object Types
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetTypeName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetCanonicalName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getCanonicalName());
|
||||
}
|
||||
|
||||
// - Inner Classes
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClass_whenGetName_thenCanonicalNameWithDollarSeparator() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClass_whenGetTypeName_thenCanonicalNameWithDollarSeparator() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClass_whenGetCanonicalName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass", RetrievingClassName.InnerClass.class.getCanonicalName());
|
||||
}
|
||||
|
||||
// - Anonymous Classes
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
|
||||
// These are the second and third appearences of an anonymous class in RetrievingClassNameUnitTest, hence $2 and $3 expectations
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$2", new RetrievingClassName() {}.getClass().getName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$3", new RetrievingClassName() {}.getClass().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetTypeName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
|
||||
// These are the fourth and fifth appearences of an anonymous class in RetrievingClassNameUnitTest, hence $4 and $5 expectations
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$4", new RetrievingClassName() {}.getClass().getTypeName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$5", new RetrievingClassName() {}.getClass().getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetCanonicalName_thenNull() {
|
||||
assertNull(new RetrievingClassName() {}.getClass().getCanonicalName());
|
||||
}
|
||||
|
||||
// - Arrays
|
||||
@Test
|
||||
public void givenPrimitiveIntArray_whenGetName_thenOpeningBracketsAndPrimitiveIntLetter() {
|
||||
assertEquals("[I", int[].class.getName());
|
||||
assertEquals("[[I", int[][].class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameGetName() {
|
||||
assertEquals("[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[].class.getName());
|
||||
assertEquals("[[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[][].class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClassArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameInnerClassGetName() {
|
||||
assertEquals("[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[].class.getName());
|
||||
assertEquals("[[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[][].class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveIntArray_whenGetTypeName_thenPrimitiveIntGetTypeNameWithBrackets() {
|
||||
assertEquals("int[]", int[].class.getTypeName());
|
||||
assertEquals("int[][]", int[][].class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetTypeName_thenRetrievingClassNameGetTypeNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getTypeName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClassArray_whenGetTypeName_thenRetrievingClassNameInnerClassGetTypeNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[]", RetrievingClassName.InnerClass[].class.getTypeName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[][]", RetrievingClassName.InnerClass[][].class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveIntArray_whenGetCanonicalName_thenPrimitiveIntGetCanonicalNameWithBrackets() {
|
||||
assertEquals("int[]", int[].class.getCanonicalName());
|
||||
assertEquals("int[][]", int[][].class.getCanonicalName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetCanonicalName_thenRetrievingClassNameGetCanonicalNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getCanonicalName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getCanonicalName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClassArray_whenGetCanonicalName_thenRetrievingClassNameInnerClassGetCanonicalNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[]", RetrievingClassName.InnerClass[].class.getCanonicalName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[][]", RetrievingClassName.InnerClass[][].class.getCanonicalName());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.regexp.optmization;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
|
@ -14,13 +13,15 @@ import static org.junit.Assert.assertTrue;
|
|||
|
||||
public class OptimizedMatcherUnitTest {
|
||||
|
||||
private long time;
|
||||
private long mstimePreCompiled;
|
||||
private long mstimeNotPreCompiled;
|
||||
|
||||
private String action;
|
||||
|
||||
private List<String> items;
|
||||
|
||||
private class TimeWrapper {
|
||||
private long time;
|
||||
private long mstimePreCompiled;
|
||||
private long mstimeNotPreCompiled;
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
|
@ -48,27 +49,27 @@ public class OptimizedMatcherUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenANotPreCompiledAndAPreCompiledPatternA_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
|
||||
|
||||
testPatterns("A*");
|
||||
assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
|
||||
TimeWrapper timeObj = new TimeWrapper();
|
||||
testPatterns("A*", timeObj);
|
||||
assertTrue(timeObj.mstimePreCompiled < timeObj.mstimeNotPreCompiled);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANotPreCompiledAndAPreCompiledPatternABC_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
|
||||
|
||||
testPatterns("A*B*C*");
|
||||
assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
|
||||
TimeWrapper timeObj = new TimeWrapper();
|
||||
testPatterns("A*B*C*", timeObj);
|
||||
assertTrue(timeObj.mstimePreCompiled < timeObj.mstimeNotPreCompiled);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANotPreCompiledAndAPreCompiledPatternECWF_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
|
||||
|
||||
testPatterns("E*C*W*F*");
|
||||
assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
|
||||
TimeWrapper timeObj = new TimeWrapper();
|
||||
testPatterns("E*C*W*F*", timeObj);
|
||||
assertTrue(timeObj.mstimePreCompiled < timeObj.mstimeNotPreCompiled);
|
||||
}
|
||||
|
||||
private void testPatterns(String regex) {
|
||||
time = System.nanoTime();
|
||||
private void testPatterns(String regex, TimeWrapper timeObj) {
|
||||
timeObj.time = System.nanoTime();
|
||||
int matched = 0;
|
||||
int unmatched = 0;
|
||||
|
||||
|
@ -83,10 +84,10 @@ public class OptimizedMatcherUnitTest {
|
|||
|
||||
this.action = "uncompiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
|
||||
|
||||
this.mstimeNotPreCompiled = (System.nanoTime() - time) / 1000000;
|
||||
System.out.println(this.action + ": " + mstimeNotPreCompiled + "ms");
|
||||
timeObj.mstimeNotPreCompiled = (System.nanoTime() - timeObj.time) / 1000000;
|
||||
System.out.println(this.action + ": " + timeObj.mstimeNotPreCompiled + "ms");
|
||||
|
||||
time = System.nanoTime();
|
||||
timeObj.time = System.nanoTime();
|
||||
|
||||
Matcher matcher = Pattern.compile(regex).matcher("");
|
||||
matched = 0;
|
||||
|
@ -103,7 +104,7 @@ public class OptimizedMatcherUnitTest {
|
|||
|
||||
this.action = "compiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
|
||||
|
||||
this.mstimePreCompiled = (System.nanoTime() - time) / 1000000;
|
||||
System.out.println(this.action + ": " + mstimePreCompiled + "ms");
|
||||
timeObj.mstimePreCompiled = (System.nanoTime() - timeObj.time) / 1000000;
|
||||
System.out.println(this.action + ": " + timeObj.mstimePreCompiled + "ms");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.string;
|
||||
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StringReplaceAndRemoveUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplace_thenProcessedString() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
String processed = master.replace(target, replacement);
|
||||
assertTrue(processed.contains(replacement));
|
||||
assertFalse(processed.contains(target));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplaceAll_thenProcessedString() {
|
||||
|
||||
String master2 = "Welcome to Baeldung, Hello World Baeldung";
|
||||
String regexTarget= "(Baeldung)$";
|
||||
String replacement = "Java";
|
||||
String processed2 = master2.replaceAll(regexTarget, replacement);
|
||||
assertTrue(processed2.endsWith("Java"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenStringBuilderMethods_thenProcessedString() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
|
||||
int startIndex = master.indexOf(target);
|
||||
int stopIndex = startIndex + target.length();
|
||||
|
||||
StringBuilder builder = new StringBuilder(master);
|
||||
|
||||
|
||||
builder.delete(startIndex, stopIndex);
|
||||
assertFalse(builder.toString().contains(target));
|
||||
|
||||
|
||||
builder.replace(startIndex, stopIndex, replacement);
|
||||
assertTrue(builder.toString().contains(replacement));
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
|
||||
String processed = StringUtils.replace(master, target, replacement);
|
||||
assertTrue(processed.contains(replacement));
|
||||
|
||||
String master2 = "Hello World Baeldung!";
|
||||
String target2 = "baeldung";
|
||||
String processed2 = StringUtils.replaceIgnoreCase(master2, target2, replacement);
|
||||
assertFalse(processed2.contains(target));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -52,7 +52,7 @@ class RandomStringUnitTest {
|
|||
random.nextBytes(bytes)
|
||||
|
||||
var randomString = (0..bytes.size - 1).map { i ->
|
||||
charPool.get((bytes[i] and 0xFF.toByte() and charPool.size.toByte()).toInt())
|
||||
charPool.get((bytes[i] and 0xFF.toByte() and (charPool.size-1).toByte()).toInt())
|
||||
}.joinToString("")
|
||||
|
||||
assert(randomString.matches(Regex(ALPHANUMERIC_REGEX)))
|
||||
|
|
|
@ -71,9 +71,8 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<io.grpc.version>1.5.0</io.grpc.version>
|
||||
<os-maven-plugin.version>1.5.0.Final</os-maven-plugin.version>
|
||||
<protobuf-maven-plugin.version>0.5.0</protobuf-maven-plugin.version>
|
||||
<io.grpc.version>1.16.1</io.grpc.version>
|
||||
<os-maven-plugin.version>1.6.1</os-maven-plugin.version>
|
||||
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -10,7 +10,7 @@ import io.grpc.ManagedChannelBuilder;
|
|||
public class GrpcClient {
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080)
|
||||
.usePlaintext(true)
|
||||
.usePlaintext()
|
||||
.build();
|
||||
|
||||
HelloServiceGrpc.HelloServiceBlockingStub stub
|
||||
|
|
|
@ -2,6 +2,9 @@ package org.baeldung.guava;
|
|||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import org.junit.Test;
|
||||
import com.google.common.collect.ImmutableRangeMap;
|
||||
|
@ -98,8 +101,9 @@ public class GuavaRangeMapUnitTest {
|
|||
final RangeMap<Integer, String> experiencedSubRangeDesignationMap = experienceRangeDesignationMap.subRangeMap(Range.closed(4, 14));
|
||||
|
||||
assertNull(experiencedSubRangeDesignationMap.get(3));
|
||||
assertEquals("Executive Director", experiencedSubRangeDesignationMap.get(14));
|
||||
assertEquals("Vice President", experiencedSubRangeDesignationMap.get(7));
|
||||
assertTrue(experiencedSubRangeDesignationMap.asMapOfRanges().values()
|
||||
.containsAll(Arrays.asList("Executive Director", "Vice President", "Executive Director")));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -24,3 +24,4 @@
|
|||
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
|
||||
- [Guide to DateTimeFormatter](https://www.baeldung.com/java-datetimeformatter)
|
||||
- [Format ZonedDateTime to String](https://www.baeldung.com/java-format-zoned-datetime-string)
|
||||
- [Convert Between java.time.Instant and java.sql.Timestamp](Convert Between java.time.Instant and java.sql.Timestamp)
|
||||
|
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.timestamp;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class StringToTimestampConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDatePattern_whenParsing_thenTimestampIsCorrect() {
|
||||
String pattern = "MMM dd, yyyy HH:mm:ss.SSSSSSSS";
|
||||
String timestampAsString = "Nov 12, 2018 13:02:56.12345678";
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
|
||||
LocalDateTime localDateTime = LocalDateTime.from(formatter.parse(timestampAsString));
|
||||
|
||||
Timestamp timestamp = Timestamp.valueOf(localDateTime);
|
||||
Assert.assertEquals("2018-11-12 13:02:56.12345678", timestamp.toString());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.timestamp;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class TimestampToStringConverterTest {
|
||||
|
||||
@Test
|
||||
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {
|
||||
Timestamp timestamp = Timestamp.valueOf("2018-12-12 01:02:03.123456789");
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
|
||||
|
||||
String timestampAsString = formatter.format(timestamp.toLocalDateTime());
|
||||
Assert.assertEquals("2018-12-12T01:02:03.123456789", timestampAsString);
|
||||
}
|
||||
}
|
|
@ -36,3 +36,4 @@
|
|||
- [String Performance Hints](https://www.baeldung.com/java-string-performance)
|
||||
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences)
|
||||
- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
|
||||
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
|
||||
|
|
|
@ -0,0 +1,69 @@
|
|||
package com.baeldung.string;
|
||||
|
||||
public class AddingNewLineToString {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String line1 = "Humpty Dumpty sat on a wall.";
|
||||
String line2 = "Humpty Dumpty had a great fall.";
|
||||
String rhyme = "";
|
||||
|
||||
System.out.println("***New Line in a String in Java***");
|
||||
//1. Using "\n"
|
||||
System.out.println("1. Using \\n");
|
||||
rhyme = line1 + "\n" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//2. Using "\r\n"
|
||||
System.out.println("2. Using \\r\\n");
|
||||
rhyme = line1 + "\r\n" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//3. Using "\r"
|
||||
System.out.println("3. Using \\r");
|
||||
rhyme = line1 + "\r" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//4. Using "\n\r" Note that this is not same as "\r\n"
|
||||
// Using "\n\r" is equivalent to adding two lines
|
||||
System.out.println("4. Using \\n\\r");
|
||||
rhyme = line1 + "\n\r" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//5. Using System.lineSeparator()
|
||||
System.out.println("5. Using System.lineSeparator()");
|
||||
rhyme = line1 + System.lineSeparator() + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//6. Using System.getProperty("line.separator")
|
||||
System.out.println("6. Using System.getProperty(\"line.separator\")");
|
||||
rhyme = line1 + System.getProperty("line.separator") + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
System.out.println("***HTML to rendered in a browser***");
|
||||
//1. Line break for HTML using <br>
|
||||
System.out.println("1. Line break for HTML using <br>");
|
||||
rhyme = line1 + "<br>" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//2. Line break for HTML using “ ”
|
||||
System.out.println("2. Line break for HTML using ");
|
||||
rhyme = line1 + " " + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//3. Line break for HTML using “ ”
|
||||
System.out.println("3. Line break for HTML using ");
|
||||
rhyme = line1 + " " + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//4. Line break for HTML using “
 ;”
|
||||
System.out.println("4. Line break for HTML using ");
|
||||
rhyme = line1 + " " + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//5. Line break for HTML using \n”
|
||||
System.out.println("5. Line break for HTML using \\n");
|
||||
rhyme = line1 + "\n" + line2;
|
||||
System.out.println(rhyme);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
package com.baeldung.stringduplicates;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class RemoveDuplicateFromString {
|
||||
|
||||
|
||||
String removeDuplicatesUsingCharArray(String str) {
|
||||
|
||||
char[] chars = str.toCharArray();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int repeatedCtr;
|
||||
for (int i = 0; i < chars.length; i++) {
|
||||
repeatedCtr = 0;
|
||||
for (int j = i + 1; j < chars.length; j++) {
|
||||
if (chars[i] == chars[j]) {
|
||||
repeatedCtr++;
|
||||
}
|
||||
}
|
||||
if (repeatedCtr == 0) {
|
||||
sb.append(chars[i]);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsinglinkedHashSet(String str) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Set<Character> linkedHashSet = new LinkedHashSet<>();
|
||||
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
linkedHashSet.add(str.charAt(i));
|
||||
}
|
||||
|
||||
for (Character c : linkedHashSet) {
|
||||
sb.append(c);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsingSorting(String str) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if(!str.isEmpty()) {
|
||||
char[] chars = str.toCharArray();
|
||||
Arrays.sort(chars);
|
||||
|
||||
sb.append(chars[0]);
|
||||
for (int i = 1; i < chars.length; i++) {
|
||||
if (chars[i] != chars[i - 1]) {
|
||||
sb.append(chars[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsingHashSet(String str) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Set<Character> hashSet = new HashSet<>();
|
||||
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
hashSet.add(str.charAt(i));
|
||||
}
|
||||
|
||||
for (Character c : hashSet) {
|
||||
sb.append(c);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsingIndexOf(String str) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int idx;
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
char c = str.charAt(i);
|
||||
idx = str.indexOf(c, i + 1);
|
||||
if (idx == -1) {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
String removeDuplicatesUsingDistinct(String str) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
str.chars().distinct().forEach(c -> sb.append((char) c));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.string;
|
||||
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StringReplaceAndRemoveUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplace_thenProcessedString() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
String processed = master.replace(target, replacement);
|
||||
assertTrue(processed.contains(replacement));
|
||||
assertFalse(processed.contains(target));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplaceAll_thenProcessedString() {
|
||||
|
||||
String master2 = "Welcome to Baeldung, Hello World Baeldung";
|
||||
String regexTarget= "(Baeldung)$";
|
||||
String replacement = "Java";
|
||||
String processed2 = master2.replaceAll(regexTarget, replacement);
|
||||
assertTrue(processed2.endsWith("Java"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenStringBuilderMethods_thenProcessedString() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
|
||||
int startIndex = master.indexOf(target);
|
||||
int stopIndex = startIndex + target.length();
|
||||
|
||||
StringBuilder builder = new StringBuilder(master);
|
||||
|
||||
|
||||
builder.delete(startIndex, stopIndex);
|
||||
assertFalse(builder.toString().contains(target));
|
||||
|
||||
|
||||
builder.replace(startIndex, stopIndex, replacement);
|
||||
assertTrue(builder.toString().contains(replacement));
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
|
||||
String processed = StringUtils.replace(master, target, replacement);
|
||||
assertTrue(processed.contains(replacement));
|
||||
|
||||
String master2 = "Hello World Baeldung!";
|
||||
String target2 = "baeldung";
|
||||
String processed2 = StringUtils.replaceIgnoreCase(master2, target2, replacement);
|
||||
assertFalse(processed2.contains(target));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,82 @@
|
|||
package com.baeldung.stringduplicates;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RemoveDuplicateFromStringUnitTest {
|
||||
|
||||
private final static String STR1 = "racecar";
|
||||
private final static String STR2 = "J2ee programming";
|
||||
private final static String STR_EMPTY = "";
|
||||
|
||||
private RemoveDuplicateFromString removeDuplicateFromString;
|
||||
|
||||
@Before
|
||||
public void executedBeforeEach() {
|
||||
removeDuplicateFromString = new RemoveDuplicateFromString();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenUsingCharArray_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("ecar", str1);
|
||||
Assert.assertEquals("J2e poraming", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingLinkedHashSet_DuplicatesShouldBeRemovedAndItKeepStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR2);
|
||||
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("race", str1);
|
||||
Assert.assertEquals("J2e progamin", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSorting_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR2);
|
||||
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingSorting(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("acer", str1);
|
||||
Assert.assertEquals(" 2Jaegimnopr", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingHashSet_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("arce", str1);
|
||||
Assert.assertEquals(" pa2regiJmno", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingIndexOf_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("ecar", str1);
|
||||
Assert.assertEquals("J2e poraming", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingJava8_DuplicatesShouldBeRemovedAndItKeepStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("race", str1);
|
||||
Assert.assertEquals("J2e progamin", str2);
|
||||
}
|
||||
}
|
|
@ -87,6 +87,13 @@
|
|||
<artifactId>h2</artifactId>
|
||||
<version>${h2database.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/io.arrow-kt/arrow-core -->
|
||||
<dependency>
|
||||
<groupId>io.arrow-kt</groupId>
|
||||
<artifactId>arrow-core</artifactId>
|
||||
<version>0.7.3</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.kotlin.arrow
|
||||
|
||||
import arrow.core.Either
|
||||
import arrow.core.filterOrElse
|
||||
import kotlin.math.sqrt
|
||||
|
||||
class FunctionalErrorHandlingWithEither {
|
||||
|
||||
sealed class ComputeProblem {
|
||||
object OddNumber : ComputeProblem()
|
||||
object NotANumber : ComputeProblem()
|
||||
}
|
||||
|
||||
fun parseInput(s : String) : Either<ComputeProblem, Int> = Either.cond(s.toIntOrNull() != null, {-> s.toInt()}, {->ComputeProblem.NotANumber} )
|
||||
|
||||
fun isEven(x : Int) : Boolean = x % 2 == 0
|
||||
|
||||
fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2)
|
||||
|
||||
fun biggestDivisor(x : Int, y : Int) : Int {
|
||||
if(x == y){
|
||||
return 1;
|
||||
}
|
||||
if(x % y == 0){
|
||||
return x / y;
|
||||
}
|
||||
return biggestDivisor(x, y+1)
|
||||
}
|
||||
|
||||
fun isSquareNumber(x : Int) : Boolean {
|
||||
val sqrt: Double = sqrt(x.toDouble())
|
||||
return sqrt % 1.0 == 0.0
|
||||
}
|
||||
|
||||
fun computeWithEither(input : String) : Either<ComputeProblem, Boolean> {
|
||||
return parseInput(input)
|
||||
.filterOrElse(::isEven) {->ComputeProblem.OddNumber}
|
||||
.map (::biggestDivisor)
|
||||
.map (::isSquareNumber)
|
||||
}
|
||||
|
||||
fun computeWithEitherClient(input : String) {
|
||||
val computeWithEither = computeWithEither(input)
|
||||
|
||||
when(computeWithEither){
|
||||
is Either.Right -> "The greatest divisor is square number: ${computeWithEither.b}"
|
||||
is Either.Left -> when(computeWithEither.a){
|
||||
is ComputeProblem.NotANumber -> "Wrong input! Not a number!"
|
||||
is ComputeProblem.OddNumber -> "It is an odd number!"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.kotlin.arrow
|
||||
|
||||
import arrow.core.None
|
||||
import arrow.core.Option
|
||||
import arrow.core.Some
|
||||
import kotlin.math.sqrt
|
||||
|
||||
class FunctionalErrorHandlingWithOption {
|
||||
|
||||
fun parseInput(s : String) : Option<Int> = Option.fromNullable(s.toIntOrNull())
|
||||
|
||||
fun isEven(x : Int) : Boolean = x % 2 == 0
|
||||
|
||||
fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2)
|
||||
|
||||
fun biggestDivisor(x : Int, y : Int) : Int {
|
||||
if(x == y){
|
||||
return 1;
|
||||
}
|
||||
if(x % y == 0){
|
||||
return x / y;
|
||||
}
|
||||
return biggestDivisor(x, y+1)
|
||||
}
|
||||
|
||||
fun isSquareNumber(x : Int) : Boolean {
|
||||
val sqrt: Double = sqrt(x.toDouble())
|
||||
return sqrt % 1.0 == 0.0
|
||||
}
|
||||
|
||||
fun computeWithOption(input : String) : Option<Boolean> {
|
||||
return parseInput(input)
|
||||
.filter(::isEven)
|
||||
.map(::biggestDivisor)
|
||||
.map(::isSquareNumber)
|
||||
}
|
||||
|
||||
fun computeWithOptionClient(input : String) : String{
|
||||
val computeOption = computeWithOption(input)
|
||||
|
||||
return when(computeOption){
|
||||
is None -> "Not an even number!"
|
||||
is Some -> "The greatest divisor is square number: ${computeOption.t}"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,143 @@
|
|||
package com.baeldung.kotlin.arrow
|
||||
|
||||
import arrow.core.*
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class FunctionalDataTypes {
|
||||
|
||||
@Test
|
||||
fun whenIdCreated_thanValueIsPresent(){
|
||||
val id = Id("foo")
|
||||
val justId = Id.just("foo");
|
||||
|
||||
Assert.assertEquals("foo", id.extract())
|
||||
Assert.assertEquals(justId, id)
|
||||
}
|
||||
|
||||
fun length(s : String) : Int = s.length
|
||||
|
||||
fun isBigEnough(i : Int) : Boolean = i > 10
|
||||
|
||||
@Test
|
||||
fun whenIdCreated_thanMapIsAssociative(){
|
||||
val foo = Id("foo")
|
||||
|
||||
val map1 = foo.map(::length)
|
||||
.map(::isBigEnough)
|
||||
val map2 = foo.map { s -> isBigEnough(length(s)) }
|
||||
|
||||
Assert.assertEquals(map1, map2)
|
||||
}
|
||||
|
||||
fun lengthId(s : String) : Id<Int> = Id.just(length(s))
|
||||
|
||||
fun isBigEnoughId(i : Int) : Id<Boolean> = Id.just(isBigEnough(i))
|
||||
|
||||
@Test
|
||||
fun whenIdCreated_thanFlatMapIsAssociative(){
|
||||
val bar = Id("bar")
|
||||
|
||||
val flatMap = bar.flatMap(::lengthId)
|
||||
.flatMap(::isBigEnoughId)
|
||||
val flatMap1 = bar.flatMap { s -> lengthId(s).flatMap(::isBigEnoughId) }
|
||||
|
||||
Assert.assertEquals(flatMap, flatMap1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenOptionCreated_thanValueIsPresent(){
|
||||
val factory = Option.just(42)
|
||||
val constructor = Option(42)
|
||||
val emptyOptional = Option.empty<Integer>()
|
||||
val fromNullable = Option.fromNullable(null)
|
||||
|
||||
Assert.assertEquals(42, factory.getOrElse { -1 })
|
||||
Assert.assertEquals(factory, constructor)
|
||||
Assert.assertEquals(emptyOptional, fromNullable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenOptionCreated_thanConstructorDifferFromFactory(){
|
||||
val constructor : Option<String?> = Option(null)
|
||||
val fromNullable : Option<String?> = Option.fromNullable(null)
|
||||
|
||||
try{
|
||||
constructor.map { s -> s!!.length }
|
||||
Assert.fail()
|
||||
} catch (e : KotlinNullPointerException){
|
||||
fromNullable.map { s->s!!.length }
|
||||
}
|
||||
Assert.assertNotEquals(constructor, fromNullable)
|
||||
}
|
||||
|
||||
fun wrapper(x : Integer?) : Option<Int> = if (x == null) Option.just(-1) else Option.just(x.toInt())
|
||||
|
||||
@Test
|
||||
fun whenOptionFromNullableCreated_thanItBreaksLeftIdentity(){
|
||||
val optionFromNull = Option.fromNullable(null)
|
||||
|
||||
Assert.assertNotEquals(optionFromNull.flatMap(::wrapper), wrapper(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenEitherCreated_thanOneValueIsPresent(){
|
||||
val rightOnly : Either<String,Int> = Either.right(42)
|
||||
val leftOnly : Either<String,Int> = Either.left("foo")
|
||||
|
||||
Assert.assertTrue(rightOnly.isRight())
|
||||
Assert.assertTrue(leftOnly.isLeft())
|
||||
Assert.assertEquals(42, rightOnly.getOrElse { -1 })
|
||||
Assert.assertEquals(-1, leftOnly.getOrElse { -1 })
|
||||
|
||||
Assert.assertEquals(0, rightOnly.map { it % 2 }.getOrElse { -1 })
|
||||
Assert.assertEquals(-1, leftOnly.map { it % 2 }.getOrElse { -1 })
|
||||
Assert.assertTrue(rightOnly.flatMap { Either.Right(it % 2) }.isRight())
|
||||
Assert.assertTrue(leftOnly.flatMap { Either.Right(it % 2) }.isLeft())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenEvalNowUsed_thenMapEvaluatedLazily(){
|
||||
val now = Eval.now(1)
|
||||
Assert.assertEquals(1, now.value())
|
||||
|
||||
var counter : Int = 0
|
||||
val map = now.map { x -> counter++; x+1 }
|
||||
Assert.assertEquals(0, counter)
|
||||
|
||||
val value = map.value()
|
||||
Assert.assertEquals(2, value)
|
||||
Assert.assertEquals(1, counter)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenEvalLaterUsed_theResultIsMemoized(){
|
||||
var counter : Int = 0
|
||||
val later = Eval.later { counter++; counter }
|
||||
Assert.assertEquals(0, counter)
|
||||
|
||||
val firstValue = later.value()
|
||||
Assert.assertEquals(1, firstValue)
|
||||
Assert.assertEquals(1, counter)
|
||||
|
||||
val secondValue = later.value()
|
||||
Assert.assertEquals(1, secondValue)
|
||||
Assert.assertEquals(1, counter)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenEvalAlwaysUsed_theResultIsNotMemoized(){
|
||||
var counter : Int = 0
|
||||
val later = Eval.always { counter++; counter }
|
||||
Assert.assertEquals(0, counter)
|
||||
|
||||
val firstValue = later.value()
|
||||
Assert.assertEquals(1, firstValue)
|
||||
Assert.assertEquals(1, counter)
|
||||
|
||||
val secondValue = later.value()
|
||||
Assert.assertEquals(2, secondValue)
|
||||
Assert.assertEquals(2, counter)
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
package com.baeldung.kotlin.arrow
|
||||
|
||||
import arrow.core.Either
|
||||
import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.NotANumber
|
||||
import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.OddNumber
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class FunctionalErrorHandlingWithEitherTest {
|
||||
|
||||
val operator = FunctionalErrorHandlingWithEither()
|
||||
|
||||
@Test
|
||||
fun givenInvalidInput_whenComputeInvoked_NotANumberIsPresent(){
|
||||
val computeWithEither = operator.computeWithEither("bar")
|
||||
|
||||
Assert.assertTrue(computeWithEither.isLeft())
|
||||
when(computeWithEither){
|
||||
is Either.Left -> when(computeWithEither.a){
|
||||
NotANumber -> "Ok."
|
||||
else -> Assert.fail()
|
||||
}
|
||||
else -> Assert.fail()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenOddNumberInput_whenComputeInvoked_OddNumberIsPresent(){
|
||||
val computeWithEither = operator.computeWithEither("121")
|
||||
|
||||
Assert.assertTrue(computeWithEither.isLeft())
|
||||
when(computeWithEither){
|
||||
is Either.Left -> when(computeWithEither.a){
|
||||
OddNumber -> "Ok."
|
||||
else -> Assert.fail()
|
||||
}
|
||||
else -> Assert.fail()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenEvenNumberWithoutSquare_whenComputeInvoked_OddNumberIsPresent(){
|
||||
val computeWithEither = operator.computeWithEither("100")
|
||||
|
||||
Assert.assertTrue(computeWithEither.isRight())
|
||||
when(computeWithEither){
|
||||
is Either.Right -> when(computeWithEither.b){
|
||||
false -> "Ok."
|
||||
else -> Assert.fail()
|
||||
}
|
||||
else -> Assert.fail()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenEvenNumberWithSquare_whenComputeInvoked_OddNumberIsPresent(){
|
||||
val computeWithEither = operator.computeWithEither("98")
|
||||
|
||||
Assert.assertTrue(computeWithEither.isRight())
|
||||
when(computeWithEither){
|
||||
is Either.Right -> when(computeWithEither.b){
|
||||
true -> "Ok."
|
||||
else -> Assert.fail()
|
||||
}
|
||||
else -> Assert.fail()
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.kotlin.arrow
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class FunctionalErrorHandlingWithOptionTest {
|
||||
|
||||
val operator = FunctionalErrorHandlingWithOption()
|
||||
|
||||
@Test
|
||||
fun givenInvalidInput_thenErrorMessageIsPresent(){
|
||||
val useComputeOption = operator.computeWithOptionClient("foo")
|
||||
Assert.assertEquals("Not an even number!", useComputeOption)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenOddNumberInput_thenErrorMessageIsPresent(){
|
||||
val useComputeOption = operator.computeWithOptionClient("539")
|
||||
Assert.assertEquals("Not an even number!",useComputeOption)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenEvenNumberInputWithNonSquareNum_thenFalseMessageIsPresent(){
|
||||
val useComputeOption = operator.computeWithOptionClient("100")
|
||||
Assert.assertEquals("The greatest divisor is square number: false",useComputeOption)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenEvenNumberInputWithSquareNum_thenTrueMessageIsPresent(){
|
||||
val useComputeOption = operator.computeWithOptionClient("242")
|
||||
Assert.assertEquals("The greatest divisor is square number: true",useComputeOption)
|
||||
}
|
||||
|
||||
}
|
|
@ -720,11 +720,11 @@
|
|||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<!-- <repository>
|
||||
<id>maven2-repository.dev.java.net</id>
|
||||
<name>Java.net repository</name>
|
||||
<url>http://download.java.net/maven/2</url>
|
||||
</repository>
|
||||
</repository> -->
|
||||
<repository>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
<?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"
|
||||
<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>
|
||||
|
@ -43,6 +44,12 @@
|
|||
<artifactId>disruptor</artifactId>
|
||||
<version>${disruptor.version}</version>
|
||||
</dependency>
|
||||
<!-- Webflux for reactive logging example -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
@ -50,6 +57,7 @@
|
|||
<log4j-api.version>2.7</log4j-api.version>
|
||||
<log4j-core.version>2.7</log4j-core.version>
|
||||
<disruptor.version>3.3.6</disruptor.version>
|
||||
<spring-boot.version>2.1.0.RELEASE</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.webFluxLogging;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class WebFluxLoggingExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Flux<Integer> reactiveStream = Flux.range(1, 5).log();
|
||||
|
||||
reactiveStream.subscribe();
|
||||
|
||||
reactiveStream = Flux.range(1, 5).log().take(3);
|
||||
|
||||
reactiveStream.subscribe();
|
||||
|
||||
reactiveStream = Flux.range(1, 5).take(3).log();
|
||||
|
||||
reactiveStream.subscribe();
|
||||
}
|
||||
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
## Relevant articles:
|
|
@ -12,3 +12,4 @@
|
|||
- [The DAO Pattern in Java](http://www.baeldung.com/java-dao-pattern)
|
||||
- [Interpreter Design Pattern in Java](http://www.baeldung.com/java-interpreter-pattern)
|
||||
- [State Design Pattern in Java](https://www.baeldung.com/java-state-design-pattern)
|
||||
- [The Decorator Pattern in Java](https://www.baeldung.com/java-decorator-pattern)
|
||||
|
|
|
@ -10,7 +10,7 @@ public class DeptEmployee {
|
|||
|
||||
private String employeeNumber;
|
||||
|
||||
private String designation;
|
||||
private String title;
|
||||
|
||||
private String name;
|
||||
|
||||
|
@ -23,11 +23,11 @@ public class DeptEmployee {
|
|||
this.department = department;
|
||||
}
|
||||
|
||||
public DeptEmployee(String name, String employeeNumber, String designation, Department department) {
|
||||
public DeptEmployee(String name, String employeeNumber, String title, Department department) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.employeeNumber = employeeNumber;
|
||||
this.designation = designation;
|
||||
this.title = title;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
|
@ -63,11 +63,11 @@ public class DeptEmployee {
|
|||
this.department = department;
|
||||
}
|
||||
|
||||
public String getDesignation() {
|
||||
return designation;
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setDesignation(String designation) {
|
||||
this.designation = designation;
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,9 +6,9 @@ import com.baeldung.hibernate.entities.DeptEmployee;
|
|||
|
||||
public interface EmployeeSearchService {
|
||||
|
||||
List<DeptEmployee> filterbyDesignationUsingCriteriaBuilder(List<String> designaitons);
|
||||
List<DeptEmployee> filterbyTitleUsingCriteriaBuilder(List<String> titles);
|
||||
|
||||
List<DeptEmployee> filterbyDesignationUsingExpression(List<String> aurhors);
|
||||
List<DeptEmployee> filterbyTitleUsingExpression(List<String> titles);
|
||||
|
||||
List<DeptEmployee> searchByDepartmentQuery(String query);
|
||||
|
||||
|
|
|
@ -25,12 +25,12 @@ public class EmployeeSearchServiceImpl implements EmployeeSearchService {
|
|||
}
|
||||
|
||||
@Override
|
||||
public List<DeptEmployee> filterbyDesignationUsingCriteriaBuilder(List<String> designations) {
|
||||
public List<DeptEmployee> filterbyTitleUsingCriteriaBuilder(List<String> titles) {
|
||||
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
|
||||
Root<DeptEmployee> root = criteriaQuery.from(DeptEmployee.class);
|
||||
In<String> inClause = criteriaBuilder.in(root.get("designation"));
|
||||
for (String designaiton : designations) {
|
||||
inClause.value(designaiton);
|
||||
In<String> inClause = criteriaBuilder.in(root.get("title"));
|
||||
for (String title : titles) {
|
||||
inClause.value(title);
|
||||
}
|
||||
criteriaQuery.select(root)
|
||||
.where(inClause);
|
||||
|
@ -39,12 +39,12 @@ public class EmployeeSearchServiceImpl implements EmployeeSearchService {
|
|||
}
|
||||
|
||||
@Override
|
||||
public List<DeptEmployee> filterbyDesignationUsingExpression(List<String> designations) {
|
||||
public List<DeptEmployee> filterbyTitleUsingExpression(List<String> titles) {
|
||||
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
|
||||
Root<DeptEmployee> root = criteriaQuery.from(DeptEmployee.class);
|
||||
criteriaQuery.select(root)
|
||||
.where(root.get("designation")
|
||||
.in(designations));
|
||||
.where(root.get("title")
|
||||
.in(titles));
|
||||
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
|
||||
return query.getResultList();
|
||||
}
|
||||
|
|
|
@ -81,42 +81,41 @@ public class EmployeeSearchServiceIntegrationTest {
|
|||
|
||||
@Test
|
||||
public final void givenCriteriaQuery_whenSearchedUsingCriteriaBuilderWithListofAuthors_thenResultIsFilteredByAuthorNames() {
|
||||
List<String> designations = new ArrayList<String>() {
|
||||
List<String> titles = new ArrayList<String>() {
|
||||
{
|
||||
add("Manager");
|
||||
add("Senior Manager");
|
||||
add("Director");
|
||||
}
|
||||
};
|
||||
List<DeptEmployee> result = searchService.filterbyDesignationUsingCriteriaBuilder(designations);
|
||||
List<DeptEmployee> result = searchService.filterbyTitleUsingCriteriaBuilder(titles);
|
||||
assertEquals("Number of Employees does not match with expected.", 6, result.size());
|
||||
assertThat(result.stream()
|
||||
.map(DeptEmployee::getDesignation)
|
||||
.map(DeptEmployee::getTitle)
|
||||
.distinct()
|
||||
.collect(Collectors.toList()), containsInAnyOrder(designations.toArray()));
|
||||
.collect(Collectors.toList()), containsInAnyOrder(titles.toArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCriteriaQuery_whenSearchedUsingExpressionWithListofAuthors_thenResultIsFilteredByAuthorNames() {
|
||||
List<String> designations = new ArrayList<String>() {
|
||||
List<String> titles = new ArrayList<String>() {
|
||||
{
|
||||
add("Manager");
|
||||
add("Senior Manager");
|
||||
add("Director");
|
||||
}
|
||||
};
|
||||
List<DeptEmployee> result = searchService.filterbyDesignationUsingExpression(designations);
|
||||
List<DeptEmployee> result = searchService.filterbyTitleUsingExpression(titles);
|
||||
assertEquals("Number of Employees does not match with expected.", 6, result.size());
|
||||
assertThat(result.stream()
|
||||
.map(DeptEmployee::getDesignation)
|
||||
.map(DeptEmployee::getTitle)
|
||||
.distinct()
|
||||
.collect(Collectors.toList()), containsInAnyOrder(designations.toArray()));
|
||||
.collect(Collectors.toList()), containsInAnyOrder(titles.toArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCriteriaQuery_whenSearchedDepartmentLike_thenResultIsFilteredByDepartment() {
|
||||
List<DeptEmployee> result = searchService.searchByDepartmentQuery("Sales");
|
||||
assertEquals("Number of Employees does not match with expected.", 7, result.size());
|
||||
// assertThat(result.stream().map(DeptEmployee::getDesignation).distinct().collect(Collectors.toList()), containsInAnyOrder(designations.toArray()));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,13 +3,12 @@ package com.baeldung.jpa.stringcast;
|
|||
import javax.persistence.*;
|
||||
|
||||
@SqlResultSetMapping(name = "textQueryMapping", classes = {
|
||||
@ConstructorResult(targetClass = DummyEntity.class, columns = {
|
||||
@ConstructorResult(targetClass = Message.class, columns = {
|
||||
@ColumnResult(name = "text")
|
||||
})
|
||||
})
|
||||
@Entity
|
||||
@Table(name = "dummy")
|
||||
public class DummyEntity {
|
||||
public class Message {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
|
@ -17,11 +16,11 @@ public class DummyEntity {
|
|||
|
||||
private String text;
|
||||
|
||||
public DummyEntity() {
|
||||
public Message() {
|
||||
|
||||
}
|
||||
|
||||
public DummyEntity(String text) {
|
||||
public Message(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
|
@ -23,7 +23,7 @@
|
|||
|
||||
<persistence-unit name="jpa-h2">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.stringcast.DummyEntity</class>
|
||||
<class>com.baeldung.jpa.stringcast.Message</class>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
|
||||
|
|
|
@ -3,10 +3,7 @@ package com.baeldung.jpa.stringcast;
|
|||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.EntityTransaction;
|
||||
import javax.persistence.Persistence;
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
@ -22,18 +19,18 @@ public class SpringCastUnitTest {
|
|||
em = emFactory.createEntityManager();
|
||||
|
||||
// insert an object into the db
|
||||
DummyEntity dummyEntity = new DummyEntity();
|
||||
dummyEntity.setText("text");
|
||||
Message message = new Message();
|
||||
message.setText("text");
|
||||
|
||||
EntityTransaction tr = em.getTransaction();
|
||||
tr.begin();
|
||||
em.persist(dummyEntity);
|
||||
em.persist(message);
|
||||
tr.commit();
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void givenExecutorNoCastCheck_whenQueryReturnsOneColumn_thenClassCastThrown() {
|
||||
List<String[]> results = QueryExecutor.executeNativeQueryNoCastCheck("select text from dummy", em);
|
||||
List<String[]> results = QueryExecutor.executeNativeQueryNoCastCheck("select text from message", em);
|
||||
|
||||
// fails
|
||||
for (String[] row : results) {
|
||||
|
@ -43,13 +40,13 @@ public class SpringCastUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenExecutorWithCastCheck_whenQueryReturnsOneColumn_thenNoClassCastThrown() {
|
||||
List<String[]> results = QueryExecutor.executeNativeQueryWithCastCheck("select text from dummy", em);
|
||||
List<String[]> results = QueryExecutor.executeNativeQueryWithCastCheck("select text from message", em);
|
||||
assertEquals("text", results.get(0)[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExecutorGeneric_whenQueryReturnsOneColumn_thenNoClassCastThrown() {
|
||||
List<DummyEntity> results = QueryExecutor.executeNativeQueryGeneric("select text from dummy", "textQueryMapping", em);
|
||||
List<Message> results = QueryExecutor.executeNativeQueryGeneric("select text from message", "textQueryMapping", em);
|
||||
assertEquals("text", results.get(0).getText());
|
||||
}
|
||||
|
||||
|
|
|
@ -20,7 +20,7 @@
|
|||
|
||||
<persistence-unit name="jpa-h2">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.stringcast.DummyEntity</class>
|
||||
<class>com.baeldung.jpa.stringcast.Message</class>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
|
||||
|
|
|
@ -4,3 +4,4 @@
|
|||
- [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source)
|
||||
- [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql)
|
||||
- [Configuring a Tomcat Connection Pool in Spring Boot](https://www.baeldung.com/spring-boot-tomcat-connection-pool)
|
||||
- [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot)
|
||||
|
|
|
@ -15,6 +15,7 @@
|
|||
- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date)
|
||||
- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd)
|
||||
- [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save)
|
||||
- [Limiting Query Results with JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results)
|
||||
|
||||
### Eclipse Config
|
||||
After importing the project into Eclipse, you may see the following error:
|
||||
|
|
|
@ -12,3 +12,4 @@
|
|||
- [Spring Data MongoDB: Projections and Aggregations](http://www.baeldung.com/spring-data-mongodb-projections-aggregations)
|
||||
- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
|
||||
- [Spring Data MongoDB Transactions](https://www.baeldung.com/spring-data-mongodb-transactions )
|
||||
- [ZonedDateTime with Spring Data MongoDB](https://www.baeldung.com/spring-data-mongodb-zoneddatetime)
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Spring Security OAuth Login with WebFlux](https://www.baeldung.com/spring-oauth-login-webflux)
|
|
@ -33,3 +33,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
- [Spring Cache – Creating a Custom KeyGenerator](http://www.baeldung.com/spring-cache-custom-keygenerator)
|
||||
- [Spring @Primary Annotation](http://www.baeldung.com/spring-primary)
|
||||
- [Spring Events](https://www.baeldung.com/spring-events)
|
||||
- [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations)
|
||||
|
|
|
@ -5,7 +5,6 @@
|
|||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-amqp-simple</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<name>Spring AMQP Simple App</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-1</artifactId>
|
||||
|
|
|
@ -9,3 +9,4 @@
|
|||
- [Display RSS Feed with Spring MVC](http://www.baeldung.com/spring-mvc-rss-feed)
|
||||
- [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao)
|
||||
- [Cache Eviction in Spring Boot](https://www.baeldung.com/spring-boot-evict-cache)
|
||||
- [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api)
|
|
@ -15,6 +15,7 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
|
@ -23,6 +24,7 @@
|
|||
<groupId>org.apache.tomcat.embed</groupId>
|
||||
<artifactId>tomcat-embed-jasper</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--JSF -->
|
||||
<dependency>
|
||||
<groupId>org.glassfish</groupId>
|
||||
|
@ -30,17 +32,13 @@
|
|||
<version>2.3.7</version>
|
||||
</dependency>
|
||||
|
||||
<!--Test -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- ROME for RSS -->
|
||||
<dependency>
|
||||
<groupId>com.rometools</groupId>
|
||||
|
@ -48,6 +46,7 @@
|
|||
<version>${rome.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Validation -->
|
||||
<dependency>
|
||||
<groupId>org.hibernate.validator</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
|
@ -56,6 +55,23 @@
|
|||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Fox 2 -->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>${spring.fox.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${spring.fox.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -72,6 +88,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<spring.fox.version>2.9.2</spring.fox.version>
|
||||
<!-- ROME for RSS -->
|
||||
<rome.version>1.10.0</rome.version>
|
||||
<start-class>com.baeldung.springbootmvc.SpringBootMvcApplication</start-class>
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.swaggerboot;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
package com.baeldung.swaggerboot.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.service.ApiInfo;
|
||||
import springfox.documentation.service.Contact;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
import springfox.documentation.swagger.web.*;
|
||||
import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@Configuration
|
||||
@EnableSwagger2
|
||||
@ComponentScan("com.baeldung.swaggerboot.controller")
|
||||
public class SpringFoxConfig {
|
||||
|
||||
private ApiInfo apiInfo() {
|
||||
return new ApiInfo(
|
||||
"My REST API",
|
||||
"Some custom description of API.",
|
||||
"API TOS",
|
||||
"Terms of service",
|
||||
new Contact("John Doe", "www.example.com", "myeaddress@company.com"),
|
||||
"License of API",
|
||||
"API license URL",
|
||||
Collections.emptyList());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Docket api() {
|
||||
return new Docket(DocumentationType.SWAGGER_2)
|
||||
.apiInfo(apiInfo())
|
||||
.select()
|
||||
.apis(RequestHandlerSelectors.any())
|
||||
.paths(PathSelectors.any())
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* SwaggerUI information
|
||||
*/
|
||||
|
||||
@Bean
|
||||
UiConfiguration uiConfig() {
|
||||
return UiConfigurationBuilder.builder()
|
||||
.deepLinking(true)
|
||||
.displayOperationId(false)
|
||||
.defaultModelsExpandDepth(1)
|
||||
.defaultModelExpandDepth(1)
|
||||
.defaultModelRendering(ModelRendering.EXAMPLE)
|
||||
.displayRequestDuration(false)
|
||||
.docExpansion(DocExpansion.NONE)
|
||||
.filter(false)
|
||||
.maxDisplayedTags(null)
|
||||
.operationsSorter(OperationsSorter.ALPHA)
|
||||
.showExtensions(false)
|
||||
.tagsSorter(TagsSorter.ALPHA)
|
||||
.supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
|
||||
.validatorUrl(null)
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.swaggerboot.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class RegularRestController {
|
||||
|
||||
@GetMapping("home")
|
||||
public String getSession() {
|
||||
return "Hello";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
spring.main.allow-bean-definition-overriding=true
|
|
@ -34,4 +34,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
- [Introduction to Chaos Monkey](https://www.baeldung.com/spring-boot-chaos-monkey)
|
||||
- [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning)
|
||||
- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties)
|
||||
- [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report)
|
||||
- [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report)
|
||||
- [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information)
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
<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>spring-boot</artifactId>
|
||||
|
@ -55,6 +56,14 @@
|
|||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ehcache</groupId>
|
||||
<artifactId>ehcache</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-ehcache</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
|
@ -70,6 +79,11 @@
|
|||
<artifactId>graphql-java-tools</artifactId>
|
||||
<version>${graphql-java-tools.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphiql-spring-boot-starter</artifactId>
|
||||
<version>${graphiql-spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
@ -143,10 +157,10 @@
|
|||
<artifactId>chaos-monkey-spring-boot</artifactId>
|
||||
<version>${chaos.monkey.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -170,6 +184,26 @@
|
|||
<groupId>pl.project13.maven</groupId>
|
||||
<artifactId>git-commit-id-plugin</artifactId>
|
||||
<version>${git-commit-id-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>get-the-git-infos</id>
|
||||
<goals>
|
||||
<goal>revision</goal>
|
||||
</goals>
|
||||
<phase>initialize</phase>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>validate-the-git-infos</id>
|
||||
<goals>
|
||||
<goal>validateRevision</goal>
|
||||
</goals>
|
||||
<phase>package</phase>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<generateGitPropertiesFile>true</generateGitPropertiesFile>
|
||||
<generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
|
@ -220,10 +254,11 @@
|
|||
<togglz.version>2.4.1.Final</togglz.version>
|
||||
<rome.version>1.9.0</rome.version>
|
||||
<chaos.monkey.version>2.0.0</chaos.monkey.version>
|
||||
<graphql-spring-boot-starter.version>3.6.0</graphql-spring-boot-starter.version>
|
||||
<graphql-java-tools.version>3.2.0</graphql-java-tools.version>
|
||||
<graphql-spring-boot-starter.version>5.0.2</graphql-spring-boot-starter.version>
|
||||
<graphiql-spring-boot-starter.version>5.0.2</graphiql-spring-boot-starter.version>
|
||||
<graphql-java-tools.version>5.2.4</graphql-java-tools.version>
|
||||
<guava.version>18.0</guava.version>
|
||||
<git-commit-id-plugin.version>2.2.4</git-commit-id-plugin.version>
|
||||
<git-commit-id-plugin.version>2.2.4</git-commit-id-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -30,7 +30,7 @@ public class ContactInfoValidator implements ConstraintValidator<ContactInfo, St
|
|||
if (StringUtils.isEmptyOrWhitespace(expressionType)) {
|
||||
LOG.error("Contact info type missing!");
|
||||
} else {
|
||||
pattern = expressionRepository.findOne(expressionType).map(ContactInfoExpression::getPattern).orElse("");
|
||||
pattern = expressionRepository.findById(expressionType).map(ContactInfoExpression::getPattern).orElse("");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -9,7 +9,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|||
public class DynamicValidationApp {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("security.basic.enabled", "false");
|
||||
SpringApplication.run(DynamicValidationApp.class, args);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,5 +7,5 @@ import org.springframework.data.repository.Repository;
|
|||
import com.baeldung.dynamicvalidation.model.ContactInfoExpression;
|
||||
|
||||
public interface ContactInfoExpressionRepository extends Repository<ContactInfoExpression, String> {
|
||||
Optional<ContactInfoExpression> findOne(String id);
|
||||
Optional<ContactInfoExpression> findById(String id);
|
||||
}
|
||||
|
|
|
@ -9,7 +9,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|||
public class FailureAnalyzerApplication {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("security.basic.enabled", "false");
|
||||
SpringApplication.run(FailureAnalyzerApplication.class, args);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,7 +9,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|||
public class InternationalizationApp {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("security.basic.enabled", "false");
|
||||
SpringApplication.run(InternationalizationApp.class, args);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,18 +1,17 @@
|
|||
package com.baeldung.rss;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages = "com.baeldung.rss")
|
||||
public class RssApp {
|
||||
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("security.basic.enabled", "false");
|
||||
SpringApplication.run(RssApp.class, args);
|
||||
}
|
||||
|
||||
|
|
|
@ -9,7 +9,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|||
public class ToggleApplication {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("security.basic.enabled", "false");
|
||||
SpringApplication.run(ToggleApplication.class, args);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,8 +4,6 @@ import org.baeldung.demo.model.Foo;
|
|||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
|
||||
|
||||
@EntityScan(basePackageClasses = Foo.class)
|
||||
@SpringBootApplication
|
||||
|
@ -15,9 +13,4 @@ public class Application {
|
|||
System.setProperty("spring.profiles.active", "exception");
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public HibernateJpaSessionFactoryBean sessionFactory() {
|
||||
return new HibernateJpaSessionFactoryBean();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
package org.baeldung.session.exception.repository;
|
||||
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
|
||||
import org.baeldung.demo.model.Foo;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
@ -10,16 +12,15 @@ import org.springframework.stereotype.Repository;
|
|||
@Repository
|
||||
public class FooRepositoryImpl implements FooRepository {
|
||||
@Autowired
|
||||
private SessionFactory sessionFactory;
|
||||
private EntityManagerFactory emf;
|
||||
|
||||
@Override
|
||||
public void save(Foo foo) {
|
||||
sessionFactory.getCurrentSession().saveOrUpdate(foo);
|
||||
emf.unwrap(SessionFactory.class).getCurrentSession().saveOrUpdate(foo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Foo get(Integer id) {
|
||||
return sessionFactory.getCurrentSession().get(Foo.class, id);
|
||||
return emf.unwrap(SessionFactory.class).getCurrentSession().get(Foo.class, id);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer
|
|
@ -7,7 +7,7 @@ spring.jpa.show-sql=true
|
|||
spring.jpa.hibernate.ddl-auto = update
|
||||
|
||||
management.endpoints.jmx.domain=Spring Sample Application
|
||||
management.endpoints.jmx.uniqueNames=true
|
||||
spring.jmx.unique-names=true
|
||||
|
||||
management.endpoints.web.exposure.include=*
|
||||
management.endpoint.shutdown.enabled=true
|
||||
|
@ -17,7 +17,6 @@ management.endpoint.shutdown.enabled=true
|
|||
##endpoints.jolokia.path=jolokia
|
||||
|
||||
spring.jmx.enabled=true
|
||||
management.endpoints.jmx.enabled=true
|
||||
|
||||
## for pretty printing of json when endpoints accessed over HTTP
|
||||
http.mappers.jsonPrettyPrint=true
|
||||
|
|
|
@ -1,6 +1,2 @@
|
|||
spring.output.ansi.enabled=never
|
||||
server.port=7070
|
||||
|
||||
# Security
|
||||
security.user.name=admin
|
||||
security.user.password=password
|
|
@ -20,7 +20,6 @@ import static org.junit.Assert.assertTrue;
|
|||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class)
|
||||
@TestPropertySource(properties = { "security.basic.enabled=false" })
|
||||
public class SpringBootWithServletComponentIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
|
|
@ -19,7 +19,6 @@ import org.springframework.test.context.junit4.SpringRunner;
|
|||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class)
|
||||
@TestPropertySource(properties = { "security.basic.enabled=false" })
|
||||
public class SpringBootWithoutServletComponentIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
|
|
@ -1,31 +1,34 @@
|
|||
package com.baeldung.displayallbeans;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.BDDAssertions.then;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.actuate.beans.BeansEndpoint.ContextBeans;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.boot.web.server.LocalServerPort;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.RequestEntity;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.BDDAssertions.then;
|
||||
import static org.hamcrest.CoreMatchers.hasItem;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@TestPropertySource(properties = { "management.port=0", "endpoints.beans.id=springbeans", "endpoints.beans.sensitive=false" })
|
||||
@TestPropertySource(properties = { "management.port=0", "management.endpoints.web.exposure.include=*" })
|
||||
public class DisplayBeanIntegrationTest {
|
||||
|
||||
@LocalServerPort
|
||||
|
@ -40,6 +43,8 @@ public class DisplayBeanIntegrationTest {
|
|||
@Autowired
|
||||
private WebApplicationContext context;
|
||||
|
||||
private static final String ACTUATOR_PATH = "/actuator";
|
||||
|
||||
@Test
|
||||
public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception {
|
||||
ResponseEntity<String> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/displayallbeans", String.class);
|
||||
|
@ -49,22 +54,27 @@ public class DisplayBeanIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception {
|
||||
@SuppressWarnings("rawtypes")
|
||||
ResponseEntity<List> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class);
|
||||
ParameterizedTypeReference<Map<String, ContextBeans>> responseType = new ParameterizedTypeReference<Map<String, ContextBeans>>() {
|
||||
};
|
||||
RequestEntity<Void> requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans"))
|
||||
.accept(MediaType.APPLICATION_JSON)
|
||||
.build();
|
||||
ResponseEntity<Map<String, ContextBeans>> entity = this.testRestTemplate.exchange(requestEntity, responseType);
|
||||
|
||||
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throws Exception {
|
||||
@SuppressWarnings("rawtypes")
|
||||
ResponseEntity<List> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class);
|
||||
RequestEntity<Void> requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans"))
|
||||
.accept(MediaType.APPLICATION_JSON)
|
||||
.build();
|
||||
ResponseEntity<BeanActuatorResponse> entity = this.testRestTemplate.exchange(requestEntity, BeanActuatorResponse.class);
|
||||
|
||||
List<Map<String, Object>> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans");
|
||||
List<String> beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList());
|
||||
Collection<String> beanNamesList = entity.getBody()
|
||||
.getBeans();
|
||||
|
||||
assertThat(beanNamesList, hasItem("fooController"));
|
||||
assertThat(beanNamesList, hasItem("fooService"));
|
||||
assertThat(beanNamesList).contains("fooController", "fooService");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -72,7 +82,20 @@ public class DisplayBeanIntegrationTest {
|
|||
String[] beanNames = context.getBeanDefinitionNames();
|
||||
|
||||
List<String> beanNamesList = Arrays.asList(beanNames);
|
||||
assertTrue(beanNamesList.contains("fooController"));
|
||||
assertTrue(beanNamesList.contains("fooService"));
|
||||
assertThat(beanNamesList).contains("fooController", "fooService");
|
||||
}
|
||||
|
||||
private static class BeanActuatorResponse {
|
||||
private Map<String, Map<String, Map<String, Map<String, Object>>>> contexts;
|
||||
|
||||
public Collection<String> getBeans() {
|
||||
return this.contexts.get("application")
|
||||
.get("beans")
|
||||
.keySet();
|
||||
}
|
||||
|
||||
public Map<String, Map<String, Map<String, Map<String, Object>>>> getContexts() {
|
||||
return contexts;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.failureanalyzer;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.BeanCreationException;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
|
||||
import com.baeldung.failureanalyzer.utils.ListAppender;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
|
||||
public class FailureAnalyzerAppIntegrationTest {
|
||||
|
||||
private static final String EXPECTED_ANALYSIS_DESCRIPTION_TITLE = "Description:";
|
||||
private static final String EXPECTED_ANALYSIS_DESCRIPTION_CONTENT = "The bean myDAO could not be injected as com.baeldung.failureanalyzer.MyDAO because it is of type com.baeldung.failureanalyzer.MySecondDAO";
|
||||
private static final String EXPECTED_ANALYSIS_ACTION_TITLE = "Action:";
|
||||
private static final String EXPECTED_ANALYSIS_ACTION_CONTENT = "Consider creating a bean with name myDAO of type com.baeldung.failureanalyzer.MyDAO";
|
||||
|
||||
@BeforeEach
|
||||
public void clearLogList() {
|
||||
ListAppender.clearEventList();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBeanCreationErrorInContext_whenContextLoaded_thenFailureAnalyzerLogsReport() {
|
||||
try {
|
||||
SpringApplication.run(FailureAnalyzerApplication.class);
|
||||
} catch (BeanCreationException e) {
|
||||
Collection<String> allLoggedEntries = ListAppender.getEvents()
|
||||
.stream()
|
||||
.map(ILoggingEvent::getFormattedMessage)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(allLoggedEntries).anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_DESCRIPTION_TITLE))
|
||||
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_DESCRIPTION_CONTENT))
|
||||
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_ACTION_TITLE))
|
||||
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_ACTION_CONTENT));
|
||||
return;
|
||||
}
|
||||
throw new IllegalStateException("Context load should be failing due to a BeanCreationException!");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.failureanalyzer.utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.AppenderBase;
|
||||
|
||||
public class ListAppender extends AppenderBase<ILoggingEvent> {
|
||||
|
||||
static private List<ILoggingEvent> events = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
protected void append(ILoggingEvent eventObject) {
|
||||
events.add(eventObject);
|
||||
}
|
||||
|
||||
public static List<ILoggingEvent> getEvents() {
|
||||
return events;
|
||||
}
|
||||
|
||||
public static void clearEventList() {
|
||||
events.clear();
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue