Merge remote-tracking branch 'upstream/master'

This commit is contained in:
abialas 2017-11-24 20:37:40 +01:00
commit 3bbe5afbde
120 changed files with 2636 additions and 66 deletions

View File

@ -109,7 +109,7 @@ cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ?
cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect
cas.authn.jdbc.query[0].user=root
cas.authn.jdbc.query[0].password=
cas.authn.jdbc.query[0].password=root
cas.authn.jdbc.query[0].ddlAuto=none
#cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver
cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver

View File

@ -0,0 +1,16 @@
-- Dumping database structure for test
CREATE DATABASE IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `test`;
-- Dumping structure for table test.users
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(50) DEFAULT NULL,
`password` text DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` (`id`, `email`, `password`) VALUES
(1, 'test@test.com', 'Mellon');
/*!40000 ALTER TABLE `users` ENABLE KEYS */;

View File

@ -30,3 +30,5 @@
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)

View File

@ -0,0 +1,5 @@
package com.baeldung.annotations;
@Deprecated
class ClassWithAnnotation {
}

View File

@ -0,0 +1,9 @@
package com.baeldung.annotations;
class ClassWithDeprecatedMethod {
@Deprecated
static void deprecatedMethod() {
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.annotations;
class ClassWithSafeVarargs<T> {
@SafeVarargs
final void iterateOverVarargs(T... args) {
for (T x : args) {
// do stuff with x
}
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.annotations;
class ClassWithSuppressWarnings {
@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
ClassWithDeprecatedMethod.deprecatedMethod(); // no warning is generated here
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.annotations;
@FunctionalInterface
interface IntConsumer {
void accept(Integer number);
}

View File

@ -0,0 +1,8 @@
package com.baeldung.annotations;
import java.lang.annotation.Repeatable;
@Repeatable(Intervals.class)
@interface Interval {
int hour() default 1;
}

View File

@ -0,0 +1,9 @@
package com.baeldung.annotations;
public class IntervalUsage {
@Interval(hour = 17)
@Interval(hour = 13)
void doPeriodicCleanup() {
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.annotations;
@interface Intervals {
Interval[] value();
}

View File

@ -0,0 +1,11 @@
package com.baeldung.annotations;
import java.lang.annotation.*;
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD})
@interface MyAnnotation {
}

View File

@ -0,0 +1,16 @@
package com.baeldung.annotations;
class MyAnnotationTarget {
// this is OK
@MyAnnotation
String someField;
// @MyAnnotation <- this is invalid usage!
void doSomething() {
// this also works
@MyAnnotation
String localVariable;
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.annotations;
interface MyOperation {
void perform();
}

View File

@ -0,0 +1,9 @@
package com.baeldung.annotations;
class MyOperationImpl implements MyOperation {
@Override
public void perform() {
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.timezonedisplay;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class TimezoneDisplay {
public enum OffsetBase {
GMT, UTC
}
public List<String> getTimeZoneList(OffsetBase base) {
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
LocalDateTime now = LocalDateTime.now();
return availableZoneIds
.stream()
.map(ZoneId::of)
.sorted(new ZoneComparator())
.map(id -> String.format("(%s%s) %s", base, getOffset(now, id), id.getId()))
.collect(Collectors.toList());
}
private String getOffset(LocalDateTime dateTime, ZoneId id) {
return dateTime
.atZone(id)
.getOffset()
.getId()
.replace("Z", "+00:00");
}
private class ZoneComparator implements Comparator<ZoneId> {
@Override
public int compare(ZoneId zoneId1, ZoneId zoneId2) {
LocalDateTime now = LocalDateTime.now();
ZoneOffset offset1 = now
.atZone(zoneId1)
.getOffset();
ZoneOffset offset2 = now
.atZone(zoneId2)
.getOffset();
return offset1.compareTo(offset2);
}
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.timezonedisplay;
import java.util.List;
public class TimezoneDisplayApp {
public static void main(String... args) {
TimezoneDisplay display = new TimezoneDisplay();
System.out.println("Time zones in UTC:");
List<String> utc = display.getTimeZoneList(TimezoneDisplay.OffsetBase.UTC);
utc.forEach(System.out::println);
System.out.println("Time zones in GMT:");
List<String> gmt = display.getTimeZoneList(TimezoneDisplay.OffsetBase.GMT);
gmt.forEach(System.out::println);
}
}

View File

@ -117,3 +117,6 @@
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)

View File

@ -460,7 +460,7 @@
<logback.version>1.1.7</logback.version>
<!-- util -->
<guava.version>22.0</guava.version>
<guava.version>23.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>

View File

@ -0,0 +1,6 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public interface AbstractFactory {
Animal getAnimal(String toyType) ;
Color getColor(String colorType);
}

View File

@ -0,0 +1,18 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class AbstractPatternDriver {
public static void main(String[] args) {
AbstractFactory abstractFactory;
//creating a brown toy dog
abstractFactory = FactoryProvider.getFactory("Toy");
Animal toy = abstractFactory.getAnimal("Dog");
abstractFactory = FactoryProvider.getFactory("Color");
Color color = abstractFactory.getColor("Brown");
String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound();
System.out.println(result);
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public interface Animal {
String getType();
String makeSound();
}

View File

@ -0,0 +1,21 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class AnimalFactory implements AbstractFactory {
@Override
public Animal getAnimal(String animalType) {
if ("Dog".equalsIgnoreCase(animalType)) {
return new Dog();
} else if ("Duck".equalsIgnoreCase(animalType)) {
return new Duck();
}
return null;
}
@Override
public Color getColor(String color) {
throw new UnsupportedOperationException();
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class Brown implements Color {
@Override
public String getColor() {
return "brown";
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public interface Color {
String getColor();
}

View File

@ -0,0 +1,21 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class ColorFactory implements AbstractFactory {
@Override
public Color getColor(String colorType) {
if ("Brown".equalsIgnoreCase(colorType)) {
return new Brown();
} else if ("White".equalsIgnoreCase(colorType)) {
return new White();
}
return null;
}
@Override
public Animal getAnimal(String toyType) {
throw new UnsupportedOperationException();
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class Dog implements Animal {
@Override
public String getType() {
return "Dog";
}
@Override
public String makeSound() {
return "Barks";
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class Duck implements Animal {
@Override
public String getType() {
return "Duck";
}
@Override
public String makeSound() {
return "Squeks";
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class FactoryProvider {
public static AbstractFactory getFactory(String choice){
if("Toy".equalsIgnoreCase(choice)){
return new AnimalFactory();
}
else if("Color".equalsIgnoreCase(choice)){
return new ColorFactory();
}
return null;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class White implements Color {
@Override
public String getColor() {
return "White";
}
}

View File

@ -0,0 +1,64 @@
package com.baeldung.designpatterns.creational.builder;
public class BankAccount {
private String name;
private String accountNumber;
private String email;
private boolean newsletter;
//The constructor that takes a builder from which it will create object
//the access to this is only provided to builder
private BankAccount(BankAccountBuilder builder) {
this.name = builder.name;
this.accountNumber = builder.accountNumber;
this.email = builder.email;
this.newsletter = builder.newsletter;
}
public static class BankAccountBuilder {
private String name;
private String accountNumber;
private String email;
private boolean newsletter;
//All Mandatory parameters goes with this constructor
public BankAccountBuilder(String name, String accountNumber) {
this.name = name;
this.accountNumber = accountNumber;
}
//setters for optional parameters which returns this same builder
//to support fluent design
public BankAccountBuilder withEmail(String email) {
this.email = email;
return this;
}
public BankAccountBuilder wantNewsletter(boolean newsletter) {
this.newsletter = newsletter;
return this;
}
//the actual build method that prepares and returns a BankAccount object
public BankAccount build() {
return new BankAccount(this);
}
}
//getters
public String getName() {
return name;
}
public String getAccountNumber() {
return accountNumber;
}
public String getEmail() {
return email;
}
public boolean isNewsletter() {
return newsletter;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.designpatterns.creational.builder;
public class BuilderPatternDriver {
public static void main(String[] args) {
BankAccount newAccount = new BankAccount
.BankAccountBuilder("Jon", "22738022275")
.withEmail("jon@example.com")
.wantNewsletter(true)
.build();
System.out.println("Name: " + newAccount.getName());
System.out.println("AccountNumber:" + newAccount.getAccountNumber());
System.out.println("Email: " + newAccount.getEmail());
System.out.println("Want News letter?: " + newAccount.isNewsletter());
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.designpatterns.creational.factory;
public class FactoryDriver {
public static void main(String[] args) {
Polygon p;
PolygonFactory factory = new PolygonFactory();
//get the shape which has 4 sides
p = factory.getPolygon(4);
System.out.println("The shape with 4 sides is a " + p.getType());
//get the shape which has 4 sides
p = factory.getPolygon(8);
System.out.println("The shape with 8 sides is a " + p.getType());
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.factory;
public class Heptagon implements Polygon {
@Override
public String getType() {
return "Heptagon";
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.factory;
public class Octagon implements Polygon {
@Override
public String getType() {
return "Octagon";
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.factory;
public class Pentagon implements Polygon {
@Override
public String getType() {
return "Pentagon";
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.creational.factory;
public interface Polygon {
String getType();
}

View File

@ -0,0 +1,22 @@
package com.baeldung.designpatterns.creational.factory;
public class PolygonFactory {
public Polygon getPolygon(int numberOfSides) {
if(numberOfSides == 3) {
return new Triangle();
}
if(numberOfSides == 4) {
return new Square();
}
if(numberOfSides == 5) {
return new Pentagon();
}
if(numberOfSides == 4) {
return new Heptagon();
}
else if(numberOfSides == 8) {
return new Octagon();
}
return null;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.factory;
public class Square implements Polygon {
@Override
public String getType() {
return "Square";
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.factory;
public class Triangle implements Polygon {
@Override
public String getType() {
return "Triangle";
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.designpatterns.creational.singleton;
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.designpatterns.creational.singleton;
public class SingletonDriver {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
System.out.println(instance.toString());
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.timezonedisplay;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class TimezoneDisplayJava7 {
public enum OffsetBase {
GMT, UTC
}
public List<String> getTimeZoneList(TimezoneDisplayJava7.OffsetBase base) {
String[] availableZoneIds = TimeZone.getAvailableIDs();
List<String> result = new ArrayList<>(availableZoneIds.length);
for (String zoneId : availableZoneIds) {
TimeZone curTimeZone = TimeZone.getTimeZone(zoneId);
String offset = calculateOffset(curTimeZone.getRawOffset());
result.add(String.format("(%s%s) %s", base, offset, zoneId));
}
Collections.sort(result);
return result;
}
private String calculateOffset(int rawOffset) {
if (rawOffset == 0) {
return "+00:00";
}
long hours = TimeUnit.MILLISECONDS.toHours(rawOffset);
long minutes = TimeUnit.MILLISECONDS.toMinutes(rawOffset);
minutes = Math.abs(minutes - TimeUnit.HOURS.toMinutes(hours));
return String.format("%+03d:%02d", hours, Math.abs(minutes));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.timezonedisplay;
import java.util.List;
public class TimezoneDisplayJava7App {
public static void main(String... args) {
TimezoneDisplayJava7 display = new TimezoneDisplayJava7();
System.out.println("Time zones in UTC:");
List<String> utc = display.getTimeZoneList(TimezoneDisplayJava7.OffsetBase.UTC);
for (String timeZone : utc) {
System.out.println(timeZone);
}
System.out.println("Time zones in GMT:");
List<String> gmt = display.getTimeZoneList(TimezoneDisplayJava7.OffsetBase.GMT);
for (String timeZone : gmt) {
System.out.println(timeZone);
}
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.copyfiles;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class FileCopierTest {
File original = new File("src/test/resources/original.txt");
@Before
public void init() throws IOException {
if (!original.exists())
Files.createFile(original.toPath());
}
@Test
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithIo.txt");
try (InputStream in = new BufferedInputStream(new FileInputStream(original));
OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
byte[] buffer = new byte[1024];
int lengthRead;
while ((lengthRead = in.read(buffer)) > 0) {
out.write(buffer, 0, lengthRead);
out.flush();
}
}
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
@Test
public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
FileUtils.copyFile(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
@Test
public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException {
Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
Path originalPath = original.toPath();
Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
assertThat(copied).exists();
assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied)));
}
@Test
public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
com.google.common.io.Files.copy(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.designpatterns.creational.abstractfactory;
import static org.junit.Assert.*;
import org.junit.Test;
public class AbstractPatternIntegrationTest {
@Test
public void givenAbstractFactory_whenGettingObjects_thenSuccessful() {
AbstractFactory abstractFactory;
//creating a brown toy dog
abstractFactory = FactoryProvider.getFactory("Toy");
Animal toy = abstractFactory.getAnimal("Dog");
abstractFactory = FactoryProvider.getFactory("Color");
Color color = abstractFactory.getColor("Brown");
String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound();
assertEquals("A Dog with brown color Barks", result);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.designpatterns.creational.builder;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class BuilderPatternIntegrationTest {
@Test
public void whenCreatingObjectThroughBuilder_thenObjectValid() {
BankAccount newAccount = new BankAccount
.BankAccountBuilder("Jon", "22738022275")
.withEmail("jon@example.com")
.wantNewsletter(true)
.build();
assertEquals(newAccount.getName(), "Jon");
assertEquals(newAccount.getAccountNumber(), "22738022275");
assertEquals(newAccount.getEmail(), "jon@example.com");
assertEquals(newAccount.isNewsletter(), true);
}
@Test
public void whenSkippingOptionalParameters_thenObjectValid() {
BankAccount newAccount = new BankAccount
.BankAccountBuilder("Jon", "22738022275")
.build();
assertEquals(newAccount.getName(), "Jon");
assertEquals(newAccount.getAccountNumber(), "22738022275");
assertEquals(newAccount.getEmail(), null);
assertEquals(newAccount.isNewsletter(), false);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.designpatterns.creational.factory;
import static org.junit.Assert.*;
import org.junit.Test;
public class FactoryIntegrationTest {
@Test
public void whenUsingFactoryForSquare_thenCorrectObjectReturned() {
Polygon p;
PolygonFactory factory = new PolygonFactory();
//get the shape which has 4 sides
p = factory.getPolygon(4);
String result = "The shape with 4 sides is a " + p.getType();
assertEquals("The shape with 4 sides is a Square", result);
}
@Test
public void whenUsingFactoryForOctagon_thenCorrectObjectReturned() {
Polygon p;
PolygonFactory factory = new PolygonFactory();
//get the shape which has 4 sides
p = factory.getPolygon(8);
String result = "The shape with 8 sides is a " + p.getType();
assertEquals("The shape with 8 sides is a Octagon", result);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.designpatterns.creational.singleton;
import org.junit.Test;
import static org.junit.Assert.*;
public class SingletonIntegrationTest {
@Test
/**
* Although there is absolutely no way to determine whether
* a class is Singleton, in this test case, we will just
* check for two objects if they point to same instance or
* not. We will also check for their hashcode.
*/
public void whenGettingMultipleObjects_thenAllPointToSame() {
//first object
Singleton obj1 = Singleton.getInstance();
//Second object
Singleton obj2 = Singleton.getInstance();
assertTrue(obj1 == obj2);
assertEquals(obj1.hashCode(), obj2.hashCode());
}
}

View File

@ -14,7 +14,8 @@ public class StringFormatterExampleTests {
public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() {
//Syntax of Format Specifiers for Date/Time Representation
Calendar c = new GregorianCalendar(2017, 11, 10);
String s = String.format("The date is: %1$tm %1$te,%1$tY", c);
String s = String.format("The date is: %tm %1$te,%1$tY", c);
assertEquals("The date is: 12 10,2017", s);
}
@ -84,7 +85,7 @@ public class StringFormatterExampleTests {
public void givenString_whenLineSeparatorConversion_thenConvertedString() {
//Line Separator Conversion
String s = String.format("First Line %nSecond Line");
assertEquals("First Line \n"
assertEquals("First Line " + System.getProperty("line.separator")
+ "Second Line", s);
}
@ -114,10 +115,10 @@ public class StringFormatterExampleTests {
public void givenString_whenSpecifyArgumentIndex_thenGotExpected() {
Calendar c = new GregorianCalendar(2017, 11, 10);
//Argument_Index
String s = String.format("The date is: %1$tm %1$te,%1$tY", c);
String s = String.format("The date is: %tm %1$te,%1$tY", c);
assertEquals("The date is: 12 10,2017", s);
s = String.format("The date is: %1$tm %<te,%<tY", c);
s = String.format("The date is: %tm %<te,%<tY", c);
assertEquals("The date is: 12 10,2017", s);
}
@ -126,8 +127,7 @@ public class StringFormatterExampleTests {
//Using String Formatter with Appendable
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
formatter.format("I am writting to a %1$s Instance.", sb.getClass());
formatter.format("I am writting to a %s Instance.", sb.getClass());
assertEquals("I am writting to a class java.lang.StringBuilder Instance.", sb.toString());
}

View File

@ -0,0 +1,2 @@
#Copy a File with Java (www.Baeldung.com)
Copying Files with Java is Fun!

1
gradle/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/.gradle/

27
gradle/.travis.yml Normal file
View File

@ -0,0 +1,27 @@
# More details on how to configure the Travis build
# https://docs.travis-ci.com/user/customizing-the-build/
# Speed up build with travis caches
cache:
directories:
- $HOME/.gradle/caches/
- $HOME/.gradle/wrapper/
language: java
jdk:
- oraclejdk8
#Skipping install step to avoid having Travis run arbitrary './gradlew assemble' task
# https://docs.travis-ci.com/user/customizing-the-build/#Skipping-the-Installation-Step
install:
- true
#Don't build tags
branches:
except:
- /^v\d/
#Build and perform release (if needed)
script:
- ./gradlew build -s && ./gradlew ciPerformRelease

View File

@ -1,25 +1,35 @@
apply plugin: 'java'
apply plugin: 'maven'
repositories{
mavenCentral()
allprojects {
repositories {
jcenter()
}
}
dependencies{
compile 'org.springframework:spring-context:4.3.5.RELEASE'
}
task hello {
println "this Baeldung's tutorial is ${awesomeness}"
subprojects {
version = '1.0'
}
uploadArchives {
repositories {
mavenDeployer {
repository(url: 'http://yourmavenrepo/repository') {
authentication(userName: 'user', password: 'password');
}
}
}
apply plugin: 'eclipse'
println 'This will be executed during the configuration phase.'
task configured {
println 'This will also be executed during the configuration phase.'
}
task execFirstTest {
doLast {
println 'This will be executed during the execution phase.'
}
}
task execSecondTest {
doFirst {
println 'This will be executed first during the execution phase.'
}
doLast {
println 'This will be executed last during the execution phase.'
}
println 'This will be executed during the configuration phase as well.'
}

View File

@ -1,3 +0,0 @@
awesomeness=awesome
group=com.baeldung.tutorial
version=1.0.1

View File

@ -0,0 +1,41 @@
//This default Shipkit configuration file was created automatically and is intended to be checked-in.
//Default configuration is sufficient for local testing and trying out Shipkit.
//To leverage Shipkit fully, please fix the TODO items, refer to our Getting Started Guide for help:
//
// https://github.com/mockito/shipkit/blob/master/docs/getting-started.md
//
shipkit {
//TODO is the repository correct?
gitHub.repository = "unspecified-user/unspecified-repo"
//TODO generate and use your own read-only GitHub personal access token
gitHub.readOnlyAuthToken = "76826c9ec886612f504d12fd4268b16721c4f85d"
//TODO generate GitHub write token, and ensure your Travis CI has this env variable exported
gitHub.writeAuthToken = System.getenv("GH_WRITE_TOKEN")
}
allprojects {
plugins.withId("com.jfrog.bintray") {
//Bintray configuration is handled by JFrog Bintray Gradle Plugin
//For reference see the official documentation: https://github.com/bintray/gradle-bintray-plugin
bintray {
//TODO sign up for free open source account with https://bintray.com, then look up your API key on your profile page in Bintray
key = '7ea297848ca948adb7d3ee92a83292112d7ae989'
//TODO don't check in the key, remove above line and use env variable exported on CI:
//key = System.getenv("BINTRAY_API_KEY")
pkg {
//TODO configure Bintray settings per your project (https://github.com/bintray/gradle-bintray-plugin)
repo = 'bootstrap'
user = 'shipkit-bootstrap-bot'
userOrg = 'shipkit-bootstrap'
name = 'maven'
licenses = ['MIT']
labels = ['continuous delivery', 'release automation', 'shipkit']
}
}
}
}

Binary file not shown.

View File

@ -1,6 +1,6 @@
#Sat Dec 31 15:46:08 BRT 2016
#Thu Oct 12 16:43:02 BDT 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.2.1-bin.zip

View File

@ -0,0 +1,5 @@
task fromPlugin {
doLast {
println "I'm from plugin"
}
}

View File

@ -0,0 +1,110 @@
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "org.shipkit:shipkit:0.9.117"
}
}
plugins {
id 'java'
}
apply from: 'aplugin.gradle'
apply plugin: 'org.shipkit.bintray-release'
//hello task
task hello {
doLast {
println 'Baeldung'
}
}
//Groovy in gradle task
task toLower {
doLast {
String someString = 'HELLO FROM BAELDUNG'
println "Original: " + someString
println "Lower case: " + someString.toLowerCase()
}
}
// Task dependencies
task helloGradle {
doLast {
println 'Hello Gradle!'
}
}
task fromBaeldung(dependsOn: helloGradle) {
doLast {
println "I'm from Baeldung"
}
}
//Adding behavior to a task via api
task helloBaeldung {
doLast {
println 'I will be executed second'
}
}
helloBaeldung.doFirst {
println 'I will be executed first'
}
helloBaeldung.doLast {
println 'I will be executed third'
}
helloBaeldung {
doLast {
println 'I will be executed fourth'
}
}
//Adding extra task properties
task ourTask {
ext.theProperty = "theValue"
}
task printTaskProperty {
doLast {
println ourTask.theProperty
}
}
//Declaring dependencies
dependencies {
compile group:
'org.springframework', name: 'spring-core', version: '4.3.5.RELEASE'
compile 'org.springframework:spring-core:4.3.5.RELEASE',
'org.springframework:spring-aop:4.3.5.RELEASE'
compile(
[group: 'org.springframework', name: 'spring-core', version: '4.3.5.RELEASE'],
[group: 'org.springframework', name: 'spring-aop', version: '4.3.5.RELEASE']
)
testCompile('org.hibernate:hibernate-core:5.2.12.Final') {
transitive = true
}
runtime(group: 'org.hibernate', name: 'hibernate-core', version: '5.2.12.Final') {
transitive = false
}
runtime "org.codehaus.groovy:groovy-all:2.4.11@jar"
runtime group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.4.11', ext: 'jar'
compile fileTree(dir: 'libs', include: '*.jar')
}

View File

@ -0,0 +1,2 @@
Manifest-Version: 1.0

46
gradle/gradlew vendored
View File

@ -6,12 +6,30 @@
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@ -30,6 +48,7 @@ die ( ) {
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
@ -40,26 +59,11 @@ case "`uname`" in
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@ -85,7 +89,7 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then

8
gradle/gradlew.bat vendored
View File

@ -8,14 +8,14 @@
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
@ -46,7 +46,7 @@ echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args

3
gradle/greeter/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/.gradle
/build
/bin

View File

@ -0,0 +1,18 @@
apply plugin : 'java'
apply plugin : 'application'
dependencies {
compile project(':greeting-library')
compile project(':greeting-library-java')
}
mainClassName = 'greeter.Greeter'
run {
if (project.hasProperty("appArgs")) {
args Eval.me(appArgs)
}
else
args = ["Baeldung"];
}

View File

@ -0,0 +1,13 @@
package greeter;
import baeldunggreeter.Formatter;
public class Greeter {
public static void main(String[] args) {
final String output = GreetingFormatter
.greeting(args[0]);
String date = Formatter.getFormattedDate();
System.out.println(output);
System.out.println("Today is :" + date);
}
}

View File

@ -0,0 +1,11 @@
public class TestGreeting{
}

View File

@ -0,0 +1,2 @@
/build
/bin

View File

@ -0,0 +1,9 @@
apply plugin :'java'
//apply plugin : 'application'
dependencies{
compile group: 'joda-time', name: 'joda-time', version: '2.9.9'
testCompile group: 'junit', name: 'junit', version: '4.12'
}

View File

@ -0,0 +1,14 @@
package baeldunggreeter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Formatter {
public static String getFormattedDate() {
DateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
}

View File

@ -0,0 +1,23 @@
package baeldunggreetertest;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import java.util.regex.Pattern;
import org.junit.Test;
import baeldunggreeter.Formatter;
public class FormatterTest {
@Test
public void testFormatter() {
String dateRegex1 = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])$";
String dateString = Formatter.getFormattedDate();
assertTrue(Pattern
.matches(dateRegex1, dateString));
}
}

1
gradle/greeting-library/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build/

View File

@ -0,0 +1,10 @@
package greeter
import groovy.transform.CompileStatic
@CompileStatic
class GreetingFormatter{
static String greeting(final String name) {
"Hello, ${name.capitalize()}"
}
}

View File

@ -0,0 +1,13 @@
package greeter
import spock.lang.Specification
class GreetingFormatterSpec extends Specification {
def 'Creating a greeting'() {
expect: 'The greeeting to be correctly capitalized'
GreetingFormatter.greeting('gradlephant') == 'Hello, Gradlephant'
}
}

View File

@ -0,0 +1,9 @@
apply plugin : 'groovy'
dependencies {
compile 'org.codehaus.groovy:groovy:2.4.12'
testCompile 'org.spockframework:spock-core:1.0-groovy-2.4', {
exclude module : 'groovy-all'
}
}

View File

@ -0,0 +1,10 @@
package greeter
import groovy.transform.CompileStatic
@CompileStatic
class GreetingFormatter{
static String greeting(final String name) {
"Hello, ${name.capitalize()}"
}
}

View File

@ -0,0 +1,13 @@
package greeter
import spock.lang.Specification
class GreetingFormatterSpec extends Specification {
def 'Creating a greeting'() {
expect: 'The greeeting to be correctly capitalized'
GreetingFormatter.greeting('gradlephant') == 'Hello, Gradlephant'
}
}

10
gradle/settings.gradle Normal file
View File

@ -0,0 +1,10 @@
rootProject.name = 'gradletutorial'
include 'greeting-library'
include 'greeting-library-java'
include 'greeter'
include 'gradletaskdemo'
println 'This will be executed during the initialization phase.'

View File

@ -1,5 +0,0 @@
public class Main{
public static void main(String[] args){
System.out.println("Baeldung Rocks");
}
}

View File

@ -0,0 +1,3 @@
#Version of the produced binaries. This file is intended to be checked-in.
#It will be automatically bumped by release automation.
version=0.0.1

View File

@ -12,6 +12,16 @@ import com.baeldung.hibernate.pojo.Course;
import com.baeldung.hibernate.pojo.Student;
import com.baeldung.hibernate.pojo.User;
import com.baeldung.hibernate.pojo.UserProfile;
import com.baeldung.hibernate.pojo.inheritance.Animal;
import com.baeldung.hibernate.pojo.inheritance.Bag;
import com.baeldung.hibernate.pojo.inheritance.Book;
import com.baeldung.hibernate.pojo.inheritance.Car;
import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
import com.baeldung.hibernate.pojo.inheritance.MyProduct;
import com.baeldung.hibernate.pojo.inheritance.Pen;
import com.baeldung.hibernate.pojo.inheritance.Person;
import com.baeldung.hibernate.pojo.inheritance.Pet;
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
@ -50,6 +60,16 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(OrderEntry.class);
metadataSources.addAnnotatedClass(OrderEntryIdClass.class);
metadataSources.addAnnotatedClass(UserProfile.class);
metadataSources.addAnnotatedClass(Book.class);
metadataSources.addAnnotatedClass(MyEmployee.class);
metadataSources.addAnnotatedClass(MyProduct.class);
metadataSources.addAnnotatedClass(Pen.class);
metadataSources.addAnnotatedClass(Person.class);
metadataSources.addAnnotatedClass(Animal.class);
metadataSources.addAnnotatedClass(Pet.class);
metadataSources.addAnnotatedClass(Vehicle.class);
metadataSources.addAnnotatedClass(Car.class);
metadataSources.addAnnotatedClass(Bag.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()

View File

@ -0,0 +1,40 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Animal {
@Id
private long animalId;
private String species;
public Animal() {}
public Animal(long animalId, String species) {
this.animalId = animalId;
this.species = species;
}
public long getAnimalId() {
return animalId;
}
public void setAnimalId(long animalId) {
this.animalId = animalId;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.Polymorphism;
import org.hibernate.annotations.PolymorphismType;
@Entity
@Polymorphism(type = PolymorphismType.EXPLICIT)
public class Bag implements Item {
@Id
private long bagId;
private String type;
public Bag(long bagId, String type) {
this.bagId = bagId;
this.type = type;
}
public long getBagId() {
return bagId;
}
public void setBagId(long bagId) {
this.bagId = bagId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("1")
public class Book extends MyProduct {
private String author;
public Book() {
}
public Book(long productId, String name, String author) {
super(productId, name);
this.author = author;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
@Entity
public class Car extends Vehicle {
private String engine;
public Car() {
}
public Car(long vehicleId, String manufacturer, String engine) {
super(vehicleId, manufacturer);
this.engine = engine;
}
public String getEngine() {
return engine;
}
public void setEngine(String engine) {
this.engine = engine;
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.hibernate.pojo.inheritance;
public interface Item {
}

View File

@ -0,0 +1,22 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
@Entity
public class MyEmployee extends Person {
private String company;
public MyEmployee(long personId, String name, String company) {
super(personId, name);
this.company = company;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import org.hibernate.annotations.DiscriminatorFormula;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "product_type", discriminatorType = DiscriminatorType.INTEGER)
// @DiscriminatorFormula("case when author is not null then 1 else 2 end")
public class MyProduct {
@Id
private long productId;
private String name;
public MyProduct() {
}
public MyProduct(long productId, String name) {
super();
this.productId = productId;
this.name = name;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("2")
public class Pen extends MyProduct {
private String color;
public Pen() {
}
public Pen(long productId, String name, String color) {
super(productId, name);
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class Person {
@Id
private long personId;
private String name;
public Person() {
}
public Person(long personId, String name) {
this.personId = personId;
this.name = name;
}
public long getPersonId() {
return personId;
}
public void setPersonId(long personId) {
this.personId = personId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
@Entity
@PrimaryKeyJoinColumn(name = "petId")
public class Pet extends Animal {
private String name;
public Pet() {
}
public Pet(long animalId, String species, String name) {
super(animalId, species);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Vehicle {
@Id
private long vehicleId;
private String manufacturer;
public Vehicle() {
}
public Vehicle(long vehicleId, String manufacturer) {
this.vehicleId = vehicleId;
this.manufacturer = manufacturer;
}
public long getVehicleId() {
return vehicleId;
}
public void setVehicleId(long vehicleId) {
this.vehicleId = vehicleId;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
}

View File

@ -0,0 +1,89 @@
package com.baeldung.hibernate;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.pojo.inheritance.Bag;
import com.baeldung.hibernate.pojo.inheritance.Book;
import com.baeldung.hibernate.pojo.inheritance.Car;
import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
import com.baeldung.hibernate.pojo.inheritance.Pen;
import com.baeldung.hibernate.pojo.inheritance.Pet;
public class InheritanceMappingIntegrationTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory()
.openSession();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void givenSubclasses_whenQuerySingleTableSuperclass_thenOk() {
Book book = new Book(1, "1984", "George Orwell");
session.save(book);
Pen pen = new Pen(2, "my pen", "blue");
session.save(pen);
assertThat(session.createQuery("from MyProduct")
.getResultList()
.size()).isEqualTo(2);
}
@Test
public void givenSubclasses_whenQueryMappedSuperclass_thenOk() {
MyEmployee emp = new MyEmployee(1, "john", "baeldung");
session.save(emp);
assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Person")
.getResultList()
.size()).isEqualTo(1);
}
@Test
public void givenSubclasses_whenQueryJoinedTableSuperclass_thenOk() {
Pet pet = new Pet(1, "dog", "lassie");
session.save(pet);
assertThat(session.createQuery("from Animal")
.getResultList()
.size()).isEqualTo(1);
}
@Test
public void givenSubclasses_whenQueryTablePerClassSuperclass_thenOk() {
Car car = new Car(1, "audi", "xyz");
session.save(car);
assertThat(session.createQuery("from Vehicle")
.getResultList()
.size()).isEqualTo(1);
}
@Test
public void givenSubclasses_whenQueryNonMappedInterface_thenOk() {
Bag bag = new Bag(1, "large");
session.save(bag);
assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Item")
.getResultList()
.size()).isEqualTo(0);
}
}

View File

@ -98,9 +98,9 @@
<jsonb-api.version>1.0</jsonb-api.version>
<johnzon.version>1.1.3</johnzon.version>
<geronimo-json_1.1_spec.version>1.0</geronimo-json_1.1_spec.version>
<yasson.version>1.0</yasson.version>
<yasson.version>1.0.1</yasson.version>
<javax.json.version>1.1.2</javax.json.version>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.adapter;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.bind.adapter.JsonbAdapter;
import com.baeldung.jsonb.Person;
public class PersonAdapter implements JsonbAdapter<Person, JsonObject> {
@Override
public JsonObject adaptToJson(Person p) throws Exception {
return Json.createObjectBuilder()
.add("id", p.getId())
.add("name", p.getName())
.build();
}
@Override
public Person adaptFromJson(JsonObject adapted) throws Exception {
Person person = new Person();
person.setId(adapted.getInt("id"));
person.setName(adapted.getString("name"));
return person;
}
}

View File

@ -22,10 +22,10 @@ public class Person {
private BigDecimal salary;
public Person() {
this(0, "", "", 0, LocalDate.now(), new BigDecimal(0));
}
public Person(int id, String name, String email, int age, LocalDate registeredDate, BigDecimal salary) {
super();
this.id = id;
this.name = name;
this.email = email;

View File

@ -17,6 +17,8 @@ import javax.json.bind.config.PropertyOrderStrategy;
import org.apache.commons.collections4.ListUtils;
import org.junit.Test;
import com.baeldung.adapter.PersonAdapter;
public class JsonbTest {
@Test
@ -155,4 +157,32 @@ public class JsonbTest {
.equals(person));
}
@Test
public void givenPersonObject_whenSerializeWithAdapter_thenGetPersonJson() {
JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter());
Jsonb jsonb = JsonbBuilder.create(config);
Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon");
String jsonPerson = jsonb.toJson(person);
// @formatter:off
String jsonExpected =
"{\"id\":1," +
"\"name\":\"Jhon\"}";
// @formatter:on
assertTrue(jsonExpected.equals(jsonPerson));
}
@Test
public void givenPersonJson_whenDeserializeWithAdapter_thenGetPersonObject() {
JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter());
Jsonb jsonb = JsonbBuilder.create(config);
Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon");
// @formatter:off
String jsonPerson =
"{\"id\":1," +
"\"name\":\"Jhon\"}";
// @formatter:on
assertTrue(jsonb.fromJson(jsonPerson, Person.class)
.equals(person));
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.junit5;
import static org.junit.Assert.assertEquals;
import org.junit.AfterClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.DEFAULT)
public class DefaultOrderOfExecutionTest {
private static StringBuilder output = new StringBuilder("");
@Test
public void secondTest() {
output.append("b");
}
@Test
public void thirdTest() {
output.append("c");
}
@Test
public void firstTest() {
output.append("a");
}
@AfterClass
public static void assertOutput() {
assertEquals(output.toString(), "cab");
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.junit5;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.JVM)
public class JVMOrderOfExecutionTest {
private static StringBuilder output = new StringBuilder("");
@Test
public void secondTest() {
output.append("b");
}
@Test
public void thirdTest() {
output.append("c");
}
@Test
public void firstTest() {
output.append("a");
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.junit5;
import static org.junit.Assert.assertEquals;
import org.junit.AfterClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class NameAscendingOrderOfExecutionTest {
private static StringBuilder output = new StringBuilder("");
@Test
public void secondTest() {
output.append("b");
}
@Test
public void thirdTest() {
output.append("c");
}
@Test
public void firstTest() {
output.append("a");
}
@AfterClass
public static void assertOutput() {
assertEquals(output.toString(), "abc");
}
}

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