This commit is contained in:
Dhawal Kapil 2019-07-27 02:07:25 +05:30
commit 662208dfb0
706 changed files with 8939 additions and 2666 deletions

4
.gitignore vendored
View File

@ -1,4 +1,5 @@
*/bin/*
bin/
*.class
@ -21,6 +22,9 @@
*.iws
out/
# VSCode
.vscode/
# Mac
.DS_Store

View File

@ -32,7 +32,7 @@ Running a Spring Boot module
====================
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
#Running Tests
###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

@ -6,4 +6,4 @@
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
- [A Guide to the Folding Technique](https://www.baeldung.com/folding-hashing-technique)
- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique)

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

@ -82,7 +82,6 @@
</build>
<properties>
<java.version>1.8</java.version>
<olingo2.version>2.0.11</olingo2.version>
</properties>

View File

@ -112,7 +112,6 @@
</repositories>
<properties>
<commons-io.version>2.5</commons-io.version>
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
<gson.version>2.8.0</gson.version>

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

@ -175,8 +175,6 @@
<junit.platform.version>1.0.0</junit.platform.version>
<hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version>
<commons-lang3.version>3.9</commons-lang3.version>
<java.version>1.8</java.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<logback.version>1.2.3</logback.version>
<groovy.version>2.5.7</groovy.version>

View File

@ -0,0 +1,52 @@
package com.baeldung.concatenate
class Wonder {
String numOfWonder = 'seven'
String operator_plus() {
return 'The ' + numOfWonder + ' wonders of the world'
}
String operator_left() {
return 'The ' << numOfWonder << ' wonders of ' << 'the world'
}
String interpolation_one() {
return "The $numOfWonder wonders of the world"
}
String interpolation_two() {
return "The ${numOfWonder} wonders of the world"
}
String multilineString() {
return """
There are $numOfWonder wonders of the world.
Can you name them all?
1. The Great Pyramid of Giza
2. Hanging Gardens of Babylon
3. Colossus of Rhode
4. Lighthouse of Alexendra
5. Temple of Artemis
6. Status of Zeus at Olympia
7. Mausoleum at Halicarnassus
"""
}
String method_concat() {
return 'The '.concat(numOfWonder).concat(' wonders of the world')
}
String method_builder() {
return new StringBuilder()
.append('The ').append(numOfWonder).append(' wonders of the world')
}
String method_buffer() {
return new StringBuffer()
.append('The ').append(numOfWonder).append(' wonders of the world')
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.concatenate
import org.junit.Before
import org.junit.Test
import static org.junit.Assert.*
class WonderUnitTest {
static final String EXPECTED_SINGLE_LINE = "The seven wonders of the world"
Wonder wonder
@Before
void before() {
wonder = new Wonder()
}
@Test
void whenUsingOperatorPlus_thenConcatCorrectly() {
assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_plus())
}
@Test
void whenUsingOperatorLeft_thenConcatCorrectly() {
assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_left())
}
@Test
void whenUsingInterpolationOne_thenConcatCorrectly() {
assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_one())
}
@Test
void whenUsingInterpolationTwo_thenConcatCorrectly() {
assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_two())
}
@Test
void whenUsingMultiline_thenConcatCorrectly() {
def expectedMultiline = """
There are seven wonders of the world.
Can you name them all?
1. The Great Pyramid of Giza
2. Hanging Gardens of Babylon
3. Colossus of Rhode
4. Lighthouse of Alexendra
5. Temple of Artemis
6. Status of Zeus at Olympia
7. Mausoleum at Halicarnassus
"""
assertEquals(expectedMultiline, wonder.multilineString())
}
@Test
void whenUsingMethodConcat_thenConcatCorrectly() {
assertEquals(EXPECTED_SINGLE_LINE, wonder.method_concat())
}
@Test
void whenUsingMethodBuilder_thenConcatCorrectly() {
assertEquals(EXPECTED_SINGLE_LINE, wonder.method_builder())
}
@Test
void whenUsingMethodBuffer_thenConcatCorrectly() {
assertEquals(EXPECTED_SINGLE_LINE, wonder.method_buffer())
}
}

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 LoopDiagonallyTest {
@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

@ -0,0 +1,3 @@
## Relevant articles:
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)

View File

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

View File

@ -175,7 +175,6 @@
<properties>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<commons-math3.version>3.6.1</commons-math3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>

View File

@ -0,0 +1,34 @@
package com.baeldung.java_8_features.groupingby;
public class Tuple {
private BlogPostType type;
private String author;
public Tuple(BlogPostType type, String author) {
super();
this.type = type;
this.author = author;
}
public BlogPostType getType() {
return type;
}
public void setType(BlogPostType type) {
this.type = type;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Tuple [type=" + type + ", author=" + author + ", getType()=" + getType() + ", getAuthor()=" + getAuthor() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]";
}
}

View File

@ -259,4 +259,15 @@ public class OptionalUnitTest {
LOG.debug("Getting default value...");
return "Default Value";
}
// Uncomment code when code base is compatiable with Java 11
// @Test
// public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() {
// Optional<String> opt = Optional.of("Baeldung");
// assertFalse(opt.isEmpty());
//
// opt = Optional.ofNullable(null);
// assertTrue(opt.isEmpty());
// }
}

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

@ -42,7 +42,7 @@ public class CoreJavaCollectionsUnitTest {
@Test(expected = UnsupportedOperationException.class)
public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() {
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
final ImmutableList<Object> unmodifiableList = ImmutableList.builder().addAll(list).build();
final ImmutableList<String> unmodifiableList = ImmutableList.<String>builder().addAll(list).build();
unmodifiableList.add("four");
}

View File

@ -72,7 +72,6 @@
<properties>
<!-- util -->
<guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-math3.version>3.6.1</commons-math3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>

View File

@ -17,3 +17,4 @@
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
- [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety)
- [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread)
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)

View File

@ -45,8 +45,6 @@
</build>
<properties>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>

View File

@ -62,7 +62,6 @@
<properties>
<!-- util -->
<guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-math3.version>3.6.1</commons-math3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>

View File

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

View File

@ -248,7 +248,6 @@
<properties>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>

View File

@ -35,7 +35,6 @@
</dependencies>
<properties>
<commons-lang3.version>3.5</commons-lang3.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables)

View File

@ -75,13 +75,7 @@
</build>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<gson.version>2.8.2</gson.version>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
<equalsverifier.version>3.0.3</equalsverifier.version>

View File

@ -54,3 +54,15 @@ class BankAccountCopyConstructor extends BankAccount {
this.balance = 0.0f;
}
}
class BankAccountChainedConstructors extends BankAccount {
public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) {
this.name = name;
this.opened = opened;
this.balance = balance;
}
public BankAccountChainedConstructors(String name) {
this(name, LocalDateTime.now(), 0.0f);
}
}

View File

@ -1,15 +1,14 @@
package com.baeldung.constructors;
import com.baeldung.constructors.*;
import com.google.common.collect.Comparators;
import org.junit.Test;
import java.util.logging.Logger;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.logging.Logger;
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;
import static org.assertj.core.api.Assertions.*;
public class ConstructorUnitTest {
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
@ -17,26 +16,28 @@ public class ConstructorUnitTest {
@Test
public void givenNoExplicitContructor_whenUsed_thenFails() {
BankAccount account = new BankAccount();
assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class);
assertThatThrownBy(() -> {
account.toString();
}).isInstanceOf(Exception.class);
}
@Test
public void givenNoArgumentConstructor_whenUsed_thenSucceeds() {
BankAccountEmptyConstructor account = new BankAccountEmptyConstructor();
assertThatCode(() -> {
account.toString();
}).doesNotThrowAnyException();
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);
new BankAccountParameterizedConstructor("Tom", opened, 1000.0f);
assertThatCode(() -> {
account.toString();
}).doesNotThrowAnyException();
account.toString();
}).doesNotThrowAnyException();
}
@Test
@ -47,7 +48,16 @@ public class ConstructorUnitTest {
assertThat(account.getName()).isEqualTo(newAccount.getName());
assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened());
assertThat(newAccount.getBalance()).isEqualTo(0.0f);
}
@Test
public void givenChainedConstructor_whenUsed_thenMaintainsLogic() {
BankAccountChainedConstructors account = new BankAccountChainedConstructors("Tim");
BankAccountChainedConstructors newAccount = new BankAccountChainedConstructors("Tim", LocalDateTime.now(), 0.0f);
assertThat(account.getName()).isEqualTo(newAccount.getName());
assertThat(account.getBalance()).isEqualTo(newAccount.getBalance());
}
}

View File

@ -18,7 +18,6 @@
- [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces)
- [Recursion In Java](http://www.baeldung.com/java-recursion)
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
- [Using Java Assertions](http://www.baeldung.com/java-assert)

View File

@ -75,9 +75,6 @@
<properties>
<gson.version>2.8.2</gson.version>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<javax.mail.version>1.5.0-b01</javax.mail.version>

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

@ -42,8 +42,6 @@
<properties>
<javax.mail.version>1.5.0-b01</javax.mail.version>
<commons-io.version>2.5</commons-io.version>
<commons-lang3.version>3.5</commons-lang3.version>
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
</properties>
</project>

View File

@ -19,12 +19,12 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind.version}</version>
<version>${jackson.version}</version>
</dependency>
</dependencies>
@ -48,7 +48,5 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<hibernate.core.version>5.4.0.Final</hibernate.core.version>
<h2database.version>1.4.197</h2database.version>
<jackson.databind.version>2.9.8</jackson.databind.version>
</properties>
</project>

View File

@ -68,7 +68,6 @@
<properties>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>

View File

@ -0,0 +1,40 @@
package com.baeldung.core.pwd;
import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Paths;
public final class CurrentDirectoryFetcher {
public static void main(String[] args) {
System.out.printf("Current Directory Using Java System API: %s%n", currentDirectoryUsingSystemProperties());
System.out.printf("Current Directory Using Java IO File API: %s%n", currentDirectoryUsingFile());
System.out.printf("Current Directory Using Java NIO FileSystems API: %s%n", currentDirectoryUsingFileSystems());
System.out.printf("Current Directory Using Java NIO Paths API: %s%n", currentDirectoryUsingPaths());
}
public static String currentDirectoryUsingSystemProperties() {
return System.getProperty("user.dir");
}
public static String currentDirectoryUsingPaths() {
return Paths.get("")
.toAbsolutePath()
.toString();
}
public static String currentDirectoryUsingFileSystems() {
return FileSystems.getDefault()
.getPath("")
.toAbsolutePath()
.toString();
}
public static String currentDirectoryUsingFile() {
return new File("").getAbsolutePath();
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.core.pwd;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CurrentDirectoryFetcherTest {
private static final String CURRENT_DIR = "core-java-os";
@Test
public void whenUsingSystemProperties_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingSystemProperties()
.endsWith(CURRENT_DIR));
}
@Test
public void whenUsingJavaNioPaths_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingPaths()
.endsWith(CURRENT_DIR));
}
@Test
public void whenUsingJavaNioFileSystems_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFileSystems()
.endsWith(CURRENT_DIR));
}
@Test
public void whenUsingJavaIoFile_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFile()
.endsWith(CURRENT_DIR));
}
}

View File

@ -23,11 +23,4 @@
</dependencies>
<properties>
<!-- util -->
<commons-lang3.version>3.8.1</commons-lang3.version>
</properties>
</project>

View File

@ -43,7 +43,6 @@
<properties>
<!-- util -->
<commons-lang3.version>3.8.1</commons-lang3.version>
<bouncycastle.version>1.60</bouncycastle.version>
<commons-codec.version>1.11</commons-codec.version>

View File

@ -264,7 +264,6 @@
<!-- util -->
<guava.version>23.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>

View File

@ -37,7 +37,6 @@
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)

View File

@ -113,7 +113,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
<version>${h2.version}</version>
</dependency>
<!-- instrumentation -->
<dependency>
@ -453,8 +453,6 @@
<gson.version>2.8.2</gson.version>
<!-- util -->
<commons-lang3.version>3.9</commons-lang3.version>
<commons-io.version>2.5</commons-io.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<unix4j.version>0.4</unix4j.version>
@ -471,7 +469,6 @@
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<h2database.version>1.4.197</h2database.version>
<esapi.version>2.1.0.1</esapi.version>
<jmh-core.version>1.19</jmh-core.version>

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

@ -22,7 +22,7 @@
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.jupiter.version}</version>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -88,7 +88,7 @@
<properties>
<kotlin.version>1.3.30</kotlin.version>
<junit.jupiter.version>5.4.2</junit.jupiter.version>
<junit-jupiter.version>5.4.2</junit-jupiter.version>
<mockito.version>2.27.0</mockito.version>
<byte-buddy.version>1.9.12</byte-buddy.version>
<assertj.version>3.10.0</assertj.version>

View File

@ -39,7 +39,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>com.github.kittinunf.fuel</groupId>
@ -76,11 +76,9 @@
<properties>
<commons-math3.version>3.6.1</commons-math3.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<junit.platform.version>1.1.1</junit.platform.version>
<junit.vintage.version>5.2.0</junit.vintage.version>
<assertj.version>3.10.0</assertj.version>
<h2database.version>1.4.197</h2database.version>
<fuel.version>1.15.0</fuel.version>
<kovenant.version>3.3.0</kovenant.version>
<injekt-core.version>1.16.1</injekt-core.version>

View File

@ -69,7 +69,6 @@
<properties>
<couchbase.client.version>2.5.0</couchbase.client.version>
<spring-framework.version>4.3.5.RELEASE</spring-framework.version>
<commons-lang3.version>3.5</commons-lang3.version>
</properties>
</project>

Binary file not shown.

View File

@ -22,6 +22,10 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule {
String className = node.getImage();
Objects.requireNonNull(className);
if (className.endsWith("SpringContextTest")) {
return data;
}
if (className.endsWith("Tests")
|| (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) {
addViolation(data, node);

View File

@ -115,7 +115,6 @@
<properties>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<disruptor.version>3.3.6</disruptor.version>
<!-- testing -->
<testng.version>6.10</testng.version>

View File

@ -26,7 +26,6 @@
</dependencies>
<properties>
<commons-lang3.version>3.5</commons-lang3.version>
<dozer.version>5.5.1</dozer.version>
</properties>

View File

@ -58,6 +58,5 @@
<flyway-core.version>5.1.4</flyway-core.version>
<tomcat-jdbc.version>8.5.33</tomcat-jdbc.version>
<javax.annotation-api.version>1.3.2</javax.annotation-api.version>
<h2.version>1.4.197</h2.version>
</properties>
</project>

View File

@ -64,7 +64,6 @@
<!-- marshalling -->
<gson.version>2.8.0</gson.version>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<joda-time.version>2.9.6</joda-time.version>
</properties>

View File

@ -55,7 +55,6 @@
<properties>
<!-- util -->
<guava.version>24.0-jre</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<!-- testing -->

View File

@ -49,7 +49,6 @@
<properties>
<!-- util -->
<guava.version>24.0-jre</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>

View File

@ -297,7 +297,6 @@
<properties>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-codec.version>1.10</commons-codec.version>
<httpasyncclient.version>4.1.4</httpasyncclient.version>
<!-- testing -->
@ -305,7 +304,6 @@
<httpcore.version>4.4.11</httpcore.version>
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
<!-- maven plugins -->
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>

View File

@ -120,7 +120,6 @@
<properties>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-codec.version>1.10</commons-codec.version>
<httpasyncclient.version>4.1.4</httpasyncclient.version>
<!-- testing -->

View File

@ -65,7 +65,6 @@
<hystrix-core.version>1.5.8</hystrix-core.version>
<rxjava-core.version>0.20.7</rxjava-core.version>
<!-- maven plugins -->
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<hystrix-metrics-event-stream.version>1.5.8</hystrix-metrics-event-stream.version>
<hystrix-dashboard.version>1.5.8</hystrix-dashboard.version>

View File

@ -118,7 +118,6 @@
<properties>
<!-- util -->
<commons-lang3.version>3.8</commons-lang3.version>
<joda-time.version>2.10</joda-time.version>
<gson.version>2.8.5</gson.version>
<commons-collections4.version>4.2</commons-collections4.version>

View File

@ -165,7 +165,7 @@ public class JacksonSerializationIgnoreUnitTest {
}
@Test
public final void givenIgnoringNullFieldsOnClass_whenWritingObjectWithNullField_thenFieldIsIgnored() throws JsonProcessingException {
public final void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull();
@ -178,7 +178,7 @@ public class JacksonSerializationIgnoreUnitTest {
}
@Test
public final void givenIgnoringNullFieldsGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
public final void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
final MyDto dtoObject = new MyDto();

View File

@ -118,7 +118,6 @@
<properties>
<!-- util -->
<commons-lang3.version>3.8</commons-lang3.version>
<joda-time.version>2.10</joda-time.version>
<gson.version>2.8.5</gson.version>
<commons-collections4.version>4.2</commons-collections4.version>

View File

@ -33,7 +33,6 @@
</dependencies>
<properties>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<assertj.version>3.6.1</assertj.version>
</properties>

View File

@ -54,7 +54,6 @@
<trove4j.version>3.0.2</trove4j.version>
<fastutil.version>8.1.0</fastutil.version>
<colt.version>1.2.0</colt.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<assertj.version>3.11.1</assertj.version>
</properties>

View File

@ -44,7 +44,6 @@
</dependencies>
<properties>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<avaitility.version>1.7.0</avaitility.version>

View File

@ -74,8 +74,6 @@
</build>
<properties>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<joda-time.version>2.10</joda-time.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>

View File

@ -72,8 +72,6 @@
<javaee-version>8.0</javaee-version>
<liberty-maven-plugin.version>2.3</liberty-maven-plugin.version>
<openliberty-runtime.version>18.0.0.1</openliberty-runtime.version>
<maven-war-plugin.version>3.2.2</maven-war-plugin.version>
</properties>
</project>

26
java-numbers-2/.gitignore vendored Normal file
View File

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

135
java-numbers-2/pom.xml Normal file
View File

@ -0,0 +1,135 @@
<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>java-numbers-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-numbers-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>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.decimal4j</groupId>
<artifactId>decimal4j</artifactId>
<version>${decimal4j.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>java-numbers-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<commons-lang3.version>3.5</commons-lang3.version>
<assertj.version>3.6.1</assertj.version>
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,68 @@
package com.baeldung.lossyconversion;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
public class ConversionTechniquesUnitTest {
@Test
public void testPrimitiveConversion() {
long longNum = 24;
short shortNum = (short) longNum;
assertEquals(24, shortNum);
double doubleNum = 15.6;
int integerNum = (int) doubleNum;
assertEquals(15, integerNum);
long largeLongNum = 32768;
short minShortNum = (short) largeLongNum;
assertEquals(-32768, minShortNum);
long smallLongNum = -32769;
short maxShortNum = (short) smallLongNum;
assertEquals(32767, maxShortNum);
long maxLong = Long.MAX_VALUE;
int minInt = (int) maxLong;
assertEquals(-1, minInt);
long minLong = Long.MIN_VALUE;
int maxInt = (int) minLong;
assertEquals(0, maxInt);
}
@Test
public void testWrapperToPrimitiveConversion() {
Float floatNum = 17.564f;
long longNum = floatNum.longValue();
assertEquals(17, longNum);
Double doubleNum = 15.9999;
longNum = doubleNum.longValue();
assertEquals(15, longNum);
}
@Test
public void testWrapperToPrimitiveConversionUsingMathRound() {
Double doubleNum = 15.9999;
long longNum = Math.round(doubleNum);
assertEquals(16, longNum);
}
@Test
public void testWrapperConversion() {
Double doubleNum = 10.3;
double dbl = doubleNum.doubleValue(); //unboxing
int intgr = (int) dbl; //downcasting
Integer intNum = Integer.valueOf(intgr);
assertEquals(Integer.valueOf(10), intNum);
}
}

View File

@ -121,7 +121,6 @@
<properties>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<commons-lang3.version>3.5</commons-lang3.version>
<assertj.version>3.6.1</assertj.version>

View File

@ -106,7 +106,6 @@
<properties>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<vavr.version>0.9.0</vavr.version>
<protonpack.version>1.15</protonpack.version>
<streamex.version>0.6.5</streamex.version>

View File

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

@ -1,4 +1,4 @@
package com.baeldung.string;
package com.baeldung.string.multiline;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

View File

@ -88,7 +88,6 @@
<assertj.version>3.9.1</assertj.version>
<mockito.version>2.21.0</mockito.version>
<commons-fileupload.version>1.3.3</commons-fileupload.version>
<commons-io.version>2.6</commons-io.version>
<javax.servlet-api.version>4.0.1</javax.servlet-api.version>
</properties>
</project>

View File

@ -130,8 +130,6 @@
<!-- maven plugins -->
<jaxb2-maven-plugin.version>2.3</jaxb2-maven-plugin.version>
<istack-commons-runtime.version>3.0.2</istack-commons-runtime.version>
<commons-io.version>2.5</commons-io.version>
<commons-lang3.version>3.5</commons-lang3.version>
<lifecycle-mapping-plugin.version>1.0.0</lifecycle-mapping-plugin.version>
<javax.activation.version>1.1</javax.activation.version>

View File

@ -519,11 +519,9 @@
<tyrus.version>1.13</tyrus.version>
<jersey.version>2.25</jersey.version>
<arquillian-glassfish.version>1.0.0.Final</arquillian-glassfish.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<org.springframework.security.version>4.2.3.RELEASE</org.springframework.security.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<taglibs.standard.version>1.1.2</taglibs.standard.version>
<commons-io.version>2.4</commons-io.version>
<com.sun.faces.jsf.version>2.2.14</com.sun.faces.jsf.version>
<httpclient.version>4.5</httpclient.version>
<arquillian-drone-bom.version>2.0.1.Final</arquillian-drone-bom.version>

View File

@ -2,43 +2,16 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jee-kotlin</artifactId>
<name>jee-kotlin</name>
<packaging>war</packaging>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>jee-kotlin</artifactId>
<name>jee-kotlin</name>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<failOnMissingWebXml>false</failOnMissingWebXml>
<javaee-api.version>8.0</javaee-api.version>
<kotlin.version>1.3.41</kotlin.version>
<kotlin.code.style>official</kotlin.code.style>
<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
<wildfly.version>8.2.1.Final</wildfly.version>
<mvn-war-plugin.version>3.2.3</mvn-war-plugin.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<maven-dependency-plugin.version>3.1.1</maven-dependency-plugin.version>
<arquillian_core.version>1.4.1.Final</arquillian_core.version>
<arquillian-drone-bom.version>2.0.1.Final</arquillian-drone-bom.version>
<arquillian-rest-client.version>1.0.0.Alpha4</arquillian-rest-client.version>
<junit.version>4.12</junit.version>
<resteasy.version>3.8.0.Final</resteasy.version>
<jackson.version>2.9.8</jackson.version>
<shrinkwrap.version>3.1.3</shrinkwrap.version>
</properties>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
@ -134,7 +107,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${mvn-war-plugin.version}</version>
<version>${maven-war-plugin.version}</version>
<configuration>
<warSourceDirectory>webapp</warSourceDirectory>
<warName>kotlin</warName>
@ -286,4 +259,28 @@
</dependencies>
</profile>
</profiles>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<failOnMissingWebXml>false</failOnMissingWebXml>
<javaee-api.version>8.0</javaee-api.version>
<kotlin.version>1.3.41</kotlin.version>
<kotlin.code.style>official</kotlin.code.style>
<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
<wildfly.version>8.2.1.Final</wildfly.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<maven-dependency-plugin.version>3.1.1</maven-dependency-plugin.version>
<arquillian_core.version>1.4.1.Final</arquillian_core.version>
<arquillian-drone-bom.version>2.0.1.Final</arquillian-drone-bom.version>
<arquillian-rest-client.version>1.0.0.Alpha4</arquillian-rest-client.version>
<resteasy.version>3.8.0.Final</resteasy.version>
<shrinkwrap.version>3.1.3</shrinkwrap.version>
</properties>
</project>

View File

@ -80,7 +80,6 @@
<properties>
<jersey.version>2.26</jersey.version>
<maven-war-plugin.version>3.2.0</maven-war-plugin.version>
</properties>
</project>

View File

@ -1,6 +0,0 @@
## Relevant articles:
- [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices)
- [Intro to JHipster](http://www.baeldung.com/jhipster)
- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service)
- [Creating New Roles and Authorities in JHipster](https://www.baeldung.com/jhipster-new-roles)

View File

@ -99,9 +99,6 @@
<com.sun.faces.version>2.2.14</com.sun.faces.version>
<javax.el.version>3.0.0</javax.el.version>
<!-- maven plugins -->
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<primefaces.version>6.2</primefaces.version>
</properties>

View File

@ -83,7 +83,6 @@
<properties>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<maven-war-plugin.version>3.0.0</maven-war-plugin.version>
<jnlp-jardiff.version>1.6.0</jnlp-jardiff.version>
<jnlp-servlet.version>1.6.0</jnlp-servlet.version>
</properties>

View File

@ -94,7 +94,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
<version>${h2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.arrow-kt/arrow-core -->
<dependency>
@ -184,7 +184,6 @@
<junit.platform.version>1.1.1</junit.platform.version>
<junit.vintage.version>5.2.0</junit.vintage.version>
<assertj.version>3.10.0</assertj.version>
<h2database.version>1.4.197</h2database.version>
<exposed.version>0.10.4</exposed.version>
<mockk.version>1.9.3</mockk.version>
</properties>

View File

@ -25,7 +25,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang.version}</version>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
@ -35,7 +35,7 @@
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-chain</groupId>
@ -87,13 +87,12 @@
</dependencies>
<properties>
<commons-lang.version>3.6</commons-lang.version>
<commons-lang3.version>3.6</commons-lang3.version>
<commons-text.version>1.1</commons-text.version>
<commons-beanutils.version>1.9.3</commons-beanutils.version>
<commons-chain.version>1.2</commons-chain.version>
<commons-csv.version>1.4</commons-csv.version>
<assertj.version>3.6.2</assertj.version>
<commons.io.version>2.5</commons.io.version>
<commons.dbutils.version>1.6</commons.dbutils.version>
<commons.collections.version>4.1</commons.collections.version>
<org.hamcrest.java-hamcrest.version>2.0.0.0</org.hamcrest.java-hamcrest.version>

View File

@ -449,7 +449,6 @@
<gson.version>2.8.2</gson.version>
<cache.version>1.1.0</cache.version>
<flink.version>1.5.0</flink.version>
<jackson.version>2.9.7</jackson.version>
<awaitility.version>3.0.0</awaitility.version>
<assertj.version>3.6.2</assertj.version>
<hazelcast.version>3.8.4</hazelcast.version>

5
libraries-io/README.md Normal file
View File

@ -0,0 +1,5 @@
### Relevant Articles:
- [Transferring a File Through SFTP in Java](https://www.baeldung.com/java-file-sftp)

40
libraries-io/pom.xml Normal file
View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries-io</artifactId>
<name>libraries-io</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- sftp file transfer -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>${jsch.version}</version>
</dependency>
<dependency>
<groupId>com.hierynomus</groupId>
<artifactId>sshj</artifactId>
<version>${sshj.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-vfs2</artifactId>
<version>${vfs.version}</version>
</dependency>
</dependencies>
<properties>
<!-- sftp -->
<jsch.version>0.1.55</jsch.version>
<sshj.version>0.27.0</sshj.version>
<vfs.version>2.4</vfs.version>
</properties>
</project>

View File

@ -0,0 +1 @@
This is a sample text content

View File

@ -0,0 +1,106 @@
package org.baeldung.java.io.remote;
import java.io.IOException;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.VFS;
import org.junit.Test;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
public class SftpFileTransferLiveTest {
private String remoteHost = "HOST_NAME_HERE";
private String username = "USERNAME_HERE";
private String password = "PASSWORD_HERE";
private String localFile = "src/main/resources/input.txt";
private String remoteFile = "welcome.txt";
private String localDir = "src/main/resources/";
private String remoteDir = "remote_sftp_test/";
private String knownHostsFileLoc = "/Users/USERNAME/known_hosts_sample";
@Test
public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
channelSftp.put(localFile, remoteDir + "jschFile.txt");
channelSftp.exit();
}
@Test
public void whenDownloadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
channelSftp.get(remoteFile, localDir + "jschFile.txt");
channelSftp.exit();
}
@Test
public void whenUploadFileUsingSshj_thenSuccess() throws IOException {
SSHClient sshClient = setupSshj();
SFTPClient sftpClient = sshClient.newSFTPClient();
sftpClient.put(localFile, remoteDir + "sshjFile.txt");
sftpClient.close();
sshClient.disconnect();
}
@Test
public void whenDownloadFileUsingSshj_thenSuccess() throws IOException {
SSHClient sshClient = setupSshj();
SFTPClient sftpClient = sshClient.newSFTPClient();
sftpClient.get(remoteFile, localDir + "sshjFile.txt");
sftpClient.close();
sshClient.disconnect();
}
@Test
public void whenUploadFileUsingApacheVfs_thenSuccess() throws IOException {
FileSystemManager manager = VFS.getManager();
FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localFile);
FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt");
remote.copyFrom(local, Selectors.SELECT_SELF);
local.close();
remote.close();
}
@Test
public void whenDownloadFileUsingApacheVfs_thenSuccess() throws IOException {
FileSystemManager manager = VFS.getManager();
FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localDir + "vfsFile.txt");
FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteFile);
local.copyFrom(remote, Selectors.SELECT_SELF);
local.close();
remote.close();
}
// ====== ssh-keyscan -H -t rsa remoteHost >> known_hosts_sample
private ChannelSftp setupJsch() throws JSchException {
JSch jsch = new JSch();
jsch.setKnownHosts(knownHostsFileLoc);
Session jschSession = jsch.getSession(username, remoteHost);
jschSession.setPassword(password);
//jschSession.setConfig("StrictHostKeyChecking", "no");
jschSession.connect();
return (ChannelSftp) jschSession.openChannel("sftp");
}
private SSHClient setupSshj() throws IOException {
SSHClient client = new SSHClient();
client.addHostKeyVerifier(new PromiscuousVerifier());
client.connect(remoteHost);
client.authPassword(username, password);
return client;
}
}

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