MsMasterpull
erge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
f004febf75
@ -1,12 +1,7 @@
|
||||
issuer:
|
||||
uri: http://localhost:8080/uaa
|
||||
|
||||
spring_profiles: postgresql,default
|
||||
|
||||
database.driverClassName: org.postgresql.Driver
|
||||
database.url: jdbc:postgresql:uaadb2
|
||||
database.username: postgres
|
||||
database.password: postgres
|
||||
spring_profiles: default,hsqldb
|
||||
|
||||
encryption:
|
||||
active_key_label: CHANGE-THIS-KEY
|
||||
|
@ -1,23 +1,11 @@
|
||||
# SECURITY OAUTH2 CLIENT (OAuth2ClientProperties)
|
||||
#spring.security.oauth2.client.provider.*= # OAuth provider details.
|
||||
#spring.security.oauth2.client.registration.*= # OAuth client registrations.
|
||||
|
||||
server.port=8081
|
||||
#server.servlet.context-path=/uaa-client-webapp
|
||||
|
||||
uaa.url=http://localhost:8080/uaa
|
||||
resource.server.url=http://localhost:8082
|
||||
|
||||
spring.security.oauth2.client.registration.uaa.client-name=UAA OAuth2 Client
|
||||
spring.security.oauth2.client.registration.uaa.client-id=client1
|
||||
spring.security.oauth2.client.registration.uaa.client-secret=client1
|
||||
spring.security.oauth2.client.registration.uaa.authorization-grant-type=authorization_code
|
||||
spring.security.oauth2.client.registration.uaa.client-name=Web App Client
|
||||
spring.security.oauth2.client.registration.uaa.client-id=webappclient
|
||||
spring.security.oauth2.client.registration.uaa.client-secret=webappclientsecret
|
||||
spring.security.oauth2.client.registration.uaa.scope=resource.read,resource.write,openid,profile
|
||||
spring.security.oauth2.client.registration.uaa.redirect-uri=http://localhost:8081/login/oauth2/code/uaa
|
||||
#spring.security.oauth2.client.registration.uaa.redirect-uri=http://localhost:8081/**
|
||||
|
||||
spring.security.oauth2.client.provider.uaa.token-uri=${uaa.url}/oauth/token
|
||||
spring.security.oauth2.client.provider.uaa.authorization-uri=${uaa.url}/oauth/authorize
|
||||
spring.security.oauth2.client.provider.uaa.jwk-set-uri=${uaa.url}/token_keys
|
||||
spring.security.oauth2.client.provider.uaa.user-info-uri=${uaa.url}/userinfo
|
||||
spring.security.oauth2.client.provider.uaa.user-name-attribute=user_name
|
||||
spring.security.oauth2.client.provider.uaa.issuer-uri=http://localhost:8080/uaa/oauth/token
|
||||
|
||||
|
@ -1,16 +1,3 @@
|
||||
server.port=8082
|
||||
|
||||
uaa.url=http://localhost:8080/uaa
|
||||
|
||||
#approch1
|
||||
spring.security.oauth2.resourceserver.jwt.issuer-uri=${uaa.url}/oauth/token
|
||||
|
||||
#approch2
|
||||
#spring.security.oauth2.resourceserver.jwt.jwk-set-uri=${uaa.url}/token_key
|
||||
|
||||
# SECURITY OAUTH2 CLIENT (OAuth2ClientProperties)
|
||||
#security.oauth2.client.client-id=client1
|
||||
#security.oauth2.client.client-secret=client1
|
||||
|
||||
#security.oauth2.resource.jwt.key-uri=${uaa.url}/token_key
|
||||
#security.oauth2.resource.token-info-uri=${uaa.url}/oauth/check_token
|
||||
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/uaa/oauth/token
|
||||
|
@ -9,3 +9,5 @@
|
||||
- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating)
|
||||
- [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits)
|
||||
- [Lists in Groovy](https://www.baeldung.com/groovy-lists)
|
||||
- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date)
|
||||
- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
|
||||
|
37
core-groovy/src/main/groovy/com/baeldung/Person.groovy
Normal file
37
core-groovy/src/main/groovy/com/baeldung/Person.groovy
Normal file
@ -0,0 +1,37 @@
|
||||
package com.baeldung
|
||||
|
||||
class Person {
|
||||
private String firstname
|
||||
private String lastname
|
||||
private Integer age
|
||||
|
||||
Person(String firstname, String lastname, Integer age) {
|
||||
this.firstname = firstname
|
||||
this.lastname = lastname
|
||||
this.age = age
|
||||
}
|
||||
|
||||
String getFirstname() {
|
||||
return firstname
|
||||
}
|
||||
|
||||
void setFirstname(String firstname) {
|
||||
this.firstname = firstname
|
||||
}
|
||||
|
||||
String getLastname() {
|
||||
return lastname
|
||||
}
|
||||
|
||||
void setLastname(String lastname) {
|
||||
this.lastname = lastname
|
||||
}
|
||||
|
||||
Integer getAge() {
|
||||
return age
|
||||
}
|
||||
|
||||
void setAge(Integer age) {
|
||||
this.age = age
|
||||
}
|
||||
}
|
@ -0,0 +1,87 @@
|
||||
package com.baeldung.closures
|
||||
|
||||
class Closures {
|
||||
|
||||
def printWelcome = {
|
||||
println "Welcome to Closures!"
|
||||
}
|
||||
|
||||
def print = { name ->
|
||||
println name
|
||||
}
|
||||
|
||||
def formatToLowerCase(name) {
|
||||
return name.toLowerCase()
|
||||
}
|
||||
def formatToLowerCaseClosure = { name ->
|
||||
return name.toLowerCase()
|
||||
}
|
||||
|
||||
def count=0
|
||||
|
||||
def increaseCount = {
|
||||
count++
|
||||
}
|
||||
|
||||
def greet = {
|
||||
return "Hello! ${it}"
|
||||
}
|
||||
|
||||
def multiply = { x, y ->
|
||||
return x*y
|
||||
}
|
||||
|
||||
def calculate = {int x, int y, String operation ->
|
||||
|
||||
//log closure
|
||||
def log = {
|
||||
println "Performing $it"
|
||||
}
|
||||
|
||||
def result = 0
|
||||
switch(operation) {
|
||||
case "ADD":
|
||||
log("Addition")
|
||||
result = x+y
|
||||
break
|
||||
case "SUB":
|
||||
log("Subtraction")
|
||||
result = x-y
|
||||
break
|
||||
case "MUL":
|
||||
log("Multiplication")
|
||||
result = x*y
|
||||
break
|
||||
case "DIV":
|
||||
log("Division")
|
||||
result = x/y
|
||||
break
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
def addAll = { int... args ->
|
||||
return args.sum()
|
||||
}
|
||||
|
||||
def volume(Closure areaCalculator, int... dimensions) {
|
||||
if(dimensions.size() == 3) {
|
||||
|
||||
//consider dimension[0] = length, dimension[1] = breadth, dimension[2] = height
|
||||
//for cube and cuboid
|
||||
return areaCalculator(dimensions[0], dimensions[1]) * dimensions[2]
|
||||
} else if(dimensions.size() == 2) {
|
||||
|
||||
//consider dimension[0] = radius, dimension[1] = height
|
||||
//for cylinder and cone
|
||||
return areaCalculator(dimensions[0]) * dimensions[1]
|
||||
} else if(dimensions.size() == 1) {
|
||||
|
||||
//consider dimension[0] = radius
|
||||
//for sphere
|
||||
return areaCalculator(dimensions[0]) * dimensions[0]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
package com.baeldung.closures
|
||||
|
||||
class Employee {
|
||||
|
||||
String fullName
|
||||
}
|
@ -0,0 +1,80 @@
|
||||
package com.baeldung.closures
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
class ClosuresUnitTest extends GroovyTestCase {
|
||||
|
||||
Closures closures = new Closures()
|
||||
|
||||
void testDeclaration() {
|
||||
|
||||
closures.print("Hello! Closure")
|
||||
closures.formatToLowerCaseClosure("Hello! Closure")
|
||||
|
||||
closures.print.call("Hello! Closure")
|
||||
closures.formatToLowerCaseClosure.call("Hello! Closure")
|
||||
|
||||
}
|
||||
|
||||
void testClosureVsMethods() {
|
||||
assert closures.formatToLowerCase("TONY STARK") == closures.formatToLowerCaseClosure("Tony STark")
|
||||
}
|
||||
|
||||
void testParameters() {
|
||||
//implicit parameter
|
||||
assert closures.greet("Alex") == "Hello! Alex"
|
||||
|
||||
//multiple parameters
|
||||
assert closures.multiply(2, 4) == 8
|
||||
|
||||
assert closures.calculate(12, 4, "ADD") == 16
|
||||
assert closures.calculate(12, 4, "SUB") == 8
|
||||
assert closures.calculate(43, 8, "DIV") == 5.375
|
||||
|
||||
//varags
|
||||
assert closures.addAll(12, 10, 14) == 36
|
||||
|
||||
}
|
||||
|
||||
void testClosureAsAnArgument() {
|
||||
assert closures.volume({ l, b -> return l*b }, 12, 6, 10) == 720
|
||||
|
||||
assert closures.volume({ radius -> return Math.PI*radius*radius/3 }, 5, 10) == Math.PI * 250/3
|
||||
}
|
||||
|
||||
void testGStringsLazyEvaluation() {
|
||||
def name = "Samwell"
|
||||
def welcomeMsg = "Welcome! $name"
|
||||
|
||||
assert welcomeMsg == "Welcome! Samwell"
|
||||
|
||||
// changing the name does not affect original interpolated value
|
||||
name = "Tarly"
|
||||
assert welcomeMsg != "Welcome! Tarly"
|
||||
|
||||
def fullName = "Tarly Samson"
|
||||
def greetStr = "Hello! ${-> fullName}"
|
||||
|
||||
assert greetStr == "Hello! Tarly Samson"
|
||||
|
||||
// this time changing the variable affects the interpolated String's value
|
||||
fullName = "Jon Smith"
|
||||
assert greetStr == "Hello! Jon Smith"
|
||||
}
|
||||
|
||||
void testClosureInLists() {
|
||||
def list = [10, 11, 12, 13, 14, true, false, "BUNTHER"]
|
||||
list.each {
|
||||
println it
|
||||
}
|
||||
|
||||
assert [13, 14] == list.findAll{ it instanceof Integer && it >= 13}
|
||||
}
|
||||
|
||||
void testClosureInMaps() {
|
||||
def map = [1:10, 2:30, 4:5]
|
||||
|
||||
assert [10, 60, 20] == map.collect{it.key * it.value}
|
||||
}
|
||||
|
||||
}
|
@ -129,13 +129,13 @@ class ListTest{
|
||||
assertTrue(filterList.findAll{it > 3} == [4, 5, 6, 76])
|
||||
|
||||
assertTrue(filterList.findAll{ it instanceof Number} == [2, 1, 3, 4, 5, 6, 76])
|
||||
|
||||
|
||||
assertTrue(filterList.grep( Number )== [2, 1, 3, 4, 5, 6, 76])
|
||||
|
||||
|
||||
assertTrue(filterList.grep{ it> 6 }== [76])
|
||||
|
||||
def conditionList = [2, 1, 3, 4, 5, 6, 76]
|
||||
|
||||
|
||||
assertFalse(conditionList.every{ it < 6})
|
||||
|
||||
assertTrue(conditionList.any{ it%2 == 0})
|
||||
@ -165,7 +165,7 @@ class ListTest{
|
||||
|
||||
def strList = ["na", "ppp", "as"]
|
||||
assertTrue(strList.max() == "ppp")
|
||||
|
||||
|
||||
Comparator minc = {a,b -> a == b? 0: a < b? -1 : 1}
|
||||
def numberList = [3, 2, 0, 7]
|
||||
assertTrue(numberList.min(minc) == 0)
|
||||
|
@ -0,0 +1,58 @@
|
||||
package com.baeldung.lists
|
||||
|
||||
import com.baeldung.Person
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.*
|
||||
|
||||
class ListUnitTest {
|
||||
|
||||
private final personList = [
|
||||
new Person("Regina", "Fitzpatrick", 25),
|
||||
new Person("Abagail", "Ballard", 26),
|
||||
new Person("Lucian", "Walter", 30),
|
||||
]
|
||||
|
||||
@Test
|
||||
void whenListContainsElement_thenCheckReturnsTrue() {
|
||||
def list = ['a', 'b', 'c']
|
||||
|
||||
assertTrue(list.indexOf('a') > -1)
|
||||
assertTrue(list.contains('a'))
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenListContainsElement_thenCheckWithMembershipOperatorReturnsTrue() {
|
||||
def list = ['a', 'b', 'c']
|
||||
|
||||
assertTrue('a' in list)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingStreamMatching_thenShouldEvaluateList() {
|
||||
assertTrue(personList.stream().anyMatch {it.age > 20})
|
||||
assertFalse(personList.stream().allMatch {it.age < 30})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingCollectionMatching_thenShouldEvaluateList() {
|
||||
assertTrue(personList.any {it.age > 20})
|
||||
assertFalse(personList.every {it.age < 30})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingStreamFind_thenShouldReturnMatchingElements() {
|
||||
assertTrue(personList.stream().filter {it.age > 20}.findAny().isPresent())
|
||||
assertFalse(personList.stream().filter {it.age > 30}.findAny().isPresent())
|
||||
assertTrue(personList.stream().filter {it.age > 20}.findAll().size() == 3)
|
||||
assertTrue(personList.stream().filter {it.age > 30}.findAll().isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingCollectionFind_thenShouldReturnMatchingElements() {
|
||||
assertNotNull(personList.find {it.age > 20})
|
||||
assertNull(personList.find {it.age > 30})
|
||||
assertTrue(personList.findAll {it.age > 20}.size() == 3)
|
||||
assertTrue(personList.findAll {it.age > 30}.isEmpty())
|
||||
}
|
||||
}
|
@ -1,10 +1,18 @@
|
||||
package com.baeldung.map
|
||||
|
||||
import static org.junit.Assert.*
|
||||
import com.baeldung.Person
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.*
|
||||
|
||||
class MapUnitTest {
|
||||
|
||||
private final personMap = [
|
||||
Regina : new Person("Regina", "Fitzpatrick", 25),
|
||||
Abagail: new Person("Abagail", "Ballard", 26),
|
||||
Lucian : new Person("Lucian", "Walter", 30)
|
||||
]
|
||||
|
||||
@Test
|
||||
void whenUsingEach_thenMapIsIterated() {
|
||||
def map = [
|
||||
@ -63,7 +71,7 @@ class MapUnitTest {
|
||||
'FF6347' : 'Tomato',
|
||||
'FF4500' : 'Orange Red'
|
||||
]
|
||||
|
||||
|
||||
map.eachWithIndex { key, val, index ->
|
||||
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
|
||||
println "$indent Hex Code: $key = Color Name: $val"
|
||||
@ -82,4 +90,65 @@ class MapUnitTest {
|
||||
println "Hex Code: $entry.key = Color Name: $entry.value"
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMapContainsKeyElement_thenCheckReturnsTrue() {
|
||||
def map = [a: 'd', b: 'e', c: 'f']
|
||||
|
||||
assertTrue(map.containsKey('a'))
|
||||
assertFalse(map.containsKey('e'))
|
||||
assertTrue(map.containsValue('e'))
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMapContainsKeyElement_thenCheckByMembershipReturnsTrue() {
|
||||
def map = [a: 'd', b: 'e', c: 'f']
|
||||
|
||||
assertTrue('a' in map)
|
||||
assertFalse('f' in map)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMapContainsFalseBooleanValues_thenCheckReturnsFalse() {
|
||||
def map = [a: true, b: false, c: null]
|
||||
|
||||
assertTrue(map.containsKey('b'))
|
||||
assertTrue('a' in map)
|
||||
assertFalse('b' in map)
|
||||
assertFalse('c' in map)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingStreamMatching_thenShouldEvaluateMap() {
|
||||
assertTrue(personMap.keySet().stream().anyMatch {it == "Regina"})
|
||||
assertFalse(personMap.keySet().stream().allMatch {it == "Albert"})
|
||||
assertFalse(personMap.values().stream().allMatch {it.age < 30})
|
||||
assertTrue(personMap.entrySet().stream().anyMatch {it.key == "Abagail" && it.value.lastname == "Ballard"})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingCollectionMatching_thenShouldEvaluateMap() {
|
||||
assertTrue(personMap.keySet().any {it == "Regina"})
|
||||
assertFalse(personMap.keySet().every {it == "Albert"})
|
||||
assertFalse(personMap.values().every {it.age < 30})
|
||||
assertTrue(personMap.any {firstname, person -> firstname == "Abagail" && person.lastname == "Ballard"})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingCollectionFind_thenShouldReturnElements() {
|
||||
assertNotNull(personMap.find {it.key == "Abagail" && it.value.lastname == "Ballard"})
|
||||
assertTrue(personMap.findAll {it.value.age > 20}.size() == 3)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingStreamFind_thenShouldReturnElements() {
|
||||
assertTrue(
|
||||
personMap.entrySet().stream()
|
||||
.filter {it.key == "Abagail" && it.value.lastname == "Ballard"}
|
||||
.findAny().isPresent())
|
||||
assertTrue(
|
||||
personMap.entrySet().stream()
|
||||
.filter {it.value.age > 20}
|
||||
.findAll().size() == 3)
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.set
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.assertTrue
|
||||
|
||||
class SetUnitTest {
|
||||
|
||||
@Test
|
||||
void whenSetContainsElement_thenCheckReturnsTrue() {
|
||||
def set = ['a', 'b', 'c'] as Set
|
||||
|
||||
assertTrue(set.contains('a'))
|
||||
assertTrue('a' in set)
|
||||
}
|
||||
}
|
@ -5,3 +5,4 @@
|
||||
- [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api)
|
||||
- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control)
|
||||
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
|
||||
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
|
||||
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.jlink;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class HelloWorld {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(HelloWorld.class.getName());
|
||||
|
||||
public static void main(String[] args) {
|
||||
LOG.info("Hello World!");
|
||||
}
|
||||
}
|
3
core-java-11/src/modules/jlinkModule/module-info.java
Normal file
3
core-java-11/src/modules/jlinkModule/module-info.java
Normal file
@ -0,0 +1,3 @@
|
||||
module jlinkModule {
|
||||
requires java.logging;
|
||||
}
|
48
core-java-12/pom.xml
Normal file
48
core-java-12/pom.xml
Normal file
@ -0,0 +1,48 @@
|
||||
<?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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-12</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-12</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>12</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>12</maven.compiler.target.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,71 @@
|
||||
package com.baeldung.collectors;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static java.util.stream.Collectors.maxBy;
|
||||
import static java.util.stream.Collectors.minBy;
|
||||
import static java.util.stream.Collectors.teeing;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Unit tests for collectors additions in Java 12.
|
||||
*/
|
||||
public class CollectorsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenTeeing_ItShouldCombineTheResultsAsExpected() {
|
||||
List<Integer> numbers = Arrays.asList(42, 4, 2, 24);
|
||||
Range range = numbers.stream()
|
||||
.collect(teeing(minBy(Integer::compareTo), maxBy(Integer::compareTo), (min, max) -> new Range(min.orElse(null), max.orElse(null))));
|
||||
|
||||
assertThat(range).isEqualTo(new Range(2, 42));
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a closed range of numbers between {@link #min} and
|
||||
* {@link #max}, both inclusive.
|
||||
*/
|
||||
private static class Range {
|
||||
|
||||
private final Integer min;
|
||||
|
||||
private final Integer max;
|
||||
|
||||
Range(Integer min, Integer max) {
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
Integer getMin() {
|
||||
return min;
|
||||
}
|
||||
|
||||
Integer getMax() {
|
||||
return max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Range range = (Range) o;
|
||||
return Objects.equals(getMin(), range.getMin()) && Objects.equals(getMax(), range.getMax());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getMin(), getMax());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Range{" + "min=" + min + ", max=" + max + '}';
|
||||
}
|
||||
}
|
||||
}
|
@ -124,11 +124,44 @@ public class Java8SortUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
|
||||
|
||||
final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
|
||||
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamComparatorOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
final List<Human> sortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName)).collect(Collectors.toList());
|
||||
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
|
||||
final List<String> letters = Lists.newArrayList("B", "A", "C");
|
||||
|
||||
final List<String> reverseSortedLetters = letters.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
|
||||
Assert.assertThat(reverseSortedLetters.get(0), equalTo("C"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamCustomOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
final Comparator<Human> reverseNameComparator = (h1, h2) -> h2.getName().compareTo(h1.getName());
|
||||
|
||||
final List<Human> reverseSortedHumans = humans.stream().sorted(reverseNameComparator).collect(Collectors.toList());
|
||||
Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamComparatorOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
final List<Human> reverseSortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder())).collect(Collectors.toList());
|
||||
Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -27,3 +27,6 @@
|
||||
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
|
||||
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)
|
||||
- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation)
|
||||
- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
|
||||
|
@ -33,3 +33,4 @@
|
||||
- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences)
|
||||
- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector)
|
||||
- [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack)
|
||||
- [Time Comparison of Arrays.sort(Object[]) and Arrays.sort(int[])](https://www.baeldung.com/arrays-sortobject-vs-sortint)
|
||||
|
@ -16,3 +16,4 @@
|
||||
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
|
||||
- [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)
|
||||
|
6
core-java-jvm/README.md
Normal file
6
core-java-jvm/README.md
Normal file
@ -0,0 +1,6 @@
|
||||
=========
|
||||
|
||||
## Core Java JVM Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Method Inlining in the JVM](http://www.baeldung.com/method-inlining-in-the-jvm/)
|
40
core-java-jvm/pom.xml
Normal file
40
core-java-jvm/pom.xml
Normal file
@ -0,0 +1,40 @@
|
||||
<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-jvm</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-jvm</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
</project>
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.socket.read;
|
||||
|
||||
import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.*;
|
||||
|
||||
public class Client {
|
||||
|
||||
public void runClient(String ip, int port) {
|
||||
try {
|
||||
Socket socket = new Socket(ip, port);
|
||||
System.out.println("Connected to server ...");
|
||||
DataInputStream in = new DataInputStream(System.in);
|
||||
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
|
||||
|
||||
char type = 's'; // s for string
|
||||
int length = 29;
|
||||
String data = "This is a string of length 29";
|
||||
byte[] dataInBytes = data.getBytes(StandardCharsets.UTF_8);
|
||||
//Sending data in TLV format
|
||||
out.writeChar(type);
|
||||
out.writeInt(length);
|
||||
out.write(dataInBytes);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.socket.read;
|
||||
|
||||
import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.*;
|
||||
|
||||
public class Server {
|
||||
|
||||
public void runServer(int port) {
|
||||
//Start the server and wait for connection
|
||||
try {
|
||||
ServerSocket server = new ServerSocket(port);
|
||||
System.out.println("Server Started. Waiting for connection ...");
|
||||
Socket socket = server.accept();
|
||||
System.out.println("Got connection from client.");
|
||||
//Get input stream from socket variable and convert the same to DataInputStream
|
||||
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
|
||||
//Read type and length of data
|
||||
char dataType = in.readChar();
|
||||
int length = in.readInt();
|
||||
System.out.println("Type : "+dataType);
|
||||
System.out.println("Lenght :"+length);
|
||||
if(dataType == 's') {
|
||||
//Read String data in bytes
|
||||
byte[] messageByte = new byte[length];
|
||||
boolean end = false;
|
||||
StringBuilder dataString = new StringBuilder(length);
|
||||
int totalBytesRead = 0;
|
||||
//We need to run while loop, to read all data in that stream
|
||||
while(!end) {
|
||||
int currentBytesRead = in.read(messageByte);
|
||||
totalBytesRead = currentBytesRead + totalBytesRead;
|
||||
if(totalBytesRead <= length) {
|
||||
dataString.append(new String(messageByte,0,currentBytesRead,StandardCharsets.UTF_8));
|
||||
} else {
|
||||
dataString.append(new String(messageByte,0,length - totalBytesRead + currentBytesRead,StandardCharsets.UTF_8));
|
||||
}
|
||||
if(dataString.length()>=length) {
|
||||
end = true;
|
||||
}
|
||||
}
|
||||
System.out.println("Read "+length+" bytes of message from client. Message = "+dataString);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.baeldung.socket.read;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class SocketReadAllDataLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenServerAndClient_whenClientSendsAndServerReceivesData_thenCorrect() {
|
||||
//Run server in new thread
|
||||
Runnable runnable1 = () -> { runServer(); };
|
||||
Thread thread1 = new Thread(runnable1);
|
||||
thread1.start();
|
||||
//Wait for 10 seconds
|
||||
try {
|
||||
TimeUnit.SECONDS.sleep(10);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
//Run client in a new thread
|
||||
Runnable runnable2 = () -> { runClient(); };
|
||||
Thread thread2 = new Thread(runnable2);
|
||||
thread2.start();
|
||||
}
|
||||
|
||||
public static void runServer() {
|
||||
//Run Server
|
||||
Server server = new Server();
|
||||
server.runServer(5555);
|
||||
}
|
||||
|
||||
public static void runClient() {
|
||||
//Run Client
|
||||
Client client = new Client();
|
||||
client.runClient("127.0.0.1", 5555);
|
||||
}
|
||||
}
|
@ -6,3 +6,5 @@ This module uses Java 9, so make sure to have the JDK 9 installed to run it.
|
||||
### Relevant Articles:
|
||||
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
- [Guide to java.lang.ProcessBuilder API](https://www.baeldung.com/java-lang-processbuilder-api)
|
||||
|
||||
|
@ -50,3 +50,4 @@
|
||||
- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
|
||||
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
|
||||
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
|
||||
- [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post)
|
||||
|
@ -2,3 +2,5 @@
|
||||
|
||||
- [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type)
|
||||
- [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges)
|
||||
- [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts)
|
||||
- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison)
|
||||
|
@ -13,4 +13,66 @@
|
||||
<relativePath>../parent-kotlin</relativePath>
|
||||
</parent>
|
||||
|
||||
</project>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-test</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-maven-plugin</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>compile</id>
|
||||
<phase>compile</phase>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>test-compile</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>test-compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<jvmTarget>1.8</jvmTarget>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<kotlin.version>1.2.71</kotlin.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>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.annotations
|
||||
|
||||
@Target(AnnotationTarget.FIELD)
|
||||
annotation class Positive
|
||||
|
||||
@Target(AnnotationTarget.FIELD)
|
||||
annotation class AllowedNames(val names: Array<String>)
|
@ -0,0 +1,3 @@
|
||||
package com.baeldung.annotations
|
||||
|
||||
class Item(@Positive val amount: Float, @AllowedNames(["Alice", "Bob"]) val name: String)
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.annotations
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val item = Item(amount = 1.0f, name = "Bob")
|
||||
val validator = Validator()
|
||||
println("Is instance valid? ${validator.isValid(item)}")
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
package com.baeldung.annotations
|
||||
|
||||
/**
|
||||
* Naive annotation-based validator.
|
||||
* @author A.Shcherbakov
|
||||
*/
|
||||
class Validator() {
|
||||
|
||||
/**
|
||||
* Return true if every item's property annotated with @Positive is positive and if
|
||||
* every item's property annotated with @AllowedNames has a value specified in that annotation.
|
||||
*/
|
||||
fun isValid(item: Item): Boolean {
|
||||
val fields = item::class.java.declaredFields
|
||||
for (field in fields) {
|
||||
field.isAccessible = true
|
||||
for (annotation in field.annotations) {
|
||||
val value = field.get(item)
|
||||
if (field.isAnnotationPresent(Positive::class.java)) {
|
||||
val amount = value as Float
|
||||
if (amount < 0) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if (field.isAnnotationPresent(AllowedNames::class.java)) {
|
||||
val allowedNames = field.getAnnotation(AllowedNames::class.java)?.names
|
||||
val name = value as String
|
||||
allowedNames?.let {
|
||||
if (!it.contains(name)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.range
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
for (ch in 'a'..'f') {
|
||||
print(ch)
|
||||
}
|
||||
println()
|
||||
|
||||
for (ch in 'f' downTo 'a') {
|
||||
print(ch)
|
||||
}
|
||||
}
|
21
core-kotlin-2/src/main/kotlin/com/baeldung/range/Color.kt
Normal file
21
core-kotlin-2/src/main/kotlin/com/baeldung/range/Color.kt
Normal file
@ -0,0 +1,21 @@
|
||||
package com.baeldung.range
|
||||
|
||||
enum class Color(val rgb: Int) {
|
||||
BLUE(0x0000FF),
|
||||
GREEN(0x008000),
|
||||
RED(0xFF0000),
|
||||
MAGENTA(0xFF00FF),
|
||||
YELLOW(0xFFFF00);
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
println(Color.values().toList());
|
||||
val red = Color.RED
|
||||
val yellow = Color.YELLOW
|
||||
val range = red..yellow
|
||||
|
||||
println(range.contains(Color.MAGENTA))
|
||||
println(range.contains(Color.BLUE))
|
||||
println(range.contains(Color.GREEN))
|
||||
}
|
18
core-kotlin-2/src/main/kotlin/com/baeldung/range/Filter.kt
Normal file
18
core-kotlin-2/src/main/kotlin/com/baeldung/range/Filter.kt
Normal file
@ -0,0 +1,18 @@
|
||||
package com.baeldung.range
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val r = 1..10
|
||||
|
||||
//Apply filter
|
||||
val f = r.filter { it -> it % 2 == 0 }
|
||||
println(f)
|
||||
|
||||
//Map
|
||||
val m = r.map { it -> it * it }
|
||||
println(m)
|
||||
|
||||
//Reduce
|
||||
val rdc = r.reduce { a, b -> a + b }
|
||||
println(rdc)
|
||||
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.range
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
println((1..9).first)
|
||||
println((1..9 step 2).step)
|
||||
println((3..9).reversed().last)
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.range
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
val r = 1..20
|
||||
println(r.min())
|
||||
println(r.max())
|
||||
println(r.sum())
|
||||
println(r.average())
|
||||
println(r.count())
|
||||
|
||||
val repeated = listOf(1, 1, 2, 4, 4, 6, 10)
|
||||
println(repeated.distinct())
|
||||
}
|
28
core-kotlin-2/src/main/kotlin/com/baeldung/range/Range.kt
Normal file
28
core-kotlin-2/src/main/kotlin/com/baeldung/range/Range.kt
Normal file
@ -0,0 +1,28 @@
|
||||
package com.baeldung.range
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
for (i in 1..9) {
|
||||
print(i)
|
||||
}
|
||||
println()
|
||||
|
||||
for (i in 9 downTo 1) {
|
||||
print(i)
|
||||
}
|
||||
println()
|
||||
|
||||
for (i in 1.rangeTo(9)) {
|
||||
print(i)
|
||||
}
|
||||
println()
|
||||
|
||||
for (i in 9.downTo(1)) {
|
||||
print(i)
|
||||
}
|
||||
println()
|
||||
|
||||
for (i in 1 until 9) {
|
||||
print(i)
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.range
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
(1..9).reversed().forEach {
|
||||
print(it)
|
||||
}
|
||||
|
||||
println()
|
||||
|
||||
(1..9).reversed().step(3).forEach {
|
||||
print(it)
|
||||
}
|
||||
}
|
15
core-kotlin-2/src/main/kotlin/com/baeldung/range/Step.kt
Normal file
15
core-kotlin-2/src/main/kotlin/com/baeldung/range/Step.kt
Normal file
@ -0,0 +1,15 @@
|
||||
package com.baeldung.range
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
for(i in 1..9 step 2){
|
||||
print(i)
|
||||
}
|
||||
|
||||
println()
|
||||
|
||||
for (i in 9 downTo 1 step 2){
|
||||
print(i)
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.range
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
for (i in 1 until 9) {
|
||||
print(i)
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.scope
|
||||
|
||||
data class Student(var studentId: String = "", var name: String = "", var surname: String = "") {
|
||||
}
|
||||
|
||||
data class Teacher(var teacherId: Int = 0, var name: String = "", var surname: String = "") {
|
||||
fun setId(anId: Int): Teacher = apply { teacherId = anId }
|
||||
fun setName(aName: String): Teacher = apply { name = aName }
|
||||
fun setSurname(aSurname: String): Teacher = apply { surname = aSurname }
|
||||
}
|
||||
|
||||
data class Headers(val headerInfo: String)
|
||||
|
||||
data class Response(val headers: Headers)
|
||||
|
||||
data class RestClient(val url: String) {
|
||||
fun getResponse() = Response(Headers("some header info"))
|
||||
}
|
||||
|
||||
data class BankAccount(val id: Int) {
|
||||
fun checkAuthorization(username: String) = Unit
|
||||
fun addPayee(payee: String) = Unit
|
||||
fun makePayment(paymentDetails: String) = Unit
|
||||
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.annotations
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.test.assertFalse
|
||||
|
||||
class ValidationTest {
|
||||
|
||||
@Test
|
||||
fun whenAmountIsOneAndNameIsAlice_thenTrue() {
|
||||
assertTrue(Validator().isValid(Item(1f, "Alice")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenAmountIsOneAndNameIsBob_thenTrue() {
|
||||
assertTrue(Validator().isValid(Item(1f, "Bob")))
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun whenAmountIsMinusOneAndNameIsAlice_thenFalse() {
|
||||
assertFalse(Validator().isValid(Item(-1f, "Alice")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenAmountIsMinusOneAndNameIsBob_thenFalse() {
|
||||
assertFalse(Validator().isValid(Item(-1f, "Bob")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenAmountIsOneAndNameIsTom_thenFalse() {
|
||||
assertFalse(Validator().isValid(Item(1f, "Tom")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenAmountIsMinusOneAndNameIsTom_thenFalse() {
|
||||
assertFalse(Validator().isValid(Item(-1f, "Tom")))
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.range
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class CharRangeTest {
|
||||
|
||||
@Test
|
||||
fun testCharRange() {
|
||||
assertEquals(listOf('a', 'b', 'c'), ('a'..'c').toList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCharDownRange() {
|
||||
assertEquals(listOf('c', 'b', 'a'), ('c'.downTo('a')).toList())
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.range
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class ColorTest {
|
||||
|
||||
@Test
|
||||
fun testEnumRange() {
|
||||
|
||||
println(Color.values().toList());
|
||||
val red = Color.RED
|
||||
val yellow = Color.YELLOW
|
||||
val range = red..yellow
|
||||
|
||||
assertTrue { range.contains(Color.MAGENTA) }
|
||||
assertFalse { range.contains(Color.BLUE) }
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.range
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class FilterTest {
|
||||
|
||||
val r = 1..10
|
||||
|
||||
@Test
|
||||
fun filterTest() {
|
||||
assertEquals(listOf(2, 4, 6, 8, 10), r.filter { it -> it % 2 == 0 }.toList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mapTest() {
|
||||
assertEquals(listOf(1, 4, 9, 16, 25, 36, 49, 64, 81, 100), r.map { it -> it * it }.toList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reduceTest() {
|
||||
assertEquals(55, r.reduce { a, b -> a + b })
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.range
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class FirstLastTest {
|
||||
|
||||
@Test
|
||||
fun testFirst() {
|
||||
assertEquals(1, (1..9).first)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testLast() {
|
||||
assertEquals(9, (1..9).last)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testStep() {
|
||||
assertEquals(2, (1..9 step 2).step)
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.baeldung.range
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class OtherRangeFunctionsTest {
|
||||
|
||||
val r = 1..20
|
||||
val repeated = listOf(1, 1, 2, 4, 4, 6, 10)
|
||||
|
||||
@Test
|
||||
fun testMin() {
|
||||
assertEquals(1, r.min())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMax() {
|
||||
assertEquals(20, r.max())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSum() {
|
||||
assertEquals(210, r.sum())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testAverage() {
|
||||
assertEquals(10.5, r.average())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCount() {
|
||||
assertEquals(20, r.count())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDistinct() {
|
||||
assertEquals(listOf(1, 2, 4, 6, 10), repeated.distinct())
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.range
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class RangeTest {
|
||||
|
||||
@Test
|
||||
fun testRange() {
|
||||
assertEquals(listOf(1,2,3), (1.rangeTo(3).toList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDownTo(){
|
||||
assertEquals(listOf(3,2,1), (3.downTo(1).toList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUntil(){
|
||||
assertEquals(listOf(1,2), (1.until(3).toList()))
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.range
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class ReverseRangeTest {
|
||||
|
||||
@Test
|
||||
fun reversedTest() {
|
||||
assertEquals(listOf(9, 6, 3), (1..9).reversed().step(3).toList())
|
||||
}
|
||||
}
|
17
core-kotlin-2/src/test/kotlin/com/baeldung/range/StepTest.kt
Normal file
17
core-kotlin-2/src/test/kotlin/com/baeldung/range/StepTest.kt
Normal file
@ -0,0 +1,17 @@
|
||||
package com.baeldung.range
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class StepTest {
|
||||
|
||||
@Test
|
||||
fun testStep() {
|
||||
assertEquals(listOf(1, 3, 5, 7, 9), (1..9 step 2).toList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testStepDown() {
|
||||
assertEquals(listOf(9, 7, 5, 3, 1), (9 downTo 1 step 2).toList())
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.range
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class UntilRangeTest {
|
||||
|
||||
@Test
|
||||
fun testUntil() {
|
||||
assertEquals(listOf(1, 2, 3, 4), (1 until 5).toList())
|
||||
}
|
||||
}
|
@ -0,0 +1,143 @@
|
||||
package com.baeldung.scope
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
|
||||
class ScopeFunctionsUnitTest {
|
||||
|
||||
class Logger {
|
||||
|
||||
var called : Boolean = false
|
||||
|
||||
fun info(message: String) {
|
||||
called = true
|
||||
}
|
||||
|
||||
fun wasCalled() = called
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldTransformWhenLetFunctionUsed() {
|
||||
val stringBuider = StringBuilder()
|
||||
val numberOfCharacters = stringBuider.let {
|
||||
it.append("This is a transformation function.")
|
||||
it.append("It takes a StringBuilder instance and returns the number of characters in the generated String")
|
||||
it.length
|
||||
}
|
||||
|
||||
assertTrue {
|
||||
numberOfCharacters == 128
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldHandleNullabilityWhenLetFunctionUsed() {
|
||||
|
||||
val message: String? = "hello there!"
|
||||
val charactersInMessage = message?.let {
|
||||
"At this point is safe to reference the variable. Let's print the message: $it"
|
||||
} ?: "default value"
|
||||
|
||||
assertTrue {
|
||||
charactersInMessage.equals("At this point is safe to reference the variable. Let's print the message: hello there!")
|
||||
}
|
||||
|
||||
val aNullMessage = null
|
||||
val thisIsNull = aNullMessage?.let {
|
||||
"At this point it would be safe to reference the variable. But it will not really happen because it is null. Let's reference: $it"
|
||||
} ?: "default value"
|
||||
|
||||
assertTrue {
|
||||
thisIsNull.equals("default value")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldInitializeObjectWhenUsingApply() {
|
||||
val aStudent = Student().apply {
|
||||
studentId = "1234567"
|
||||
name = "Mary"
|
||||
surname = "Smith"
|
||||
}
|
||||
|
||||
assertTrue {
|
||||
aStudent.name.equals("Mary")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldAllowBuilderStyleObjectDesignWhenApplyUsedInClassMethods() {
|
||||
val teacher = Teacher()
|
||||
.setId(1000)
|
||||
.setName("Martha")
|
||||
.setSurname("Spector")
|
||||
|
||||
assertTrue {
|
||||
teacher.surname.equals("Spector")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldAllowSideEffectWhenUsingAlso() {
|
||||
val restClient = RestClient("http://www.someurl.com")
|
||||
|
||||
val logger = Logger()
|
||||
|
||||
val headers = restClient
|
||||
.getResponse()
|
||||
.also { logger.info(it.toString()) }
|
||||
.headers
|
||||
|
||||
assertTrue {
|
||||
logger.wasCalled() && headers.headerInfo.equals("some header info")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldInitializeFieldWhenAlsoUsed() {
|
||||
val aStudent = Student().also { it.name = "John"}
|
||||
|
||||
assertTrue {
|
||||
aStudent.name.equals("John")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldLogicallyGroupObjectCallsWhenUsingWith() {
|
||||
val bankAccount = BankAccount(1000)
|
||||
with (bankAccount) {
|
||||
checkAuthorization("someone")
|
||||
addPayee("some payee")
|
||||
makePayment("payment information")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldConvertObjectWhenRunUsed() {
|
||||
val stringBuider = StringBuilder()
|
||||
val numberOfCharacters = stringBuider.run {
|
||||
append("This is a transformation function.")
|
||||
append("It takes a StringBuilder instance and returns the number of characters in the generated String")
|
||||
length
|
||||
}
|
||||
|
||||
assertTrue {
|
||||
numberOfCharacters == 128
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shouldHandleNullabilityWhenRunIsUsed() {
|
||||
val message: String? = "hello there!"
|
||||
val charactersInMessage = message?.run {
|
||||
"At this point is safe to reference the variable. Let's print the message: $this"
|
||||
} ?: "default value"
|
||||
|
||||
assertTrue {
|
||||
charactersInMessage.equals("At this point is safe to reference the variable. Let's print the message: hello there!")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -55,3 +55,4 @@
|
||||
- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl)
|
||||
- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods)
|
||||
- [Inline Functions in Kotlin](https://www.baeldung.com/kotlin-inline-functions)
|
||||
- [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern)
|
||||
|
@ -11,3 +11,6 @@
|
||||
- [Convert JSON to a Map Using Gson](https://www.baeldung.com/gson-json-to-map)
|
||||
- [Working with Primitive Values in Gson](https://www.baeldung.com/java-gson-primitives)
|
||||
- [Convert String to JsonObject with Gson](https://www.baeldung.com/gson-string-to-jsonobject)
|
||||
- [Mapping Multiple JSON Fields to One Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field)
|
||||
- [Serializing and Deserializing a List with Gson](https://www.baeldung.com/gson-list)
|
||||
|
||||
|
13
jackson-2/.gitignore
vendored
Normal file
13
jackson-2/.gitignore
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
9
jackson-2/README.md
Normal file
9
jackson-2/README.md
Normal file
@ -0,0 +1,9 @@
|
||||
=========
|
||||
|
||||
## Jackson Cookbooks and Examples
|
||||
|
||||
###The Course
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles:
|
||||
- [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field)
|
52
jackson-2/pom.xml
Normal file
52
jackson-2/pom.xml
Normal file
@ -0,0 +1,52 @@
|
||||
<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>jackson-2</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>jackson-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- marshalling -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>jackson-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj.version>3.11.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
13
jackson-2/src/main/resources/logback.xml
Normal file
13
jackson-2/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
45
java-collections-maps-2/pom.xml
Normal file
45
java-collections-maps-2/pom.xml
Normal file
@ -0,0 +1,45 @@
|
||||
<?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>java-collections-maps-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>java-collections-maps-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.eclipse.collections</groupId>
|
||||
<artifactId>eclipse-collections</artifactId>
|
||||
<version>${eclipse-collections.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.sf.trove4j</groupId>
|
||||
<artifactId>trove4j</artifactId>
|
||||
<version>3.0.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>8.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>colt</groupId>
|
||||
<artifactId>colt</artifactId>
|
||||
<version>1.2.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<eclipse-collections.version>8.2.0</eclipse-collections.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,69 @@
|
||||
package com.baeldung.map;
|
||||
|
||||
import cern.colt.map.AbstractIntDoubleMap;
|
||||
import cern.colt.map.OpenIntDoubleHashMap;
|
||||
import gnu.trove.map.TDoubleIntMap;
|
||||
import gnu.trove.map.hash.TDoubleIntHashMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2BooleanMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMaps;
|
||||
import org.eclipse.collections.api.map.primitive.ImmutableIntIntMap;
|
||||
import org.eclipse.collections.api.map.primitive.MutableIntIntMap;
|
||||
import org.eclipse.collections.api.map.primitive.MutableObjectDoubleMap;
|
||||
import org.eclipse.collections.impl.factory.primitive.IntIntMaps;
|
||||
import org.eclipse.collections.impl.factory.primitive.ObjectDoubleMaps;
|
||||
|
||||
public class PrimitiveMaps {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
eclipseCollectionsMap();
|
||||
troveMap();
|
||||
coltMap();
|
||||
fastutilMap();
|
||||
}
|
||||
|
||||
private static void fastutilMap() {
|
||||
Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap();
|
||||
int2BooleanMap.put(1, true);
|
||||
int2BooleanMap.put(7, false);
|
||||
int2BooleanMap.put(4, true);
|
||||
|
||||
boolean value = int2BooleanMap.get(1);
|
||||
|
||||
Int2BooleanSortedMap int2BooleanSorted = Int2BooleanSortedMaps.EMPTY_MAP;
|
||||
}
|
||||
|
||||
private static void coltMap() {
|
||||
AbstractIntDoubleMap map = new OpenIntDoubleHashMap();
|
||||
map.put(1, 4.5);
|
||||
double value = map.get(1);
|
||||
}
|
||||
|
||||
private static void eclipseCollectionsMap() {
|
||||
MutableIntIntMap mutableIntIntMap = IntIntMaps.mutable.empty();
|
||||
mutableIntIntMap.addToValue(1, 1);
|
||||
|
||||
ImmutableIntIntMap immutableIntIntMap = IntIntMaps.immutable.empty();
|
||||
|
||||
MutableObjectDoubleMap<String> dObject = ObjectDoubleMaps.mutable.empty();
|
||||
dObject.addToValue("price", 150.5);
|
||||
dObject.addToValue("quality", 4.4);
|
||||
dObject.addToValue("stability", 0.8);
|
||||
}
|
||||
|
||||
private static void troveMap() {
|
||||
double[] doubles = new double[] {1.2, 4.5, 0.3};
|
||||
int[] ints = new int[] {1, 4, 0};
|
||||
|
||||
TDoubleIntMap doubleIntMap = new TDoubleIntHashMap(doubles, ints);
|
||||
|
||||
doubleIntMap.put(1.2, 22);
|
||||
doubleIntMap.put(4.5, 16);
|
||||
|
||||
doubleIntMap.adjustValue(1.2, 1);
|
||||
doubleIntMap.adjustValue(4.5, 4);
|
||||
doubleIntMap.adjustValue(0.3, 7);
|
||||
}
|
||||
}
|
29
java-dates-2/.gitignore
vendored
Normal file
29
java-dates-2/.gitignore
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
*.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
|
||||
|
||||
#jenv
|
||||
.java-version
|
55
java-dates-2/pom.xml
Normal file
55
java-dates-2/pom.xml
Normal file
@ -0,0 +1,55 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-dates-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>java-dates-2</name>
|
||||
|
||||
<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.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>java-dates-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
</properties>
|
||||
</project>
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.xmlgregoriancalendar;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.xml.datatype.DatatypeConfigurationException;
|
||||
import javax.xml.datatype.DatatypeConstants;
|
||||
import javax.xml.datatype.DatatypeFactory;
|
||||
import javax.xml.datatype.XMLGregorianCalendar;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class XmlGregorianCalendarConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void fromLocalDateToXMLGregorianCalendar() throws DatatypeConfigurationException {
|
||||
LocalDate localDate = LocalDate.of(2017, 4, 25);
|
||||
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(localDate.toString());
|
||||
|
||||
assertThat(xmlGregorianCalendar.getYear()).isEqualTo(localDate.getYear());
|
||||
assertThat(xmlGregorianCalendar.getMonth()).isEqualTo(localDate.getMonthValue());
|
||||
assertThat(xmlGregorianCalendar.getDay()).isEqualTo(localDate.getDayOfMonth());
|
||||
assertThat(xmlGregorianCalendar.getTimezone()).isEqualTo(DatatypeConstants.FIELD_UNDEFINED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fromXMLGregorianCalendarToLocalDate() throws DatatypeConfigurationException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-04-25");
|
||||
LocalDate localDate = LocalDate.of(xmlGregorianCalendar.getYear(), xmlGregorianCalendar.getMonth(), xmlGregorianCalendar.getDay());
|
||||
|
||||
assertThat(localDate.getYear()).isEqualTo(xmlGregorianCalendar.getYear());
|
||||
assertThat(localDate.getMonthValue()).isEqualTo(xmlGregorianCalendar.getMonth());
|
||||
assertThat(localDate.getDayOfMonth()).isEqualTo(xmlGregorianCalendar.getDay());
|
||||
}
|
||||
|
||||
}
|
3
java-streams-2/README.md
Normal file
3
java-streams-2/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
|
||||
|
@ -17,3 +17,4 @@
|
||||
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
|
||||
- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count)
|
||||
- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api)
|
||||
- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams)
|
||||
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.filters;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.annotation.WebFilter;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebFilter(urlPatterns = "/uppercase")
|
||||
public class EmptyParamFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
|
||||
FilterChain filterChain) throws IOException, ServletException {
|
||||
String inputString = servletRequest.getParameter("input");
|
||||
|
||||
if (inputString != null && inputString.matches("[A-Za-z0-9]+")) {
|
||||
filterChain.doFilter(servletRequest, servletResponse);
|
||||
} else {
|
||||
servletResponse.getWriter().println("Missing input parameter");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.listeners;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
import javax.servlet.annotation.WebListener;
|
||||
|
||||
@WebListener
|
||||
public class AppListener implements ServletContextListener {
|
||||
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent event) {
|
||||
ServletContext context = event.getServletContext();
|
||||
context.setAttribute("counter", 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent event) {
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.listeners;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletRequestEvent;
|
||||
import javax.servlet.ServletRequestListener;
|
||||
import javax.servlet.annotation.WebListener;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@WebListener
|
||||
public class RequestListener implements ServletRequestListener {
|
||||
|
||||
@Override
|
||||
public void requestInitialized(ServletRequestEvent event) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void requestDestroyed(ServletRequestEvent event) {
|
||||
HttpServletRequest request = (HttpServletRequest)event.getServletRequest();
|
||||
if (!request.getServletPath().equals("/counter")) {
|
||||
ServletContext context = event.getServletContext();
|
||||
context.setAttribute("counter", (int)context.getAttribute("counter") + 1);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
@WebServlet(urlPatterns = "/counter", name = "counterServlet")
|
||||
public class CounterServlet extends HttpServlet {
|
||||
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
PrintWriter out = response.getWriter();
|
||||
|
||||
int count = (int)request.getServletContext().getAttribute("counter");
|
||||
|
||||
out.println("Request counter: " + count);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
@WebServlet(urlPatterns = "/uppercase", name = "uppercaseServlet")
|
||||
public class UppercaseServlet extends HttpServlet {
|
||||
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
String inputString = request.getParameter("input").toUpperCase();
|
||||
|
||||
PrintWriter out = response.getWriter();
|
||||
|
||||
out.println(inputString);
|
||||
}
|
||||
}
|
@ -19,6 +19,14 @@
|
||||
<name>exposed</name>
|
||||
<url>https://dl.bintray.com/kotlin/exposed</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
<id>kotlinx</id>
|
||||
<name>bintray</name>
|
||||
<url>https://dl.bintray.com/kotlin/kotlinx</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
@ -112,9 +120,30 @@
|
||||
<version>3.3.0</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/junit/junit -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>27.1-jre</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-collections-immutable -->
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlinx</groupId>
|
||||
<artifactId>kotlinx-collections-immutable</artifactId>
|
||||
<version>0.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
||||
<kodein.version>4.1.0</kodein.version>
|
||||
<klaxon.version>3.0.4</klaxon.version>
|
||||
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.kotlin.immutable
|
||||
|
||||
import junit.framework.Assert.assertEquals
|
||||
import kotlinx.collections.immutable.ImmutableList
|
||||
import kotlinx.collections.immutable.immutableListOf
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.ExpectedException
|
||||
|
||||
class KotlinxImmutablesUnitTest{
|
||||
|
||||
|
||||
@Rule
|
||||
@JvmField
|
||||
var ee : ExpectedException = ExpectedException.none()
|
||||
|
||||
@Test
|
||||
fun givenKICLList_whenAddTried_checkExceptionThrown(){
|
||||
|
||||
val list: ImmutableList<String> = immutableListOf("I", "am", "immutable")
|
||||
|
||||
list.add("My new item")
|
||||
|
||||
assertEquals(listOf("I", "am", "immutable"), list)
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
package com.baeldung.kotlin.immutable
|
||||
|
||||
import com.google.common.collect.ImmutableList
|
||||
import com.google.common.collect.ImmutableSet
|
||||
import junit.framework.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.ExpectedException
|
||||
|
||||
class ReadOnlyUnitTest{
|
||||
|
||||
@Test
|
||||
fun givenReadOnlyList_whenCastToMutableList_checkNewElementsAdded(){
|
||||
|
||||
val list: List<String> = listOf("This", "Is", "Totally", "Immutable")
|
||||
|
||||
(list as MutableList<String>)[2] = "Not"
|
||||
|
||||
assertEquals(listOf("This", "Is", "Not", "Immutable"), list)
|
||||
|
||||
}
|
||||
|
||||
@Rule
|
||||
@JvmField
|
||||
var ee : ExpectedException = ExpectedException.none()
|
||||
|
||||
@Test
|
||||
fun givenImmutableList_whenAddTried_checkExceptionThrown(){
|
||||
|
||||
val list: List<String> = ImmutableList.of("I", "am", "actually", "immutable")
|
||||
|
||||
ee.expect(UnsupportedOperationException::class.java)
|
||||
|
||||
(list as MutableList<String>).add("Oops")
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenMutableList_whenCopiedAndAddTried_checkExceptionThrown(){
|
||||
|
||||
val mutableList : List<String> = listOf("I", "Am", "Definitely", "Immutable")
|
||||
|
||||
(mutableList as MutableList<String>)[2] = "100% Not"
|
||||
|
||||
assertEquals(listOf("I", "Am", "100% Not", "Immutable"), mutableList)
|
||||
|
||||
val list: List<String> = ImmutableList.copyOf(mutableList)
|
||||
|
||||
ee.expect(UnsupportedOperationException::class.java)
|
||||
|
||||
(list as MutableList<String>)[2] = "Really?"
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenImmutableSetBuilder_whenAddTried_checkExceptionThrown(){
|
||||
|
||||
val mutableList : List<String> = listOf("Hello", "Baeldung")
|
||||
val set: ImmutableSet<String> = ImmutableSet.builder<String>()
|
||||
.add("I","am","immutable")
|
||||
.addAll(mutableList)
|
||||
.build()
|
||||
|
||||
assertEquals(setOf("Hello", "Baeldung", "I", "am", "immutable"), set)
|
||||
|
||||
ee.expect(UnsupportedOperationException::class.java)
|
||||
|
||||
(set as MutableSet<String>).add("Oops")
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -6,4 +6,5 @@
|
||||
- [Lombok Builder with Default Value](https://www.baeldung.com/lombok-builder-default-value)
|
||||
- [Lombok Builder with Custom Setter](https://www.baeldung.com/lombok-builder-custom-setter)
|
||||
- [Setting up Lombok with Eclipse and Intellij](https://www.baeldung.com/lombok-ide)
|
||||
- [Using the @Singular Annotation with Lombok Builders](https://www.baeldung.com/lombok-builder-singular)
|
||||
|
||||
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.lombok.builder.singular;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.Singular;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@Getter
|
||||
@Builder
|
||||
public class Person {
|
||||
|
||||
private final String givenName;
|
||||
private final String additionalName;
|
||||
private final String familyName;
|
||||
|
||||
private final List<String> tags;
|
||||
@Singular private final List<String> interests;
|
||||
@Singular private final Set<String> skills;
|
||||
@Singular private final Map<String, LocalDate> awards;
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.lombok.builder.singular;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.Singular;
|
||||
|
||||
@Getter
|
||||
@Builder
|
||||
public class Sea {
|
||||
|
||||
@Singular private final List<String> grasses;
|
||||
@Singular("oneFish") private final List<String> fish;
|
||||
}
|
@ -0,0 +1,192 @@
|
||||
package com.baeldung.lombok.builder.singular;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
public class BuilderWithSingularSupportForCollectionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void canAddMultipleElementsAsNewCollection() throws Exception {
|
||||
Person person = Person.builder()
|
||||
.givenName("Aaron")
|
||||
.additionalName("A")
|
||||
.familyName("Aardvark")
|
||||
.tags(Arrays.asList("fictional", "incidental"))
|
||||
.build();
|
||||
|
||||
assertThat(person.getTags(), containsInAnyOrder("fictional", "incidental"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void canUpdateCollectionAfterBuildIfMutableCollectionPassedToBuilder() throws Exception {
|
||||
|
||||
List<String> tags = new ArrayList();
|
||||
tags.add("fictional");
|
||||
tags.add("incidental");
|
||||
Person person = Person.builder()
|
||||
.givenName("Aaron")
|
||||
.additionalName("A")
|
||||
.familyName("Aardvark")
|
||||
.tags(tags)
|
||||
.build();
|
||||
person.getTags()
|
||||
.clear();
|
||||
person.getTags()
|
||||
.add("non-fictional");
|
||||
person.getTags()
|
||||
.add("important");
|
||||
|
||||
assertThat(person.getTags(), containsInAnyOrder("non-fictional", "important"));
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void cannotUpdateCollectionAfterBuildIfImmutableCollectionPassedToBuilder() throws Exception {
|
||||
List<String> tags = Arrays.asList("fictional", "incidental");
|
||||
Person person = Person.builder()
|
||||
.givenName("Aaron")
|
||||
.additionalName("A")
|
||||
.familyName("Aardvark")
|
||||
.tags(tags)
|
||||
.build();
|
||||
person.getTags()
|
||||
.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void canAssignToSingularAnnotatedCollectionOneByOne() throws Exception {
|
||||
|
||||
Person person = Person.builder()
|
||||
.givenName("Aaron")
|
||||
.additionalName("A")
|
||||
.familyName("Aardvark")
|
||||
.interest("history")
|
||||
.interest("sport")
|
||||
.build();
|
||||
|
||||
assertThat(person.getInterests(), containsInAnyOrder("sport", "history"));
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void singularAnnotatedBuilderCreatesImmutableCollection() throws Exception {
|
||||
|
||||
Person person = Person.builder()
|
||||
.givenName("Aaron")
|
||||
.additionalName("A")
|
||||
.familyName("Aardvark")
|
||||
.interest("history")
|
||||
.interest("sport")
|
||||
.build();
|
||||
person.getInterests()
|
||||
.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unpopulatedListsCreatedAsNullIfNotSingularButEmptyArrayIfSingular() throws Exception {
|
||||
|
||||
Person person = Person.builder()
|
||||
.givenName("Aaron")
|
||||
.additionalName("A")
|
||||
.familyName("Aardvark")
|
||||
.build();
|
||||
assertThat(person.getInterests(), hasSize(0));
|
||||
assertThat(person.getSkills(), hasSize(0));
|
||||
assertThat(person.getAwards()
|
||||
.keySet(), hasSize(0));
|
||||
assertThat(person.getTags(), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void singularSupportsSetsToo() throws Exception {
|
||||
|
||||
Person person = Person.builder()
|
||||
.givenName("Aaron")
|
||||
.additionalName("A")
|
||||
.familyName("Aardvark")
|
||||
.skill("singing")
|
||||
.skill("dancing")
|
||||
.build();
|
||||
assertThat(person.getSkills(), contains("singing", "dancing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void singularSetsAreLenientWithDuplicates() throws Exception {
|
||||
|
||||
Person person = Person.builder()
|
||||
.givenName("Aaron")
|
||||
.additionalName("A")
|
||||
.familyName("Aardvark")
|
||||
.interest("singing")
|
||||
.interest("singing")
|
||||
.skill("singing")
|
||||
.skill("singing")
|
||||
.build();
|
||||
assertThat(person.getInterests(), contains("singing", "singing"));
|
||||
assertThat(person.getSkills(), contains("singing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void singularSupportsMapsToo() throws Exception {
|
||||
|
||||
Person person = Person.builder()
|
||||
.givenName("Aaron")
|
||||
.additionalName("A")
|
||||
.familyName("Aardvark")
|
||||
.award("Singer of the Year", LocalDate.now()
|
||||
.minusYears(5))
|
||||
.award("Best Dancer", LocalDate.now()
|
||||
.minusYears(2))
|
||||
.build();
|
||||
assertThat(person.getAwards()
|
||||
.keySet(), contains("Singer of the Year", "Best Dancer"));
|
||||
assertThat(person.getAwards()
|
||||
.get("Best Dancer"),
|
||||
is(LocalDate.now()
|
||||
.minusYears(2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void singularIsLenientWithMapKeys() throws Exception {
|
||||
|
||||
Person person = Person.builder()
|
||||
.givenName("Aaron")
|
||||
.additionalName("A")
|
||||
.familyName("Aardvark")
|
||||
.award("Best Dancer", LocalDate.now()
|
||||
.minusYears(5))
|
||||
.award("Best Dancer", LocalDate.now()
|
||||
.minusYears(4))
|
||||
.award("Best Dancer", LocalDate.now()
|
||||
.minusYears(3))
|
||||
.award("Best Dancer", LocalDate.now()
|
||||
.minusYears(2))
|
||||
.award("Best Dancer", LocalDate.now()
|
||||
.minusYears(1))
|
||||
.build();
|
||||
assertThat(person.getAwards()
|
||||
.keySet(), hasSize(1));
|
||||
assertThat(person.getAwards()
|
||||
.get("Best Dancer"),
|
||||
is(LocalDate.now()
|
||||
.minusYears(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wordsWithNonStandardPlurals() throws Exception {
|
||||
Sea sea = Sea.builder()
|
||||
.grass("Dulse")
|
||||
.grass("Kelp")
|
||||
.oneFish("Cod")
|
||||
.oneFish("Mackerel")
|
||||
.build();
|
||||
assertThat(sea.getGrasses(), contains("Dulse", "Kelp"));
|
||||
assertThat(sea.getFish(), contains("Cod", "Mackerel"));
|
||||
}
|
||||
|
||||
}
|
@ -15,3 +15,4 @@
|
||||
- [Use the Latest Version of a Dependency in Maven](https://www.baeldung.com/maven-dependency-latest-version)
|
||||
- [Multi-Module Project with Maven](https://www.baeldung.com/maven-multi-module)
|
||||
- [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin)
|
||||
- [Eclipse Error: web.xml is missing and failOnMissingWebXml is set to true](https://www.baeldung.com/eclipse-error-web-xml-missing)
|
||||
|
@ -1,3 +1,4 @@
|
||||
### Relevant Articles:
|
||||
- [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern)
|
||||
- [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java)
|
||||
- [Introduction to the Null Object Pattern](https://www.baeldung.com/java-null-object-pattern)
|
||||
|
@ -7,3 +7,4 @@
|
||||
- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
|
||||
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
|
||||
- [A Simple Guide to Connection Pooling in Java](https://www.baeldung.com/java-connection-pooling)
|
||||
- [Guide to the JDBC ResultSet Interface](https://www.baeldung.com/jdbc-resultset)
|
||||
|
@ -83,13 +83,18 @@
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${openjdk-jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>2.3.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>hibernate5</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<directory>src/test/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
@ -113,6 +113,7 @@ public class HibernateUtil {
|
||||
metadataSources.addAnnotatedClass(OptimisticLockingCourse.class);
|
||||
metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
|
||||
metadataSources.addAnnotatedClass(OfficeEmployee.class);
|
||||
metadataSources.addAnnotatedClass(Post.class);
|
||||
|
||||
Metadata metadata = metadataSources.getMetadataBuilder()
|
||||
.applyBasicType(LocalDateStringType.INSTANCE)
|
||||
|
@ -0,0 +1,59 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "posts")
|
||||
public class Post {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private int id;
|
||||
|
||||
private String title;
|
||||
|
||||
private String body;
|
||||
|
||||
public Post() { }
|
||||
|
||||
public Post(String title, String body) {
|
||||
this.title = title;
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void setBody(String body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Post{" +
|
||||
"id=" + id +
|
||||
", title='" + title + '\'' +
|
||||
", body='" + body + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.hibernate.transaction;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.hibernate.query.Query;
|
||||
|
||||
public class PostService {
|
||||
|
||||
|
||||
private Session session;
|
||||
|
||||
public PostService(Session session) {
|
||||
this.session = session;
|
||||
}
|
||||
|
||||
|
||||
public void updatePost(String title, String body, int id) {
|
||||
Transaction txn = session.beginTransaction();
|
||||
Query updateQuery = session.createQuery("UPDATE Post p SET p.title = ?1, p.body = ?2 WHERE p.id = ?3");
|
||||
updateQuery.setParameter(1, title);
|
||||
updateQuery.setParameter(2, body);
|
||||
updateQuery.setParameter(3, id);
|
||||
updateQuery.executeUpdate();
|
||||
txn.commit();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
@ -74,4 +74,6 @@ public class CustomClassIntegrationTest {
|
||||
assertEquals("John Smith", result.getEmployeeName());
|
||||
assertEquals("Sales", result.getDepartmentName());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,57 @@
|
||||
package com.baeldung.hibernate.transaction;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import com.baeldung.hibernate.pojo.Post;
|
||||
import com.baeldung.hibernate.transaction.PostService;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class TransactionIntegrationTest {
|
||||
|
||||
private static PostService postService;
|
||||
private static Session session;
|
||||
private static Logger logger = LoggerFactory.getLogger(TransactionIntegrationTest.class);
|
||||
|
||||
@BeforeClass
|
||||
public static void init() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
|
||||
properties.setProperty("hibernate.connection.url", "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1");
|
||||
properties.setProperty("hibernate.connection.username", "sa");
|
||||
properties.setProperty("hibernate.show_sql", "true");
|
||||
properties.setProperty("jdbc.password", "");
|
||||
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
|
||||
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
|
||||
SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties);
|
||||
session = sessionFactory.openSession();
|
||||
postService = new PostService(session);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTitleAndBody_whenRepositoryUpdatePost_thenUpdatePost() {
|
||||
|
||||
Post post = new Post("This is a title", "This is a sample post");
|
||||
session.persist(post);
|
||||
|
||||
String title = "[UPDATE] Java HowTos";
|
||||
String body = "This is an updated posts on Java how-tos";
|
||||
postService.updatePost(title, body, post.getId());
|
||||
|
||||
session.refresh(post);
|
||||
|
||||
assertEquals(post.getTitle(), title);
|
||||
assertEquals(post.getBody(), body);
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -6,3 +6,4 @@
|
||||
- [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph)
|
||||
- [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time)
|
||||
- [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date)
|
||||
- [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates)
|
||||
|
@ -1,3 +1,4 @@
|
||||
# Relevant Articles
|
||||
|
||||
- [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field)
|
||||
- [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb)
|
||||
|
@ -25,6 +25,11 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-mongodb</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embed</groupId>
|
||||
<artifactId>de.flapdoodle.embed.mongo</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- JUnit Jupiter dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
@ -102,4 +107,4 @@
|
||||
</profiles>
|
||||
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
@ -2,7 +2,6 @@ package com.baeldung.mongodb;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.baeldung.boot.Application;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@ -12,10 +11,11 @@ import org.springframework.data.mongodb.core.MongoTemplate;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
|
||||
import com.baeldung.SpringBootPersistenceApplication;
|
||||
import com.mongodb.BasicDBObjectBuilder;
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
@ContextConfiguration(classes = Application.class)
|
||||
@ContextConfiguration(classes = SpringBootPersistenceApplication.class)
|
||||
@DataMongoTest
|
||||
@ExtendWith(SpringExtension.class)
|
||||
public class MongoDbSpringIntegrationTest {
|
@ -7,3 +7,4 @@
|
||||
- [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot)
|
||||
- [Integrating Spring Boot with HSQLDB](https://www.baeldung.com/spring-boot-hsqldb)
|
||||
- [Configuring a DataSource Programmatically in Spring Boot](https://www.baeldung.com/spring-boot-configure-data-source-programmatic)
|
||||
- [Resolving “Failed to Configure a DataSource” Error](https://www.baeldung.com/spring-boot-failed-to-configure-data-source)
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user