Merge branch 'master' into BAEL-3095

This commit is contained in:
Andrew Shcherbakov 2019-08-05 19:29:38 +02:00
commit 1ccfdebc41
1178 changed files with 13874 additions and 4986 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

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

@ -1,4 +1,4 @@
## Relevant articles:
## Relevant Articles:
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
@ -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,45 @@
package com.baeldung.metaprogramming
import groovy.transform.AutoClone
import groovy.transform.Canonical
import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString
import groovy.transform.TupleConstructor
import groovy.util.logging.*
@Canonical
@TupleConstructor
@EqualsAndHashCode
@ToString(includePackage=false, excludes=['id'])
@Log
@AutoClone
class Employee {
long id
String firstName
String lastName
int age
//method to catch missing property's getter
def propertyMissing(String propertyName) {
log.info "$propertyName is not available"
"property '$propertyName' is not available"
}
//method to catch missing property's setter
def propertyMissing(String propertyName, propertyValue) {
println "property '$propertyName' is not available"
log.info "$propertyName is not available"
"property '$propertyName' is not available"
}
def methodMissing(String methodName, def methodArgs) {
log.info "$methodName is not defined"
"method '$methodName' is not defined"
}
def logEmp() {
log.info "Employee: $lastName, $firstName is of $age years age"
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.metaprogramming.extension
import com.baeldung.metaprogramming.Employee
class BasicExtensions {
static int getYearOfBirth(Employee self) {
return (new Date().getYear() + 1900) - self.age;
}
static String capitalize(String self) {
return self.substring(0, 1).toUpperCase() + self.substring(1)
}
static void printCounter(Integer self) {
while (self>0) {
println self
self--
}
}
static Long square(Long self) {
return self*self
}
static BigDecimal cube(BigDecimal self) {
return self*self*self
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.metaprogramming.extension
import com.baeldung.metaprogramming.Employee
class StaticEmployeeExtension {
static Employee getDefaultObj(Employee self) {
return new Employee(firstName: "firstName", lastName: "lastName", age: 20)
}
}

View File

@ -0,0 +1,4 @@
moduleName=core-groovy-2
moduleVersion=1.0-SNAPSHOT
extensionClasses=com.baeldung.metaprogramming.extension.BasicExtensions
staticExtensionClasses=com.baeldung.metaprogramming.extension.StaticEmployeeExtension

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,118 @@
package com.baeldung.metaprogramming
import groovy.time.TimeCategory
class MetaprogrammingUnitTest extends GroovyTestCase {
Employee emp = new Employee(firstName: "Norman", lastName: "Lewis")
void testPropertyMissing() {
assert emp.address == "property 'address' is not available"
}
void testMethodMissing() {
Employee emp = new Employee()
try {
emp.getFullName()
} catch(MissingMethodException e) {
println "method is not defined"
}
assert emp.getFullName() == "method 'getFullName' is not defined"
}
void testMetaClassProperty() {
Employee.metaClass.address = ""
emp = new Employee(firstName: "Norman", lastName: "Lewis", address: "US")
assert emp.address == "US"
}
void testMetaClassMethod() {
emp.metaClass.getFullName = {
"$lastName, $firstName"
}
assert emp.getFullName() == "Lewis, Norman"
}
void testMetaClassConstructor() {
try {
Employee emp = new Employee("Norman")
} catch(GroovyRuntimeException e) {
assert e.message == "Could not find matching constructor for: com.baeldung.metaprogramming.Employee(String)"
}
Employee.metaClass.constructor = { String firstName ->
new Employee(firstName: firstName)
}
Employee norman = new Employee("Norman")
assert norman.firstName == "Norman"
assert norman.lastName == null
}
void testJavaMetaClass() {
String.metaClass.capitalize = { String str ->
str.substring(0, 1).toUpperCase() + str.substring(1);
}
assert "norman".capitalize() == "Norman"
}
void testEmployeeExtension() {
Employee emp = new Employee(age: 28)
assert emp.getYearOfBirth() == 1991
}
void testJavaClassesExtensions() {
5.printCounter()
assert 40l.square() == 1600l
assert (2.98).cube() == 26.463592
}
void testStaticEmployeeExtension() {
assert Employee.getDefaultObj().firstName == "firstName"
assert Employee.getDefaultObj().lastName == "lastName"
assert Employee.getDefaultObj().age == 20
}
void testToStringAnnotation() {
Employee employee = new Employee()
employee.id = 1
employee.firstName = "norman"
employee.lastName = "lewis"
employee.age = 28
assert employee.toString() == "Employee(norman, lewis, 28)"
}
void testTupleConstructorAnnotation() {
Employee norman = new Employee(1, "norman", "lewis", 28)
assert norman.toString() == "Employee(norman, lewis, 28)"
Employee snape = new Employee(2, "snape")
assert snape.toString() == "Employee(snape, null, 0)"
}
void testEqualsAndHashCodeAnnotation() {
Employee norman = new Employee(1, "norman", "lewis", 28)
Employee normanCopy = new Employee(1, "norman", "lewis", 28)
assert norman.equals(normanCopy)
assert norman.hashCode() == normanCopy.hashCode()
}
void testAutoCloneAnnotation() {
try {
Employee norman = new Employee(1, "norman", "lewis", 28)
def normanCopy = norman.clone()
assert norman == normanCopy
} catch(CloneNotSupportedException e) {
e.printStackTrace()
}
}
void testLoggingAnnotation() {
Employee employee = new Employee(1, "Norman", "Lewis", 28)
employee.logEmp()
}
}

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,4 @@
## Relevant Articles:
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)

View File

@ -7,3 +7,4 @@
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
- [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments)
- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit)
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)

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

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

@ -7,7 +7,7 @@
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays)
- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
- [Multi-Dimensional Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
@ -16,3 +16,4 @@
- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays)
- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array)
- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array)
- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element)

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) {
boolean isSorted(Comparable[] 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(Object[] array, Comparator comparator) {
for (int i = 0; i < array.length - 1; ++i) {
if (array[i].getName().compareTo(array[i + 1].getName()) > 0)
if (comparator.compare(array[i], (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;
}
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

@ -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,3 @@
### Relevant Articles
- [Design Strategies for Decoupling Java Modules](https://www.baeldung.com/java-modules-decoupling-design-strategies)

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

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

@ -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,7 +16,9 @@ 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
@ -50,4 +51,13 @@ public class ConstructorUnitTest {
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

@ -0,0 +1,43 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-lang-operators</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-operators</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>
<!-- 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-lang-operators</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -0,0 +1,64 @@
package com.baeldung.incrementdecrementunaryoperators;
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

@ -18,3 +18,4 @@
- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java)
- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator)
- [Java instanceof Operator](https://www.baeldung.com/java-instanceof)
- [Breaking Out of Nested Loops](https://www.baeldung.com/java-breaking-out-nested-loop)

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

@ -76,9 +76,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>
<!-- testing -->

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

@ -1,3 +1,3 @@
## Relevant articles:
## Relevant Articles:
- [Determine File Creating Date in Java](https://www.baeldung.com/java-file-creation-date)
- [Determine File Creation Date in Java](https://www.baeldung.com/java-file-creation-date)

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

@ -10,3 +10,4 @@
- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures)
- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)
- [Enabling TLS v1.2 in Java 7](https://www.baeldung.com/java-7-tls-v12)
- [The Java SecureRandom Class](https://www.baeldung.com/java-secure-random)

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

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

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

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