Merge branch 'master' into BAEL-16633

This commit is contained in:
Alessio Stalla
2019-10-29 13:17:27 +01:00
262 changed files with 2537 additions and 4044 deletions

8
.gitignore vendored
View File

@@ -84,4 +84,10 @@ software-security/sql-injection-samples/derby.log
spring-soap/src/main/java/com/baeldung/springsoap/gen/ spring-soap/src/main/java/com/baeldung/springsoap/gen/
/report-*.json /report-*.json
transaction.log transaction.log
*-shell.log *-shell.log
apache-cxf/cxf-aegis/baeldung.xml
apache-fop/src/test/resources/input.xml
apache-fop/src/test/resources/output_herold.pdf
apache-fop/src/test/resources/output_html2fo.pdf
apache-fop/src/test/resources/output_jtidy.pdf

File diff suppressed because it is too large Load Diff

View File

@@ -12,10 +12,16 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value-annotations</artifactId>
<version>${auto-value.version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.google.auto.value</groupId> <groupId>com.google.auto.value</groupId>
<artifactId>auto-value</artifactId> <artifactId>auto-value</artifactId>
<version>${auto-value.version}</version> <version>${auto-value.version}</version>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.auto.factory</groupId> <groupId>com.google.auto.factory</groupId>
@@ -43,9 +49,9 @@
</dependencies> </dependencies>
<properties> <properties>
<auto-value.version>1.3</auto-value.version> <auto-value.version>1.6.6</auto-value.version>
<auto-factory.version>1.0-beta5</auto-factory.version> <auto-factory.version>1.0-beta6</auto-factory.version>
<auto-service.version>1.0-rc5</auto-service.version> <auto-service.version>1.0-rc6</auto-service.version>
<guice.version>4.2.0</guice.version> <guice.version>4.2.0</guice.version>
</properties> </properties>

View File

@@ -0,0 +1,38 @@
package com.baeldung.autovalue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class Person {
public abstract String name();
public abstract List<String> favoriteMovies();
public static Builder builder() {
return new AutoValue_Person.Builder();
}
@AutoValue.Builder
public static abstract class Builder {
public abstract Builder name(String value);
public abstract Builder favoriteMovies(List<String> value);
abstract List<String> favoriteMovies();
abstract Person autoBuild();
public Person build() {
List<String> favoriteMovies = favoriteMovies();
List<String> copy = Collections.unmodifiableList(new ArrayList<>(favoriteMovies));
favoriteMovies(copy);
return autoBuild();
}
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.autovalue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
/**
* Unit Test which verifies that the {@link Person} value object creates defensive copies of its favoriteMovies list.
*/
public class PersonUnitTest {
@Test
public void givenNewPerson_whenModifyOriginalList_thenValueObjectIsNotAlsoModified() {
// GIVEN new Person
List<String> originalFavoriteMoviesList = new ArrayList<String>();
originalFavoriteMoviesList.add("Training Day");
originalFavoriteMoviesList.add("Fast and the Furious");
Person person = Person.builder()
.name("Dan")
.favoriteMovies(originalFavoriteMoviesList)
.build();
// WHEN modify original list
originalFavoriteMoviesList.add("Friday");
// THEN Person remains unaffected
assertFalse(person.favoriteMovies()
.contains("Friday"));
assertEquals(2, person.favoriteMovies()
.size());
}
}

View File

@@ -5,4 +5,6 @@ This module contains articles about Groovy core collections
## Relevant articles: ## Relevant articles:
- [Maps in Groovy](https://www.baeldung.com/groovy-maps) - [Maps in Groovy](https://www.baeldung.com/groovy-maps)
- [Finding Elements in Collections in Groovy](https://www.baeldung.com/groovy-collections-find-elements)
- [Lists in Groovy](https://www.baeldung.com/groovy-lists)
- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating)

View File

@@ -1,11 +1,11 @@
package com.baeldung.lists package com.baeldung.find
import com.baeldung.Person import com.baeldung.find.Person
import org.junit.Test import org.junit.Test
import static org.junit.Assert.* import static org.junit.Assert.*
class ListUnitTest { class ListFindUnitTest {
private final personList = [ private final personList = [
new Person("Regina", "Fitzpatrick", 25), new Person("Regina", "Fitzpatrick", 25),

View File

@@ -1,11 +1,11 @@
package com.baeldung.map package com.baeldung.find
import com.baeldung.Person import com.baeldung.find.Person
import org.junit.Test import org.junit.Test
import static org.junit.Assert.* import static org.junit.Assert.*
class MapUnitTest { class MapFindUnitTest {
private final personMap = [ private final personMap = [
Regina : new Person("Regina", "Fitzpatrick", 25), Regina : new Person("Regina", "Fitzpatrick", 25),
@@ -13,84 +13,6 @@ class MapUnitTest {
Lucian : new Person("Lucian", "Walter", 30) Lucian : new Person("Lucian", "Walter", 30)
] ]
@Test
void whenUsingEach_thenMapIsIterated() {
def map = [
'FF0000' : 'Red',
'00FF00' : 'Lime',
'0000FF' : 'Blue',
'FFFF00' : 'Yellow'
]
map.each { println "Hex Code: $it.key = Color Name: $it.value" }
}
@Test
void whenUsingEachWithEntry_thenMapIsIterated() {
def map = [
'E6E6FA' : 'Lavender',
'D8BFD8' : 'Thistle',
'DDA0DD' : 'Plum',
]
map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" }
}
@Test
void whenUsingEachWithKeyAndValue_thenMapIsIterated() {
def map = [
'000000' : 'Black',
'FFFFFF' : 'White',
'808080' : 'Gray'
]
map.each { key, val ->
println "Hex Code: $key = Color Name $val"
}
}
@Test
void whenUsingEachWithIndexAndEntry_thenMapIsIterated() {
def map = [
'800080' : 'Purple',
'4B0082' : 'Indigo',
'6A5ACD' : 'Slate Blue'
]
map.eachWithIndex { entry, index ->
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
println "$indent Hex Code: $entry.key = Color Name: $entry.value"
}
}
@Test
void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() {
def map = [
'FFA07A' : 'Light Salmon',
'FF7F50' : 'Coral',
'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"
}
}
@Test
void whenUsingForLoop_thenMapIsIterated() {
def map = [
'2E8B57' : 'Seagreen',
'228B22' : 'Forest Green',
'008000' : 'Green'
]
for (entry in map) {
println "Hex Code: $entry.key = Color Name: $entry.value"
}
}
@Test @Test
void whenMapContainsKeyElement_thenCheckReturnsTrue() { void whenMapContainsKeyElement_thenCheckReturnsTrue() {
def map = [a: 'd', b: 'e', c: 'f'] def map = [a: 'd', b: 'e', c: 'f']

View File

@@ -1,4 +1,4 @@
package com.baeldung package com.baeldung.find
class Person { class Person {
private String firstname private String firstname

View File

@@ -1,10 +1,10 @@
package com.baeldung.set package com.baeldung.find
import org.junit.Test import org.junit.Test
import static org.junit.Assert.assertTrue import static org.junit.Assert.assertTrue
class SetUnitTest { class SetFindUnitTest {
@Test @Test
void whenSetContainsElement_thenCheckReturnsTrue() { void whenSetContainsElement_thenCheckReturnsTrue() {

View File

@@ -0,0 +1,87 @@
package com.baeldung.iteratemap
import com.baeldung.find.Person
import org.junit.Test
import static org.junit.Assert.*
class IterateMapUnitTest {
@Test
void whenUsingEach_thenMapIsIterated() {
def map = [
'FF0000' : 'Red',
'00FF00' : 'Lime',
'0000FF' : 'Blue',
'FFFF00' : 'Yellow'
]
map.each { println "Hex Code: $it.key = Color Name: $it.value" }
}
@Test
void whenUsingEachWithEntry_thenMapIsIterated() {
def map = [
'E6E6FA' : 'Lavender',
'D8BFD8' : 'Thistle',
'DDA0DD' : 'Plum',
]
map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" }
}
@Test
void whenUsingEachWithKeyAndValue_thenMapIsIterated() {
def map = [
'000000' : 'Black',
'FFFFFF' : 'White',
'808080' : 'Gray'
]
map.each { key, val ->
println "Hex Code: $key = Color Name $val"
}
}
@Test
void whenUsingEachWithIndexAndEntry_thenMapIsIterated() {
def map = [
'800080' : 'Purple',
'4B0082' : 'Indigo',
'6A5ACD' : 'Slate Blue'
]
map.eachWithIndex { entry, index ->
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
println "$indent Hex Code: $entry.key = Color Name: $entry.value"
}
}
@Test
void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() {
def map = [
'FFA07A' : 'Light Salmon',
'FF7F50' : 'Coral',
'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"
}
}
@Test
void whenUsingForLoop_thenMapIsIterated() {
def map = [
'2E8B57' : 'Seagreen',
'228B22' : 'Forest Green',
'008000' : 'Green'
]
for (entry in map) {
println "Hex Code: $entry.key = Color Name: $entry.value"
}
}
}

View File

@@ -1,9 +1,9 @@
package com.baeldung.groovy.lists package com.baeldung.lists
import static groovy.test.GroovyAssert.* import static groovy.test.GroovyAssert.*
import org.junit.Test import org.junit.Test
class ListTest{ class ListUnitTest {
@Test @Test
void testCreateList() { void testCreateList() {

View File

@@ -1,4 +1,4 @@
package com.baeldung.map; package com.baeldung.maps;
import static groovy.test.GroovyAssert.* import static groovy.test.GroovyAssert.*
import org.junit.Test import org.junit.Test

View File

@@ -8,11 +8,8 @@ This module contains articles about core Groovy concepts
- [Working with JSON in Groovy](https://www.baeldung.com/groovy-json) - [Working with JSON in Groovy](https://www.baeldung.com/groovy-json)
- [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read) - [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read)
- [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings) - [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings)
- [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) - [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits)
- [Closures in Groovy](https://www.baeldung.com/groovy-closures) - [Closures in Groovy](https://www.baeldung.com/groovy-closures)
- [Finding Elements in Collections in Groovy](https://www.baeldung.com/groovy-collections-find-elements)
- [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) - [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) - [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
- [[More -->]](/core-groovy-2) - [[More -->]](/core-groovy-2)

View File

@@ -1,148 +0,0 @@
package com.baeldung.groovy.map;
import static groovy.test.GroovyAssert.*
import org.junit.Test
class MapTest{
@Test
void createMap() {
def emptyMap = [:]
assertNotNull(emptyMap)
assertTrue(emptyMap instanceof java.util.LinkedHashMap)
def map = [name:"Jerry", age: 42, city: "New York"]
assertTrue(map.size() == 3)
}
@Test
void addItemsToMap() {
def map = [name:"Jerry"]
map["age"] = 42
map.city = "New York"
def hobbyLiteral = "hobby"
def hobbyMap = [(hobbyLiteral): "Singing"]
map.putAll(hobbyMap)
assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"])
assertTrue(hobbyMap.hobby == "Singing")
assertTrue(hobbyMap[hobbyLiteral] == "Singing")
map.plus([1:20]) // returns new map
map << [2:30]
}
@Test
void getItemsFromMap() {
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
assertTrue(map["name"] == "Jerry")
assertTrue(map.name == "Jerry")
def propertyAge = "age"
assertTrue(map[propertyAge] == 42)
}
@Test
void removeItemsFromMap() {
def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49]
def minusMap = map.minus([2:42, 4:34]);
assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49])
minusMap.removeAll{it -> it.key instanceof String}
assertTrue( minusMap == [ 1:20, 6:39, 7:49])
minusMap.retainAll{it -> it.value %2 == 0}
assertTrue( minusMap == [1:20])
}
@Test
void iteratingOnMaps(){
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
map.each{ entry -> println "$entry.key: $entry.value" }
map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" }
map.eachWithIndex{ key, value, i -> println "$i $key: $value" }
}
@Test
void filteringAndSearchingMaps(){
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
assertTrue(map.find{ it.value == "New York"}.key == "city")
assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"])
map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")}
assertTrue(map.every{it -> it.value instanceof String} == false)
assertTrue(map.any{it -> it.value instanceof String} == true)
}
@Test
void collect(){
def map = [1: [name:"Jerry", age: 42, city: "New York"],
2: [name:"Long", age: 25, city: "New York"],
3: [name:"Dustin", age: 29, city: "New York"],
4: [name:"Dustin", age: 34, city: "New York"]]
def names = map.collect{entry -> entry.value.name} // returns only list
assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"])
def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name}
assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set)
def idNames = map.collectEntries{key, value -> [key, value.name]}
assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"])
def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name}
assertTrue(below30Names == ["Long", "Dustin"])
}
@Test
void group(){
def map = [1:20, 2: 40, 3: 11, 4: 93]
def subMap = map.groupBy{it.value % 2}
println subMap
assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]])
def keySubMap = map.subMap([1, 2])
assertTrue(keySubMap == [1:20, 2:40])
}
@Test
void sorting(){
def map = [ab:20, a: 40, cb: 11, ba: 93]
def naturallyOrderedMap = map.sort()
assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap)
def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator)
assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap)
def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value })
assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap)
}
}

View File

@@ -0,0 +1,6 @@
## Core Java 9 streams
This module contains articles about Java 9 streams
### Relevant Articles:
- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach)

View File

@@ -0,0 +1,31 @@
<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-9-streams</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-9-streams</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>
</dependencies>
<build>
<finalName>core-java-9-streams</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
</properties>
</project>

View File

@@ -1,4 +1,4 @@
package com.baeldung.breakforeach; package com.baeldung.streams.breakforeach;
import java.util.Spliterator; import java.util.Spliterator;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;

View File

@@ -1,4 +1,4 @@
package com.baeldung.breakforeach; package com.baeldung.streams.breakforeach;
import java.util.Spliterator; import java.util.Spliterator;
import java.util.Spliterators; import java.util.Spliterators;

View File

@@ -1,4 +1,4 @@
package com.baeldung.breakforeach; package com.baeldung.streams.breakforeach;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Stream; import java.util.stream.Stream;

View File

@@ -1,4 +1,4 @@
package com.baeldung.breakforeach; package com.baeldung.streams.breakforeach;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;

View File

@@ -1,4 +1,4 @@
package com.baeldung.breakforeach; package com.baeldung.streams.breakforeach;
import org.junit.Test; import org.junit.Test;

View File

@@ -0,0 +1,15 @@
## Java Date/time computations Cookbooks and Examples
This module contains articles about date and time computations in Java.
### Relevant Articles:
- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference)
- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time)
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day)
- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar)
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
- [Introduction to Joda-Time](http://www.baeldung.com/joda-time)

View File

@@ -0,0 +1,71 @@
<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-datetime-computations</artifactId>
<version>${project.parent.version}</version>
<name>core-java-datetime-computations</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>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</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>
<dependency>
<groupId>com.darwinsys</groupId>
<artifactId>hirondelle-date4j</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-datetime-computations</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>
<joda-time.version>2.10</joda-time.version>
<!-- 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>

View File

@@ -1,28 +1,28 @@
package com.baeldung.datetime; package com.baeldung.datetime;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
public class DateExtractYearMonthDayIntegerValues { public class DateExtractYearMonthDayIntegerValues {
int getYear(Date date) { int getYear(Date date) {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
return calendar.get(Calendar.YEAR); return calendar.get(Calendar.YEAR);
} }
int getMonth(Date date) { int getMonth(Date date) {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
return calendar.get(Calendar.MONTH); return calendar.get(Calendar.MONTH);
} }
int getDay(Date date) { int getDay(Date date) {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH); return calendar.get(Calendar.DAY_OF_MONTH);
} }
} }

View File

@@ -1,18 +1,18 @@
package com.baeldung.datetime; package com.baeldung.datetime;
import java.time.LocalDate; import java.time.LocalDate;
public class LocalDateExtractYearMonthDayIntegerValues { public class LocalDateExtractYearMonthDayIntegerValues {
int getYear(LocalDate localDate) { int getYear(LocalDate localDate) {
return localDate.getYear(); return localDate.getYear();
} }
int getMonth(LocalDate localDate) { int getMonth(LocalDate localDate) {
return localDate.getMonthValue(); return localDate.getMonthValue();
} }
int getDay(LocalDate localDate) { int getDay(LocalDate localDate) {
return localDate.getDayOfMonth(); return localDate.getDayOfMonth();
} }
} }

View File

@@ -1,18 +1,18 @@
package com.baeldung.datetime; package com.baeldung.datetime;
import java.time.LocalDateTime; import java.time.LocalDateTime;
public class LocalDateTimeExtractYearMonthDayIntegerValues { public class LocalDateTimeExtractYearMonthDayIntegerValues {
int getYear(LocalDateTime localDateTime) { int getYear(LocalDateTime localDateTime) {
return localDateTime.getYear(); return localDateTime.getYear();
} }
int getMonth(LocalDateTime localDateTime) { int getMonth(LocalDateTime localDateTime) {
return localDateTime.getMonthValue(); return localDateTime.getMonthValue();
} }
int getDay(LocalDateTime localDateTime) { int getDay(LocalDateTime localDateTime) {
return localDateTime.getDayOfMonth(); return localDateTime.getDayOfMonth();
} }
} }

View File

@@ -1,18 +1,18 @@
package com.baeldung.datetime; package com.baeldung.datetime;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
public class OffsetDateTimeExtractYearMonthDayIntegerValues { public class OffsetDateTimeExtractYearMonthDayIntegerValues {
int getYear(OffsetDateTime offsetDateTime) { int getYear(OffsetDateTime offsetDateTime) {
return offsetDateTime.getYear(); return offsetDateTime.getYear();
} }
int getMonth(OffsetDateTime offsetDateTime) { int getMonth(OffsetDateTime offsetDateTime) {
return offsetDateTime.getMonthValue(); return offsetDateTime.getMonthValue();
} }
int getDay(OffsetDateTime offsetDateTime) { int getDay(OffsetDateTime offsetDateTime) {
return offsetDateTime.getDayOfMonth(); return offsetDateTime.getDayOfMonth();
} }
} }

View File

@@ -1,18 +1,18 @@
package com.baeldung.datetime; package com.baeldung.datetime;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
public class ZonedDateTimeExtractYearMonthDayIntegerValues { public class ZonedDateTimeExtractYearMonthDayIntegerValues {
int getYear(ZonedDateTime zonedDateTime) { int getYear(ZonedDateTime zonedDateTime) {
return zonedDateTime.getYear(); return zonedDateTime.getYear();
} }
int getMonth(ZonedDateTime zonedDateTime) { int getMonth(ZonedDateTime zonedDateTime) {
return zonedDateTime.getMonthValue(); return zonedDateTime.getMonthValue();
} }
int getDay(ZonedDateTime zonedDateTime) { int getDay(ZonedDateTime zonedDateTime) {
return zonedDateTime.getDayOfMonth(); return zonedDateTime.getDayOfMonth();
} }
} }

View File

@@ -1,45 +1,45 @@
package com.baeldung.datetime; package com.baeldung.datetime;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
public class DateExtractYearMonthDayIntegerValuesUnitTest { public class DateExtractYearMonthDayIntegerValuesUnitTest {
DateExtractYearMonthDayIntegerValues extractYearMonthDateIntegerValues = new DateExtractYearMonthDayIntegerValues(); DateExtractYearMonthDayIntegerValues extractYearMonthDateIntegerValues = new DateExtractYearMonthDayIntegerValues();
Date date; Date date;
@Before @Before
public void setup() throws ParseException public void setup() throws ParseException
{ {
date=new SimpleDateFormat("dd-MM-yyyy").parse("01-03-2018"); date=new SimpleDateFormat("dd-MM-yyyy").parse("01-03-2018");
} }
@Test @Test
public void whenGetYear_thenCorrectYear() public void whenGetYear_thenCorrectYear()
{ {
int actualYear=extractYearMonthDateIntegerValues.getYear(date); int actualYear=extractYearMonthDateIntegerValues.getYear(date);
assertThat(actualYear,is(2018)); assertThat(actualYear,is(2018));
} }
@Test @Test
public void whenGetMonth_thenCorrectMonth() public void whenGetMonth_thenCorrectMonth()
{ {
int actualMonth=extractYearMonthDateIntegerValues.getMonth(date); int actualMonth=extractYearMonthDateIntegerValues.getMonth(date);
assertThat(actualMonth,is(02)); assertThat(actualMonth,is(02));
} }
@Test @Test
public void whenGetDay_thenCorrectDay() public void whenGetDay_thenCorrectDay()
{ {
int actualDayOfMonth=extractYearMonthDateIntegerValues.getDay(date); int actualDayOfMonth=extractYearMonthDateIntegerValues.getDay(date);
assertThat(actualDayOfMonth,is(01)); assertThat(actualDayOfMonth,is(01));
} }
} }

View File

@@ -1,36 +1,36 @@
package com.baeldung.datetime; package com.baeldung.datetime;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.time.LocalDate; import java.time.LocalDate;
import org.junit.Test; import org.junit.Test;
public class LocalDateExtractYearMonthDayIntegerValuesUnitTest { public class LocalDateExtractYearMonthDayIntegerValuesUnitTest {
LocalDateExtractYearMonthDayIntegerValues localDateExtractYearMonthDayIntegerValues=new LocalDateExtractYearMonthDayIntegerValues(); LocalDateExtractYearMonthDayIntegerValues localDateExtractYearMonthDayIntegerValues=new LocalDateExtractYearMonthDayIntegerValues();
LocalDate localDate=LocalDate.parse("2007-12-03"); LocalDate localDate=LocalDate.parse("2007-12-03");
@Test @Test
public void whenGetYear_thenCorrectYear() public void whenGetYear_thenCorrectYear()
{ {
int actualYear=localDateExtractYearMonthDayIntegerValues.getYear(localDate); int actualYear=localDateExtractYearMonthDayIntegerValues.getYear(localDate);
assertThat(actualYear,is(2007)); assertThat(actualYear,is(2007));
} }
@Test @Test
public void whenGetMonth_thenCorrectMonth() public void whenGetMonth_thenCorrectMonth()
{ {
int actualMonth=localDateExtractYearMonthDayIntegerValues.getMonth(localDate); int actualMonth=localDateExtractYearMonthDayIntegerValues.getMonth(localDate);
assertThat(actualMonth,is(12)); assertThat(actualMonth,is(12));
} }
@Test @Test
public void whenGetDay_thenCorrectDay() public void whenGetDay_thenCorrectDay()
{ {
int actualDayOfMonth=localDateExtractYearMonthDayIntegerValues.getDay(localDate); int actualDayOfMonth=localDateExtractYearMonthDayIntegerValues.getDay(localDate);
assertThat(actualDayOfMonth,is(03)); assertThat(actualDayOfMonth,is(03));
} }
} }

View File

@@ -1,36 +1,36 @@
package com.baeldung.datetime; package com.baeldung.datetime;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import org.junit.Test; import org.junit.Test;
public class LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest { public class LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest {
LocalDateTimeExtractYearMonthDayIntegerValues localDateTimeExtractYearMonthDayIntegerValues = new LocalDateTimeExtractYearMonthDayIntegerValues(); LocalDateTimeExtractYearMonthDayIntegerValues localDateTimeExtractYearMonthDayIntegerValues = new LocalDateTimeExtractYearMonthDayIntegerValues();
LocalDateTime localDateTime=LocalDateTime.parse("2007-12-03T10:15:30"); LocalDateTime localDateTime=LocalDateTime.parse("2007-12-03T10:15:30");
@Test @Test
public void whenGetYear_thenCorrectYear() public void whenGetYear_thenCorrectYear()
{ {
int actualYear=localDateTimeExtractYearMonthDayIntegerValues.getYear(localDateTime); int actualYear=localDateTimeExtractYearMonthDayIntegerValues.getYear(localDateTime);
assertThat(actualYear,is(2007)); assertThat(actualYear,is(2007));
} }
@Test @Test
public void whenGetMonth_thenCorrectMonth() public void whenGetMonth_thenCorrectMonth()
{ {
int actualMonth=localDateTimeExtractYearMonthDayIntegerValues.getMonth(localDateTime); int actualMonth=localDateTimeExtractYearMonthDayIntegerValues.getMonth(localDateTime);
assertThat(actualMonth,is(12)); assertThat(actualMonth,is(12));
} }
@Test @Test
public void whenGetDay_thenCorrectDay() public void whenGetDay_thenCorrectDay()
{ {
int actualDayOfMonth=localDateTimeExtractYearMonthDayIntegerValues.getDay(localDateTime); int actualDayOfMonth=localDateTimeExtractYearMonthDayIntegerValues.getDay(localDateTime);
assertThat(actualDayOfMonth,is(03)); assertThat(actualDayOfMonth,is(03));
} }
} }

View File

@@ -1,36 +1,36 @@
package com.baeldung.datetime; package com.baeldung.datetime;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import org.junit.Test; import org.junit.Test;
public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest { public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest {
OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues(); OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues();
OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00"); OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00");
@Test @Test
public void whenGetYear_thenCorrectYear() public void whenGetYear_thenCorrectYear()
{ {
int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime); int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime);
assertThat(actualYear,is(2007)); assertThat(actualYear,is(2007));
} }
@Test @Test
public void whenGetMonth_thenCorrectMonth() public void whenGetMonth_thenCorrectMonth()
{ {
int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime); int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime);
assertThat(actualMonth,is(12)); assertThat(actualMonth,is(12));
} }
@Test @Test
public void whenGetDay_thenCorrectDay() public void whenGetDay_thenCorrectDay()
{ {
int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime); int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime);
assertThat(actualDayOfMonth,is(03)); assertThat(actualDayOfMonth,is(03));
} }
} }

View File

@@ -1,36 +1,36 @@
package com.baeldung.datetime; package com.baeldung.datetime;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import org.junit.Test; import org.junit.Test;
public class ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest { public class ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest {
ZonedDateTimeExtractYearMonthDayIntegerValues zonedDateTimeExtractYearMonthDayIntegerValues = new ZonedDateTimeExtractYearMonthDayIntegerValues(); ZonedDateTimeExtractYearMonthDayIntegerValues zonedDateTimeExtractYearMonthDayIntegerValues = new ZonedDateTimeExtractYearMonthDayIntegerValues();
ZonedDateTime zonedDateTime=ZonedDateTime.parse("2007-12-03T10:15:30+01:00"); ZonedDateTime zonedDateTime=ZonedDateTime.parse("2007-12-03T10:15:30+01:00");
@Test @Test
public void whenGetYear_thenCorrectYear() public void whenGetYear_thenCorrectYear()
{ {
int actualYear=zonedDateTimeExtractYearMonthDayIntegerValues.getYear(zonedDateTime); int actualYear=zonedDateTimeExtractYearMonthDayIntegerValues.getYear(zonedDateTime);
assertThat(actualYear,is(2007)); assertThat(actualYear,is(2007));
} }
@Test @Test
public void whenGetMonth_thenCorrectMonth() public void whenGetMonth_thenCorrectMonth()
{ {
int actualMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getMonth(zonedDateTime); int actualMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getMonth(zonedDateTime);
assertThat(actualMonth,is(12)); assertThat(actualMonth,is(12));
} }
@Test @Test
public void whenGetDay_thenCorrectDay() public void whenGetDay_thenCorrectDay()
{ {
int actualDayOfMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getDay(zonedDateTime); int actualDayOfMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getDay(zonedDateTime);
assertThat(actualDayOfMonth,is(03)); assertThat(actualDayOfMonth,is(03));
} }
} }

View File

@@ -0,0 +1,15 @@
## Java 8+ Date and Time API
This module contains articles about the Date and Time API introduced with Java 8.
### Relevant Articles:
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api)
- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster)
- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset)
- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
- [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates)

View File

@@ -1,17 +1,16 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <artifactId>core-java-datetime-java8</artifactId>
<artifactId>java-dates</artifactId> <version>${project.parent.version}</version>
<version>0.1.0-SNAPSHOT</version> <name>core-java-datetime-java8</name>
<name>java-dates</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId> <artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath> <relativePath>../../parent-java</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@@ -21,11 +20,10 @@
<version>${commons-lang3.version}</version> <version>${commons-lang3.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>log4j</groupId> <groupId>joda-time</groupId>
<artifactId>log4j</artifactId> <artifactId>joda-time</artifactId>
<version>${log4j.version}</version> <version>${joda-time.version}</version>
</dependency> </dependency>
<!-- test scoped -->
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>
@@ -33,20 +31,15 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>joda-time</groupId> <groupId>log4j</groupId>
<artifactId>joda-time</artifactId> <artifactId>log4j</artifactId>
<version>${joda-time.version}</version> <version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>com.darwinsys</groupId>
<artifactId>hirondelle-date4j</artifactId>
<version>RELEASE</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<finalName>java-dates</finalName> <finalName>core-java-datetime-java8</finalName>
<resources> <resources>
<resource> <resource>
<directory>src/main/resources</directory> <directory>src/main/resources</directory>
@@ -68,10 +61,10 @@
</build> </build>
<properties> <properties>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<joda-time.version>2.10</joda-time.version> <joda-time.version>2.10</joda-time.version>
<!-- testing --> <!-- testing -->
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
</properties> </properties>
</project> </project>

View File

@@ -1,72 +1,72 @@
package com.baeldung.datetime; package com.baeldung.datetime;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.Instant; import java.time.Instant;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.TimeZone; import java.util.TimeZone;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
public class UseTimeZoneUnitTest { public class UseTimeZoneUnitTest {
/* https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */ /* https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */
String timeZone = "Asia/Singapore"; String timeZone = "Asia/Singapore";
private static final String PATTERN = "E yyyy-MM-dd HH:mm:ss a"; private static final String PATTERN = "E yyyy-MM-dd HH:mm:ss a";
@Test @Test
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava7_ThenTimeZoneIsSetSuccessfully() { public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava7_ThenTimeZoneIsSetSuccessfully() {
Date nowUtc = new Date(); Date nowUtc = new Date();
TimeZone asiaSingapore = TimeZone.getTimeZone(timeZone); TimeZone asiaSingapore = TimeZone.getTimeZone(timeZone);
Calendar nowAsiaSingapore = Calendar.getInstance(asiaSingapore); Calendar nowAsiaSingapore = Calendar.getInstance(asiaSingapore);
nowAsiaSingapore.setTime(nowUtc); nowAsiaSingapore.setTime(nowUtc);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
System.out.println(String.format("Java7: Time now in '%s' is '%s'", nowAsiaSingapore.getTimeZone() System.out.println(String.format("Java7: Time now in '%s' is '%s'", nowAsiaSingapore.getTimeZone()
.getID(), simpleDateFormat.format(nowAsiaSingapore.getTime()))); .getID(), simpleDateFormat.format(nowAsiaSingapore.getTime())));
Assert.assertEquals(nowUtc.toInstant().getEpochSecond(), nowAsiaSingapore.toInstant().getEpochSecond()); Assert.assertEquals(nowUtc.toInstant().getEpochSecond(), nowAsiaSingapore.toInstant().getEpochSecond());
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getTimeZone()); Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getTimeZone());
} }
@Test @Test
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava8_ThenTimeZoneIsSetSuccessfully() { public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava8_ThenTimeZoneIsSetSuccessfully() {
Instant nowUtc = Instant.now(); Instant nowUtc = Instant.now();
ZoneId asiaSingapore = ZoneId.of(timeZone); ZoneId asiaSingapore = ZoneId.of(timeZone);
ZonedDateTime nowAsiaSingapore = ZonedDateTime.ofInstant(nowUtc, asiaSingapore); ZonedDateTime nowAsiaSingapore = ZonedDateTime.ofInstant(nowUtc, asiaSingapore);
System.out.println(String.format("Java8: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(), System.out.println(String.format("Java8: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(),
nowAsiaSingapore.format(DateTimeFormatter.ofPattern(PATTERN)))); nowAsiaSingapore.format(DateTimeFormatter.ofPattern(PATTERN))));
Assert.assertEquals(nowUtc.getEpochSecond(), nowAsiaSingapore.toEpochSecond()); Assert.assertEquals(nowUtc.getEpochSecond(), nowAsiaSingapore.toEpochSecond());
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone()); Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone());
} }
@Test @Test
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJodaTime_ThenTimeZoneIsSetSuccessfully() { public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJodaTime_ThenTimeZoneIsSetSuccessfully() {
org.joda.time.Instant nowUtc = org.joda.time.Instant.now(); org.joda.time.Instant nowUtc = org.joda.time.Instant.now();
DateTimeZone asiaSingapore = DateTimeZone.forID(timeZone); DateTimeZone asiaSingapore = DateTimeZone.forID(timeZone);
DateTime nowAsiaSingapore = nowUtc.toDateTime(asiaSingapore); DateTime nowAsiaSingapore = nowUtc.toDateTime(asiaSingapore);
System.out.println(String.format("Joda-time: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(), System.out.println(String.format("Joda-time: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(),
nowAsiaSingapore.toString(PATTERN))); nowAsiaSingapore.toString(PATTERN)));
Assert.assertEquals(nowUtc.toInstant().getMillis(), nowAsiaSingapore.toInstant().getMillis()); Assert.assertEquals(nowUtc.toInstant().getMillis(), nowAsiaSingapore.toInstant().getMillis());
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone()); Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone());
} }
} }

View File

@@ -0,0 +1,96 @@
package com.baeldung.scanner;
import lombok.extern.log4j.Log4j;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Scanner;
@Log4j
public class HasNextVsHasNextLineDemo {
private static final String LINE = "----------------------------";
private static final String END_LINE = "--------OUTPUT--END---------\n";
private static final String INPUT = new StringBuilder()
.append("magic\tproject\n")
.append(" database: oracle\n")
.append("dependencies:\n")
.append("spring:foo:bar\n")
.append("\n").toString();
private static void hasNextBasic() {
printHeader("hasNext() Basic");
Scanner scanner = new Scanner(INPUT);
while (scanner.hasNext()) {
log.info(scanner.next());
}
log.info(END_LINE);
scanner.close();
}
private static void hasNextWithDelimiter() {
printHeader("hasNext() with delimiter");
Scanner scanner = new Scanner(INPUT);
while (scanner.hasNext()) {
String token = scanner.next();
if ("dependencies:".equals(token)) {
scanner.useDelimiter(":");
}
log.info(token);
}
log.info(END_LINE);
scanner.close();
}
private static void hasNextWithDelimiterFixed() {
printHeader("hasNext() with delimiter FIX");
Scanner scanner = new Scanner(INPUT);
while (scanner.hasNext()) {
String token = scanner.next();
if ("dependencies:".equals(token)) {
scanner.useDelimiter(":|\\s+");
}
log.info(token);
}
log.info(END_LINE);
scanner.close();
}
private static void addLineNumber() {
printHeader("add line number by hasNextLine() ");
Scanner scanner = new Scanner(INPUT);
int i = 0;
while (scanner.hasNextLine()) {
log.info(String.format("%d|%s", ++i, scanner.nextLine()));
}
log.info(END_LINE);
scanner.close();
}
private static void printHeader(String title) {
log.info(LINE);
log.info(title);
log.info(LINE);
}
public static void main(String[] args) throws IOException {
setLogger();
hasNextBasic();
hasNextWithDelimiter();
hasNextWithDelimiterFixed();
addLineNumber();
}
//overwrite the logger config
private static void setLogger() throws IOException {
InputStream is = HasNextVsHasNextLineDemo.class.getResourceAsStream("/scanner/log4j.properties");
Properties props = new Properties();
props.load(is);
LogManager.resetConfiguration();
PropertyConfigurator.configure(props);
}
}

View File

@@ -0,0 +1,4 @@
log4j.rootLogger=INFO, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[DEMO]%m%n

View File

@@ -50,6 +50,12 @@
<artifactId>jmimemagic</artifactId> <artifactId>jmimemagic</artifactId>
<version>${jmime-magic.version}</version> <version>${jmime-magic.version}</version>
</dependency> </dependency>
<!-- Context Libraries -->
<dependency>
<groupId>com.sun.messaging.mq</groupId>
<artifactId>fscontext</artifactId>
<version>${fscontext.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@@ -154,7 +160,7 @@
<tika.version>1.18</tika.version> <tika.version>1.18</tika.version>
<jmime-magic.version>0.1.5</jmime-magic.version> <jmime-magic.version>0.1.5</jmime-magic.version>
<maven-jar-plugin.version>3.1.0</maven-jar-plugin.version> <maven-jar-plugin.version>3.1.0</maven-jar-plugin.version>
<fscontext.version>4.4.2</fscontext.version>
</properties> </properties>
</project> </project>

View File

@@ -1,8 +1,12 @@
=========
## Core Java JVM Cookbooks and Examples ## Core Java JVM Cookbooks and Examples
This module contains articles about working with the Java Virtual Machine (JVM).
### Relevant Articles: ### Relevant Articles:
- [Method Inlining in the JVM](https://www.baeldung.com/jvm-method-inlining) - [Method Inlining in the JVM](https://www.baeldung.com/jvm-method-inlining)
- [JVM Log Forging](https://www.baeldung.com/jvm-log-forging)
- [Guide to Java Instrumentation](https://www.baeldung.com/java-instrumentation)
- [Class Loaders in Java](https://www.baeldung.com/java-classloaders)
- [A Guide to System.exit()](https://www.baeldung.com/java-system-exit) - [A Guide to System.exit()](https://www.baeldung.com/java-system-exit)
- [Guide to System.gc()](https://www.baeldung.com/java-system-gc) - [Guide to System.gc()](https://www.baeldung.com/java-system-gc)

View File

@@ -13,4 +13,49 @@
<relativePath>../../</relativePath> <relativePath>../../</relativePath>
</parent> </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>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javaassist.version}</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>${esapi.version}</version>
</dependency>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>${sun.tools.version}</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
</dependencies>
<properties>
<assertj.version>3.6.1</assertj.version>
<!-- instrumentation -->
<javaassist.version>3.21.0-GA</javaassist.version>
<esapi.version>2.1.0.1</esapi.version>
<sun.tools.version>1.8.0</sun.tools.version>
</properties>
</project> </project>

View File

@@ -3,9 +3,14 @@
This module contains articles about working with the operating system (OS) in Java This module contains articles about working with the operating system (OS) in Java
### Relevant Articles: ### Relevant Articles:
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api) - [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.Process API](https://www.baeldung.com/java-process-api)
- [Guide to java.lang.ProcessBuilder API](https://www.baeldung.com/java-lang-processbuilder-api) - [Guide to java.lang.ProcessBuilder API](https://www.baeldung.com/java-lang-processbuilder-api)
- [Get the Current Working Directory in Java](https://www.baeldung.com/java-current-directory) - [Get the Current Working Directory in Java](https://www.baeldung.com/java-current-directory)
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
This module uses Java 9, so make sure to have the JDK 9 installed to run it. This module uses Java 9, so make sure to have the JDK 9 installed to run it.

View File

@@ -42,6 +42,16 @@
<version>${assertj.version}</version> <version>${assertj.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@@ -77,5 +87,7 @@
<maven.compiler.source>1.9</maven.compiler.source> <maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target> <maven.compiler.target>1.9</maven.compiler.target>
<guava.version>25.1-jre</guava.version> <guava.version>25.1-jre</guava.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
</properties> </properties>
</project> </project>

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