Merge remote-tracking branch 'upstream/master' into BAEL-2688

This commit is contained in:
pcoates 2019-08-02 17:41:35 +01:00
commit b8934b1c67
480 changed files with 7700 additions and 1016 deletions

View File

@ -1,12 +1,16 @@
The "REST with Spring" Classes
The Courses
==============================
Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material): <br/>
**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
And here's the Master Class of Learn Spring Security: <br/>
**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
Here's the new "Learn Spring" course: <br/>
**[>> LEARN SPRING - THE MASTER CLASS](https://www.baeldung.com/learn-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=ls#master-class)**
Here's the Master Class of "REST With Spring" (along with the new announced Boot 2 material): <br/>
**[>> THE REST WITH SPRING - MASTER CLASS](https://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
And here's the Master Class of "Learn Spring Security": <br/>
**[>> LEARN SPRING SECURITY - MASTER CLASS](https://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
@ -15,7 +19,7 @@ Java and Spring Tutorials
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security.
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
In additional to Spring, the modules here are covering a number of aspects in Java.
Building the project
@ -32,8 +36,15 @@ Running a Spring Boot module
====================
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
###Running Tests
Working with the IDE
====================
This repo contains a large number of modules.
When you're working with an individual module, there's no need to import all of them (or build all of them) - you can simply import that particular module in either Eclipse or IntelliJ.
Running Tests
=============
The command `mvn clean install` will run the unit tests in a module.
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`

View File

@ -0,0 +1,30 @@
package com.baeldung.algorithms.stringsortingbynumber;
import java.util.Comparator;
public final class NaturalOrderComparators {
private static final String DIGIT_AND_DECIMAL_REGEX = "[^\\d.]";
private NaturalOrderComparators() {
throw new AssertionError("Let's keep this static");
}
public static Comparator<String> createNaturalOrderRegexComparator() {
return Comparator.comparingDouble(NaturalOrderComparators::parseStringToNumber);
}
private static double parseStringToNumber(String input){
final String digitsOnly = input.replaceAll(DIGIT_AND_DECIMAL_REGEX, "");
if("".equals(digitsOnly)) return 0;
try{
return Double.parseDouble(digitsOnly);
}catch (NumberFormatException nfe){
return 0;
}
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.algorithms.stringsortingbynumber;
import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class NaturalOrderComparatorsUnitTest {
@Test
public void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() {
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d");
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
List<String> expected = Arrays.asList("a1", "d2.2", "d2.3d", "d2.4", "b3", "c4");
assertEquals(expected, testStrings);
}
@Test
public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() {
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d");
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.4", "b3", "c4");
assertEquals(expected, testStrings);
}
@Test
public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() {
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d");
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.f4", "b3", "c4");
assertEquals(expected, testStrings);
}
@Test
public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() {
List<String> testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5
List<String> expected = Arrays.asList("b3ght3.2", "something65.thensomething5", "a1b2c5" );
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
assertEquals(expected, testStrings);
}
@Test
public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() {
List<String> testStrings = Arrays.asList("a", "c", "d", "e");
List<String> expected = new ArrayList<>(testStrings);
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
assertEquals(expected, testStrings);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.algorithms.shellsort;
public class ShellSort {
public static void sort(int arrayToSort[]) {
int n = arrayToSort.length;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int key = arrayToSort[i];
int j = i;
while (j >= gap && arrayToSort[j - gap] > key) {
arrayToSort[j] = arrayToSort[j - gap];
j -= gap;
}
arrayToSort[j] = key;
}
}
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.shellsort;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class ShellSortUnitTest {
@Test
public void givenUnsortedArray_whenShellSort_thenSortedAsc() {
int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8};
ShellSort.sort(input);
int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82};
assertArrayEquals("the two arrays are not equal", expected, input);
}
}

View File

@ -18,12 +18,6 @@
<groupId>org.axonframework</groupId>
<artifactId>axon-spring-boot-starter</artifactId>
<version>${axon.version}</version>
<exclusions>
<exclusion>
<groupId>org.axonframework</groupId>
<artifactId>axon-server-connector</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@ -58,7 +52,7 @@
</dependencies>
<properties>
<axon.version>4.0.3</axon.version>
<axon.version>4.1.2</axon.version>
</properties>
</project>

View File

@ -13,6 +13,7 @@ import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
import com.baeldung.axon.coreapi.events.OrderPlacedEvent;
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
@Aggregate
public class OrderAggregate {
@ -34,7 +35,7 @@ public class OrderAggregate {
@CommandHandler
public void handle(ShipOrderCommand command) {
if (!orderConfirmed) {
throw new IllegalStateException("Cannot ship an order which has not been confirmed yet.");
throw new UnconfirmedOrderException();
}
apply(new OrderShippedEvent(orderId));
@ -43,12 +44,12 @@ public class OrderAggregate {
@EventSourcingHandler
public void on(OrderPlacedEvent event) {
this.orderId = event.getOrderId();
orderConfirmed = false;
this.orderConfirmed = false;
}
@EventSourcingHandler
public void on(OrderConfirmedEvent event) {
orderConfirmed = true;
this.orderConfirmed = true;
}
protected OrderAggregate() {

View File

@ -0,0 +1,8 @@
package com.baeldung.axon.coreapi.exceptions;
public class UnconfirmedOrderException extends IllegalStateException {
public UnconfirmedOrderException() {
super("Cannot ship an order which has not been confirmed yet.");
}
}

View File

@ -5,6 +5,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.axonframework.config.ProcessingGroup;
import org.axonframework.eventhandling.EventHandler;
import org.axonframework.queryhandling.QueryHandler;
import org.springframework.stereotype.Service;
@ -16,6 +17,7 @@ import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
import com.baeldung.axon.coreapi.queries.OrderedProduct;
@Service
@ProcessingGroup("ordered-products")
public class OrderedProductsEventHandler {
private final Map<String, OrderedProduct> orderedProducts = new HashMap<>();

View File

@ -0,0 +1 @@
spring.application.name=Order Management Service

View File

@ -2,6 +2,7 @@ package com.baeldung.axon.commandmodel;
import java.util.UUID;
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.*;
@ -41,12 +42,12 @@ public class OrderAggregateUnitTest {
}
@Test
public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowIllegalStateException() {
public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowUnconfirmedOrderException() {
String orderId = UUID.randomUUID().toString();
String product = "Deluxe Chair";
fixture.given(new OrderPlacedEvent(orderId, product))
.when(new ShipOrderCommand(orderId))
.expectException(IllegalStateException.class);
.expectException(UnconfirmedOrderException.class);
}
@Test

View File

@ -1,3 +1,4 @@
## Relevant articles:
## Relevant Articles:
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)

View File

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

View File

@ -0,0 +1,50 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-arrays-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-arrays-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-arrays-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- util -->
<commons-lang3.version>3.9</commons-lang3.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -0,0 +1,45 @@
package com.baeldung.array.looping;
public class LoopDiagonally {
public String loopDiagonally(String[][] twoDArray) {
int length = twoDArray.length;
int diagonalLines = (length + length) - 1;
int itemsInDiagonal = 0;
int midPoint = (diagonalLines / 2) + 1;
StringBuilder output = new StringBuilder();
for (int i = 1; i <= diagonalLines; i++) {
StringBuilder items = new StringBuilder();
int rowIndex;
int columnIndex;
if (i <= midPoint) {
itemsInDiagonal++;
for (int j = 0; j < itemsInDiagonal; j++) {
rowIndex = (i - j) - 1;
columnIndex = j;
items.append(twoDArray[rowIndex][columnIndex]);
}
} else {
itemsInDiagonal--;
for (int j = 0; j < itemsInDiagonal; j++) {
rowIndex = (length - 1) - j;
columnIndex = (i - length) + j;
items.append(twoDArray[rowIndex][columnIndex]);
}
}
if (i != diagonalLines) {
output.append(items).append(" ");
} else {
output.append(items);
}
}
return output.toString();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.array.looping;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LoopDiagonallyUnitTest {
@Test
public void twoArrayIsLoopedDiagonallyAsExpected() {
LoopDiagonally loopDiagonally = new LoopDiagonally();
String[][] twoDArray = {{"a", "b", "c"},
{"d", "e", "f"},
{"g", "h", "i"}};
String output = loopDiagonally.loopDiagonally(twoDArray);
assertEquals("a db gec hf i", output);
}
}

View File

@ -2,7 +2,10 @@ package com.baeldung.array;
import com.baeldung.arraycopy.model.Employee;
import java.util.Comparator;
public class SortedArrayChecker {
boolean isSorted(int[] array, int length) {
if (array == null || length < 2)
return true;
@ -22,7 +25,7 @@ public class SortedArrayChecker {
return true;
}
boolean isSorted(String[] array, int length) {
boolean isSorted(Comparable[] array, int length) {
if (array == null || length < 2)
return true;
@ -32,40 +35,31 @@ public class SortedArrayChecker {
return isSorted(array, length - 1);
}
boolean isSorted(String[] array) {
for (int i = 0; i < array.length - 1; ++i) {
if (array[i].compareTo(array[i + 1]) > 0)
return false;
}
return true;
}
boolean isSortedByName(Employee[] array) {
boolean isSorted(Comparable[] array) {
for (int i = 0; i < array.length - 1; ++i) {
if (array[i].getName().compareTo(array[i + 1].getName()) > 0)
if (array[i].compareTo(array[i + 1]) > 0)
return false;
}
return true;
}
boolean isSortedByAge(Employee[] array) {
for (int i = 0; i < array.length - 1; ++i) {
if (array[i].getAge() > (array[i + 1].getAge()))
return false;
boolean isSorted(Object[] array, Comparator comparator) {
for (int i = 0; i < array.length - 1; ++i) {
if (comparator.compare(array[i], (array[i + 1])) > 0)
return false;
}
return true;
}
return true;
}
boolean isSortedByAge(Employee[] array, int length) {
boolean isSorted(Object[] array, Comparator comparator, int length) {
if (array == null || length < 2)
return true;
if (array[length - 2].getAge() > array[length - 1].getAge())
if (comparator.compare(array[length - 2], array[length - 1]) > 0)
return false;
return isSortedByAge(array, length - 1);
return isSorted(array, comparator, length - 1);
}
}

View File

@ -4,32 +4,33 @@ import com.baeldung.arraycopy.model.Employee;
import org.junit.Before;
import org.junit.Test;
import java.util.Comparator;
import static org.assertj.core.api.Assertions.assertThat;
class SortedArrayCheckerUnitTest {
public class SortedArrayCheckerUnitTest {
private static final int[] INTEGER_SORTED = {1, 3, 5, 7, 9};
private static final int[] INTEGER_NOT_SORTED = {1, 3, 11, 7};
private static final String[] STRING_SORTED = {"abc", "cde", "fgh"};
private static final String[] STRING_NOT_SORTED = {"abc", "fgh", "cde", "ijk"};
private final Employee[] EMPLOYEES_SORTED_BY_NAME = {
private static final Employee[] EMPLOYEES_SORTED_BY_NAME = {
new Employee(1, "Carlos", 26),
new Employee(2, "Daniel", 31),
new Employee(3, "Marta", 27)};
private final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = {
private static final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = {
new Employee(1, "Daniel", 31),
new Employee(2, "Carlos", 26),
new Employee(3, "Marta", 27)};
private final Employee[] EMPLOYEES_SORTED_BY_AGE = {
private static final Employee[] EMPLOYEES_SORTED_BY_AGE = {
new Employee(1, "Carlos", 26),
new Employee(2, "Marta", 27),
new Employee(3, "Daniel", 31)};
private final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = {
private static final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = {
new Employee(1, "Marta", 27),
new Employee(2, "Carlos", 26),
new Employee(3, "Daniel", 31)};
@ -61,13 +62,18 @@ class SortedArrayCheckerUnitTest {
@Test
public void givenEmployeeArray_thenReturnIfItIsSortedOrNot() {
assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_SORTED_BY_NAME)).isEqualTo(true);
assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_NOT_SORTED_BY_NAME)).isEqualTo(false);
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(true);
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(false);
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE)).isEqualTo(true);
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE)).isEqualTo(false);
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).isEqualTo(true);
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).isEqualTo(false);
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE, EMPLOYEES_SORTED_BY_AGE.length)).isEqualTo(true);
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE, EMPLOYEES_NOT_SORTED_BY_AGE.length)).isEqualTo(false);
assertThat(sortedArrayChecker
.isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), EMPLOYEES_SORTED_BY_AGE.length))
.isEqualTo(true);
assertThat(sortedArrayChecker
.isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), EMPLOYEES_NOT_SORTED_BY_AGE.length))
.isEqualTo(false);
}
}

View File

@ -1,3 +1,3 @@
## Relevant articles:
## Relevant Articles:
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)

View File

@ -0,0 +1,24 @@
package com.baeldung.files;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner;
public class Main {
private static final String INPUT_FILE_NAME = "src/main/resources/input.txt";
public static void main(String... args) throws Exception {
System.out.printf("Total Number of Lines Using BufferedReader: %s%n", getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using LineNumberReader: %s%n", getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using Scanner: %s%n", getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using NIO Files: %s%n", getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using NIO FileChannel: %s%n", getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using Apache Commons IO: %s%n", getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using NIO Google Guava: %s%n", getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME));
}
}

View File

@ -0,0 +1,112 @@
package com.baeldung.files;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Stream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
public class NumberOfLineFinder {
public static int getTotalNumberOfLinesUsingBufferedReader(String fileName) {
int lines = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
while (reader.readLine() != null) {
lines++;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingLineNumberReader(String fileName) {
int lines = 0;
try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) {
reader.skip(Integer.MAX_VALUE);
lines = reader.getLineNumber() + 1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingScanner(String fileName) {
int lines = 0;
try (Scanner scanner = new Scanner(new FileReader(fileName))) {
while (scanner.hasNextLine()) {
scanner.nextLine();
lines++;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingNIOFiles(String fileName) {
int lines = 0;
try (Stream<String> fileStream = Files.lines(Paths.get(fileName))) {
lines = (int) fileStream.count();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingNIOFileChannel(String fileName) {
int lines = 1;
try (FileChannel channel = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ)) {
ByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, channel.size());
while (byteBuffer.hasRemaining()) {
byte currentChar = byteBuffer.get();
if (currentChar == '\n') {
lines++;
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingApacheCommonsIO(String fileName) {
int lines = 0;
try {
LineIterator lineIterator = FileUtils.lineIterator(new File(fileName));
while (lineIterator.hasNext()) {
lineIterator.nextLine();
lines++;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingGoogleGuava(String fileName) {
int lines = 0;
try {
List<String> lineItems = com.google.common.io.Files.readLines(Paths.get(fileName)
.toFile(), Charset.defaultCharset());
lines = lineItems.size();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.file;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class NumberOfLineFinderUnitTest {
private static final String INPUT_FILE_NAME = "src/main/resources/input.txt";
private static final int ACTUAL_LINE_COUNT = 45;
@Test
public void whenUsingBufferedReader_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingLineNumberReader_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingScanner_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingNIOFiles_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingNIOFileChannel_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingApacheCommonsIO_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingGoogleGuava_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.relationships.aggregation;
import java.util.List;
public class Car {
private List<Wheel> wheels;
}

View File

@ -0,0 +1,13 @@
package com.baeldung.relationships.aggregation;
import java.util.List;
public class CarWithStaticInnerWheel {
private List<Wheel> wheels;
public static class Wheel {
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.relationships.aggregation;
public class Wheel {
private Car car;
}

View File

@ -0,0 +1,7 @@
package com.baeldung.relationships.association;
public class Child {
private Mother mother;
}

View File

@ -0,0 +1,9 @@
package com.baeldung.relationships.association;
import java.util.List;
public class Mother {
private List<Child> children;
}

View File

@ -0,0 +1,18 @@
package com.baeldung.relationships.composition;
import java.util.List;
public class Building {
private String address;
private List<Room> rooms;
public class Room {
public String getBuildingAddress() {
return Building.this.address;
}
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.relationships.composition;
public class BuildingWithDefinitionRoomInMethod {
public Room createAnonymousRoom() {
return new Room() {
@Override
public void doInRoom() {}
};
}
public Room createInlineRoom() {
class InlineRoom implements Room {
@Override
public void doInRoom() {}
}
return new InlineRoom();
}
public Room createLambdaRoom() {
return () -> {};
}
public interface Room {
void doInRoom();
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.relationships.university;
import java.util.List;
public class Department {
private List<Professor> professors;
}

View File

@ -0,0 +1,10 @@
package com.baeldung.relationships.university;
import java.util.List;
public class Professor {
private List<Department> department;
private List<Professor> friends;
}

View File

@ -0,0 +1,9 @@
package com.baeldung.relationships.university;
import java.util.List;
public class University {
private List<Department> department;
}

View File

@ -0,0 +1,63 @@
package com.baeldung.incrementdecrementunaryoperator;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class IncrementDecrementUnaryOperatorUnitTest {
@Test
public void givenAnOperand_whenUsingPreIncrementUnaryOperator_thenOperandIsIncrementedByOne() {
int operand = 1;
++operand;
assertThat(operand).isEqualTo(2);
}
@Test
public void givenANumber_whenUsingPreIncrementUnaryOperatorInEvaluation_thenNumberIsIncrementedByOne() {
int operand = 1;
int number = ++operand;
assertThat(number).isEqualTo(2);
}
@Test
public void givenAnOperand_whenUsingPreDecrementUnaryOperator_thenOperandIsDecrementedByOne() {
int operand = 1;
--operand;
assertThat(operand).isEqualTo(0);
}
@Test
public void givenANumber_whenUsingPreDecrementUnaryOperatorInEvaluation_thenNumberIsDecrementedByOne() {
int operand = 1;
int number = --operand;
assertThat(number).isEqualTo(0);
}
@Test
public void givenAnOperand_whenUsingPostIncrementUnaryOperator_thenOperandIsIncrementedByOne() {
int operand = 1;
operand++;
assertThat(operand).isEqualTo(2);
}
@Test
public void givenANumber_whenUsingPostIncrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() {
int operand = 1;
int number = operand++;
assertThat(number).isEqualTo(1);
}
@Test
public void givenAnOperand_whenUsingPostDecrementUnaryOperator_thenOperandIsDecrementedByOne() {
int operand = 1;
operand--;
assertThat(operand).isEqualTo(0);
}
@Test
public void givenANumber_whenUsingPostDecrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() {
int operand = 1;
int number = operand--;
assertThat(number).isEqualTo(1);
}
}

View File

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

View File

@ -0,0 +1,20 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-networking-2</artifactId>
<name>core-java-networking-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
</dependencies>
<build>
<finalName>core-java-networking-2</finalName>
</build>
</project>

View File

@ -0,0 +1,25 @@
package com.baeldung.url;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlChecker {
public int getResponseCodeForURL(String address) throws IOException {
return getResponseCodeForURLUsing(address, "GET");
}
public int getResponseCodeForURLUsingHead(String address) throws IOException {
return getResponseCodeForURLUsing(address, "HEAD");
}
private int getResponseCodeForURLUsing(String address, String method) throws IOException {
HttpURLConnection.setFollowRedirects(false); // Set follow redirects to false
final URL url = new URL(address);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod(method);
return huc.getResponseCode();
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.url;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.Test;
public class UrlCheckerUnitTest {
@Test
public void givenValidUrl_WhenUsingHEAD_ThenReturn200() throws IOException {
UrlChecker tester = new UrlChecker();
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com");
assertEquals(200, responseCode);
}
@Test
public void givenInvalidIUrl_WhenUsingHEAD_ThenReturn404() throws IOException {
UrlChecker tester = new UrlChecker();
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com/unkownurl");
assertEquals(404, responseCode);
}
@Test
public void givenValidUrl_WhenUsingGET_ThenReturn200() throws IOException {
UrlChecker tester = new UrlChecker();
int responseCode = tester.getResponseCodeForURL("http://www.example.com");
assertEquals(200, responseCode);
}
@Test
public void givenInvalidIUrl_WhenUsingGET_ThenReturn404() throws IOException {
UrlChecker tester = new UrlChecker();
int responseCode = tester.getResponseCodeForURL("http://www.example.com/unkownurl");
assertEquals(404, responseCode);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.sasl;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.RealmCallback;
public class ClientCallbackHandler implements CallbackHandler {
@Override
public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException {
for (Callback cb : cbs) {
if (cb instanceof NameCallback) {
NameCallback nc = (NameCallback) cb;
nc.setName("username");
} else if (cb instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) cb;
pc.setPassword("password".toCharArray());
} else if (cb instanceof RealmCallback) {
RealmCallback rc = (RealmCallback) cb;
rc.setText("myServer");
}
}
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.sasl;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.AuthorizeCallback;
import javax.security.sasl.RealmCallback;
public class ServerCallbackHandler implements CallbackHandler {
@Override
public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException {
for (Callback cb : cbs) {
if (cb instanceof AuthorizeCallback) {
AuthorizeCallback ac = (AuthorizeCallback) cb;
ac.setAuthorized(true);
} else if (cb instanceof NameCallback) {
NameCallback nc = (NameCallback) cb;
nc.setName("username");
} else if (cb instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) cb;
pc.setPassword("password".toCharArray());
} else if (cb instanceof RealmCallback) {
RealmCallback rc = (RealmCallback) cb;
rc.setText("myServer");
}
}
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.sasl;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class SaslUnitTest {
private static final String MECHANISM = "DIGEST-MD5";
private static final String SERVER_NAME = "myServer";
private static final String PROTOCOL = "myProtocol";
private static final String AUTHORIZATION_ID = null;
private static final String QOP_LEVEL = "auth-conf";
private SaslServer saslServer;
private SaslClient saslClient;
@Before
public void setUp() throws SaslException {
ServerCallbackHandler serverHandler = new ServerCallbackHandler();
ClientCallbackHandler clientHandler = new ClientCallbackHandler();
Map<String, String> props = new HashMap<>();
props.put(Sasl.QOP, QOP_LEVEL);
saslServer = Sasl.createSaslServer(MECHANISM, PROTOCOL, SERVER_NAME, props, serverHandler);
saslClient = Sasl.createSaslClient(new String[] { MECHANISM }, AUTHORIZATION_ID, PROTOCOL, SERVER_NAME, props, clientHandler);
}
@Test
public void givenHandlers_whenStarted_thenAutenticationWorks() throws SaslException {
byte[] challenge;
byte[] response;
challenge = saslServer.evaluateResponse(new byte[0]);
response = saslClient.evaluateChallenge(challenge);
challenge = saslServer.evaluateResponse(response);
response = saslClient.evaluateChallenge(challenge);
assertTrue(saslServer.isComplete());
assertTrue(saslClient.isComplete());
String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP);
assertEquals("auth-conf", qop);
byte[] outgoing = "Baeldung".getBytes();
byte[] secureOutgoing = saslClient.wrap(outgoing, 0, outgoing.length);
byte[] secureIncoming = secureOutgoing;
byte[] incoming = saslServer.unwrap(secureIncoming, 0, secureIncoming.length);
assertEquals("Baeldung", new String(incoming, StandardCharsets.UTF_8));
}
@After
public void tearDown() throws SaslException {
saslClient.dispose();
saslServer.dispose();
}
}

View File

@ -0,0 +1,3 @@
## Relevant Articles
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)

View File

@ -17,6 +17,7 @@
<module>pre-jpms</module>
<module>core-java-exceptions</module>
<module>core-java-optional</module>
<module>core-java-networking-2</module>
</modules>
</project>

View File

@ -0,0 +1,72 @@
package com.baeldung.graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
public class Graph {
private Map<Integer, List<Integer>> adjVertices;
public Graph() {
this.adjVertices = new HashMap<Integer, List<Integer>>();
}
public void addVertex(int vertex) {
adjVertices.putIfAbsent(vertex, new ArrayList<>());
}
public void addEdge(int src, int dest) {
adjVertices.get(src).add(dest);
}
public void dfsWithoutRecursion(int start) {
Stack<Integer> stack = new Stack<Integer>();
boolean[] isVisited = new boolean[adjVertices.size()];
stack.push(start);
while (!stack.isEmpty()) {
int current = stack.pop();
isVisited[current] = true;
System.out.print(" " + current);
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
stack.push(dest);
}
}
}
public void dfs(int start) {
boolean[] isVisited = new boolean[adjVertices.size()];
dfsRecursive(start, isVisited);
}
private void dfsRecursive(int current, boolean[] isVisited) {
isVisited[current] = true;
System.out.print(" " + current);
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
dfsRecursive(dest, isVisited);
}
}
public void topologicalSort(int start) {
Stack<Integer> result = new Stack<Integer>();
boolean[] isVisited = new boolean[adjVertices.size()];
topologicalSortRecursive(start, isVisited, result);
while (!result.isEmpty()) {
System.out.print(" " + result.pop());
}
}
private void topologicalSortRecursive(int current, boolean[] isVisited, Stack<Integer> result) {
isVisited[current] = true;
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
topologicalSortRecursive(dest, isVisited, result);
}
result.push(current);
}
}

View File

@ -2,6 +2,7 @@ package com.baeldung.tree;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class BinaryTree {
@ -147,6 +148,68 @@ public class BinaryTree {
}
}
public void traverseInOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Node current = root;
stack.push(root);
while(! stack.isEmpty()) {
while(current.left != null) {
current = current.left;
stack.push(current);
}
current = stack.pop();
System.out.print(" " + current.value);
if(current.right != null) {
current = current.right;
stack.push(current);
}
}
}
public void traversePreOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Node current = root;
stack.push(root);
while(! stack.isEmpty()) {
current = stack.pop();
System.out.print(" " + current.value);
if(current.right != null)
stack.push(current.right);
if(current.left != null)
stack.push(current.left);
}
}
public void traversePostOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Node prev = root;
Node current = root;
stack.push(root);
while (!stack.isEmpty()) {
current = stack.peek();
boolean hasChild = (current.left != null || current.right != null);
boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null));
if (!hasChild || isPrevLastChild) {
current = stack.pop();
System.out.print(" " + current.value);
prev = current;
} else {
if (current.right != null) {
stack.push(current.right);
}
if (current.left != null) {
stack.push(current.left);
}
}
}
}
class Node {
int value;
Node left;

View File

@ -0,0 +1,37 @@
package com.baeldung.graph;
import org.junit.Test;
public class GraphUnitTest {
@Test
public void givenDirectedGraph_whenDFS_thenPrintAllValues() {
Graph graph = createDirectedGraph();
graph.dfs(0);
System.out.println();
graph.dfsWithoutRecursion(0);
}
@Test
public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() {
Graph graph = createDirectedGraph();
graph.topologicalSort(0);
}
private Graph createDirectedGraph() {
Graph graph = new Graph();
graph.addVertex(0);
graph.addVertex(1);
graph.addVertex(2);
graph.addVertex(3);
graph.addVertex(4);
graph.addVertex(5);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 5);
return graph;
}
}

View File

@ -87,6 +87,8 @@ public class BinaryTreeUnitTest {
BinaryTree bt = createBinaryTree();
bt.traverseInOrder(bt.root);
System.out.println();
bt.traverseInOrderWithoutRecursion();
}
@Test
@ -95,6 +97,8 @@ public class BinaryTreeUnitTest {
BinaryTree bt = createBinaryTree();
bt.traversePreOrder(bt.root);
System.out.println();
bt.traversePreOrderWithoutRecursion();
}
@Test
@ -103,6 +107,8 @@ public class BinaryTreeUnitTest {
BinaryTree bt = createBinaryTree();
bt.traversePostOrder(bt.root);
System.out.println();
bt.traversePostOrderWithoutRecursion();
}
@Test

View File

@ -0,0 +1,148 @@
package com.baeldung.binarynumbers;
public class BinaryNumbers {
/**
* This method takes a decimal number and convert it into a binary number.
* example:- input:10, output:1010
*
* @param decimalNumber
* @return binary number
*/
public Integer convertDecimalToBinary(Integer decimalNumber) {
if (decimalNumber == 0) {
return decimalNumber;
}
StringBuilder binaryNumber = new StringBuilder();
while (decimalNumber > 0) {
int remainder = decimalNumber % 2;
int result = decimalNumber / 2;
binaryNumber.append(remainder);
decimalNumber = result;
}
binaryNumber = binaryNumber.reverse();
return Integer.valueOf(binaryNumber.toString());
}
/**
* This method takes a binary number and convert it into a decimal number.
* example:- input:101, output:5
*
* @param binary number
* @return decimal Number
*/
public Integer convertBinaryToDecimal(Integer binaryNumber) {
Integer result = 0;
Integer base = 1;
while (binaryNumber > 0) {
int lastDigit = binaryNumber % 10;
binaryNumber = binaryNumber / 10;
result += lastDigit * base;
base = base * 2;
}
return result;
}
/**
* This method accepts two binary numbers and returns sum of input numbers.
* Example:- firstNum: 101, secondNum: 100, output: 1001
*
* @param firstNum
* @param secondNum
* @return addition of input numbers
*/
public Integer addBinaryNumber(Integer firstNum, Integer secondNum) {
StringBuilder output = new StringBuilder();
int carry = 0;
int temp;
while (firstNum != 0 || secondNum != 0) {
temp = (firstNum % 10 + secondNum % 10 + carry) % 2;
output.append(temp);
carry = (firstNum % 10 + secondNum % 10 + carry) / 2;
firstNum = firstNum / 10;
secondNum = secondNum / 10;
}
if (carry != 0) {
output.append(carry);
}
return Integer.valueOf(output.reverse()
.toString());
}
/**
* This method takes two binary number as input and subtract second number from the first number.
* example:- firstNum: 1000, secondNum: 11, output: 101
* @param firstNum
* @param secondNum
* @return Result of subtraction of secondNum from first
*/
public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) {
int onesComplement = Integer.valueOf(getOnesComplement(secondNum));
StringBuilder output = new StringBuilder();
int carry = 0;
int temp;
while (firstNum != 0 || onesComplement != 0) {
temp = (firstNum % 10 + onesComplement % 10 + carry) % 2;
output.append(temp);
carry = (firstNum % 10 + onesComplement % 10 + carry) / 2;
firstNum = firstNum / 10;
onesComplement = onesComplement / 10;
}
String additionOfFirstNumAndOnesComplement = output.reverse()
.toString();
if (carry == 1) {
return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry);
} else {
return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement));
}
}
public Integer getOnesComplement(Integer num) {
StringBuilder onesComplement = new StringBuilder();
while (num > 0) {
int lastDigit = num % 10;
if (lastDigit == 0) {
onesComplement.append(1);
} else {
onesComplement.append(0);
}
num = num / 10;
}
return Integer.valueOf(onesComplement.reverse()
.toString());
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.binarynumbers;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class BinaryNumbersUnitTest {
private BinaryNumbers binaryNumbers = new BinaryNumbers();
@Test
public void given_decimalNumber_then_returnBinaryNumber() {
assertEquals(Integer.valueOf(1000), binaryNumbers.convertDecimalToBinary(8));
assertEquals(Integer.valueOf(10100), binaryNumbers.convertDecimalToBinary(20));
}
@Test
public void given_decimalNumber_then_convertToBinaryNumber() {
assertEquals("1000", Integer.toBinaryString(8));
assertEquals("10100", Integer.toBinaryString(20));
}
@Test
public void given_binaryNumber_then_ConvertToDecimalNumber() {
assertEquals(8, Integer.parseInt("1000", 2));
assertEquals(20, Integer.parseInt("10100", 2));
}
@Test
public void given_binaryNumber_then_returnDecimalNumber() {
assertEquals(Integer.valueOf(8), binaryNumbers.convertBinaryToDecimal(1000));
assertEquals(Integer.valueOf(20), binaryNumbers.convertBinaryToDecimal(10100));
}
@Test
public void given_twoBinaryNumber_then_returnAddition() {
// adding 4 and 10
assertEquals(Integer.valueOf(1110), binaryNumbers.addBinaryNumber(100, 1010));
// adding 26 and 14
assertEquals(Integer.valueOf(101000), binaryNumbers.addBinaryNumber(11010, 1110));
}
@Test
public void given_twoBinaryNumber_then_returnSubtraction() {
// subtracting 16 from 25
assertEquals(Integer.valueOf(1001), binaryNumbers.substractBinaryNumber(11001, 10000));
// subtracting 29 from 16, the output here is negative
assertEquals(Integer.valueOf(1101), binaryNumbers.substractBinaryNumber(10000, 11101));
}
@Test
public void given_binaryLiteral_thenReturnDecimalValue() {
byte five = 0b101;
assertEquals((byte) 5, five);
short three = 0b11;
assertEquals((short) 3, three);
int nine = 0B1001;
assertEquals(9, nine);
long twentyNine = 0B11101;
assertEquals(29, twentyNine);
int minusThirtySeven = -0B100101;
assertEquals(-37, minusThirtySeven);
}
}

View File

@ -3,5 +3,20 @@
- [Java Localization Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
- [Java Generate Random String](http://www.baeldung.com/java-random-string)
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
- [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)
- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list)
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters)
- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation)
- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram)
- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words)
- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings)
- [String Initialization in Java](https://www.baeldung.com/java-string-initialization)

View File

@ -40,6 +40,16 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -52,32 +62,54 @@
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<!-- Added for password generation -->
<dependency>
<groupId>org.passay</groupId>
<artifactId>passay</artifactId>
<version>${passay.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>com.vdurmont</groupId>
<artifactId>emoji-java</artifactId>
<version>${emoji-java.version}</version>
</dependency>
<dependency>
<groupId>org.ahocorasick</groupId>
<artifactId>ahocorasick</artifactId>
<version>${ahocorasick.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
<version>${validation-api.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.2.Final</version>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
<version>${javax.el-api.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
<version>${javax.el.version}</version>
</dependency>
</dependencies>
<build>
@ -105,9 +137,19 @@
<properties>
<commons-lang3.version>3.8.1</commons-lang3.version>
<commons-codec.version>1.10</commons-codec.version>
<passay.version>1.3.1</passay.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<emoji-java.version>4.0.0</emoji-java.version>
<ahocorasick.version>0.4.0</ahocorasick.version>
<icu4j.version>61.1</icu4j.version>
<guava.version>28.0-jre</guava.version>
<commons-text.version>1.4</commons-text.version>
<validation-api.version>2.0.0.Final</validation-api.version>
<hibernate-validator.version>6.0.2.Final</hibernate-validator.version>
<javax.el-api.version>3.0.0</javax.el-api.version>
<javax.el.version>2.2.6</javax.el.version>
</properties>
</project>

View File

@ -0,0 +1,29 @@
package com.baeldung.string.changecase;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import org.junit.Test;
public class ToLowerCaseUnitTest {
private static final Locale TURKISH = new Locale("tr");
private String name = "John Doe";
private String foreignUppercase = "\u0049";
@Test
public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() {
assertEquals("john doe", name.toLowerCase());
}
@Test
public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() {
assertEquals("\u0069", foreignUppercase.toLowerCase());
}
@Test
public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() {
assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH));
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.string.changecase;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import org.junit.Test;
public class ToUpperCaseUnitTest {
private static final Locale TURKISH = new Locale("tr");
private String name = "John Doe";
private String foreignLowercase = "\u0069";
@Test
public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() {
assertEquals("JOHN DOE", name.toUpperCase());
}
@Test
public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() {
assertEquals("\u0049", foreignLowercase.toUpperCase());
}
@Test
public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() {
assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH));
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.string.todouble;
import static org.junit.Assert.assertEquals;
import java.text.DecimalFormat;
import java.text.ParseException;
import org.junit.Test;
public class StringToDoubleConversionUnitTest {
@Test
public void givenValidString_WhenParseDouble_ThenResultIsPrimitiveDouble() {
assertEquals(1.23, Double.parseDouble("1.23"), 0.000001);
}
@Test(expected = NullPointerException.class)
public void givenNullString_WhenParseDouble_ThenNullPointerExceptionIsThrown() {
Double.parseDouble(null);
}
@Test(expected = NumberFormatException.class)
public void givenInalidString_WhenParseDouble_ThenNumberFormatExceptionIsThrown() {
Double.parseDouble("&");
}
@Test
public void givenValidString_WhenValueOf_ThenResultIsPrimitiveDouble() {
assertEquals(1.23, Double.valueOf("1.23"), 0.000001);
}
@Test(expected = NullPointerException.class)
public void givenNullString_WhenValueOf_ThenNullPointerExceptionIsThrown() {
Double.valueOf(null);
}
@Test(expected = NumberFormatException.class)
public void givenInalidString_WhenValueOf_ThenNumberFormatExceptionIsThrown() {
Double.valueOf("&");
}
@Test
public void givenValidString_WhenDecimalFormat_ThenResultIsValidDouble() throws ParseException {
assertEquals(1.23, new DecimalFormat("#").parse("1.23").doubleValue(), 0.000001);
}
@Test(expected = NullPointerException.class)
public void givenNullString_WhenDecimalFormat_ThenNullPointerExceptionIsThrown() throws ParseException {
new DecimalFormat("#").parse(null);
}
@Test(expected = ParseException.class)
public void givenInvalidString_WhenDecimalFormat_ThenParseExceptionIsThrown() throws ParseException {
new DecimalFormat("#").parse("&");
}
}

View File

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

@ -0,0 +1,22 @@
=========
## Java Strings Cookbooks and Examples
### Relevant Articles:
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [Java String Conversions](https://www.baeldung.com/java-string-conversions)
- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
- [Get Substring from String in Java](https://www.baeldung.com/java-substring)
- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Split a String in Java](http://www.baeldung.com/java-split-string)
- [Common String Operations in Java](https://www.baeldung.com/java-string-operations)
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
- [Java toString() Method](https://www.baeldung.com/java-tostring)
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)

99
java-strings-ops/pom.xml Normal file
View File

@ -0,0 +1,99 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>java-strings-ops</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>java-strings-ops</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter-api.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>java-strings-ops</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- util -->
<commons-lang3.version>3.8.1</commons-lang3.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<guava.version>27.0.1-jre</guava.version>
<junit-jupiter-api.version>5.3.1</junit-jupiter-api.version>
</properties>
</project>

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