Merge branch 'eugenp:master' into master
This commit is contained in:
commit
a0998d2edf
@ -7,5 +7,6 @@ This module contains articles about Project Jigsaw and the Java Platform Module
|
||||
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
|
||||
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
|
||||
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api)
|
||||
- [Java 9 Illegal Reflective Access Warning](https://www.baeldung.com/java-illegal-reflective-access)
|
||||
|
||||
|
||||
|
@ -0,0 +1,11 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR=baeldung-agent
|
||||
|
||||
# compile
|
||||
mkdir -p out/${DIR}
|
||||
javac -d out/${DIR} $(find ${DIR} -type f -name "*.java")
|
||||
|
||||
# package
|
||||
mkdir -p mods
|
||||
jar --create --file=mods/${DIR}.jar --manifest=${DIR}/manifest.txt -C out/${DIR} .
|
@ -0,0 +1,11 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR=baeldung-reflected
|
||||
|
||||
# compile
|
||||
mkdir -p out/${DIR}
|
||||
javac -d out/${DIR} $(find ${DIR} -type f -name "*.java")
|
||||
|
||||
# package
|
||||
mkdir -p mods
|
||||
jar --create --file=mods/${DIR}.jar -C out/${DIR} .
|
@ -0,0 +1,11 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR=baeldung-intermedium
|
||||
|
||||
# compile
|
||||
mkdir -p out/${DIR}
|
||||
javac -d out/${DIR} $(find ${DIR} -type f -name "*.java")
|
||||
|
||||
# package
|
||||
mkdir -p mods
|
||||
jar --create --file=mods/${DIR}.jar -C out/${DIR} .
|
@ -0,0 +1,11 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR=baeldung-reflecting-named
|
||||
|
||||
# compile
|
||||
mkdir -p out/${DIR}
|
||||
javac -d out/${DIR} --module-path mods $(find ${DIR} -type f -name "*.java")
|
||||
|
||||
# package
|
||||
mkdir -p mods
|
||||
jar --create --file=mods/${DIR}.jar -C out/${DIR} .
|
@ -0,0 +1,11 @@
|
||||
#!/bin/bash
|
||||
|
||||
DIR=baeldung-reflecting-unnamed
|
||||
|
||||
# compile
|
||||
mkdir -p out/${DIR}
|
||||
javac -d out/${DIR} $(find ${DIR} -type f -name "*.java")
|
||||
|
||||
# package
|
||||
mkdir -p mods
|
||||
jar --create --file=mods/${DIR}.jar -C out/${DIR} .
|
@ -0,0 +1,4 @@
|
||||
#!/bin/bash
|
||||
java --module-path mods \
|
||||
--add-opens baeldung.reflected/com.baeldung.reflected.internal=baeldung.reflecting.named \
|
||||
--module baeldung.reflecting.named/com.baeldung.reflecting.named.Main
|
@ -0,0 +1,4 @@
|
||||
#!/bin/bash
|
||||
java --module-path mods \
|
||||
--add-opens baeldung.reflected/com.baeldung.reflected.internal=baeldung.intermedium \
|
||||
--module baeldung.reflecting.named/com.baeldung.reflecting.named.MainWithForwardOpen
|
@ -0,0 +1,4 @@
|
||||
#!/bin/bash
|
||||
java --module-path mods \
|
||||
-javaagent:mods/baeldung-agent.jar=com.baeldung.reflected.internal.InternalNonPublicClass,com.baeldung.reflecting.named.Main \
|
||||
--module baeldung.reflecting.named/com.baeldung.reflecting.named.Main
|
@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
java -cp "mods/*" com.baeldung.reflecting.unnamed.Main
|
@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
java -cp "mods/*" --add-opens java.base/java.lang=ALL-UNNAMED com.baeldung.reflecting.unnamed.Main
|
@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
java -cp "mods/*" -javaagent:mods/baeldung-agent.jar com.baeldung.reflecting.unnamed.Main
|
@ -0,0 +1,4 @@
|
||||
#!/bin/bash
|
||||
|
||||
rm -rf out
|
||||
rm -rf mods
|
@ -0,0 +1,69 @@
|
||||
package com.baeldung.agent;
|
||||
|
||||
import java.lang.instrument.Instrumentation;
|
||||
import java.util.*;
|
||||
|
||||
public class LoadTimeAgent {
|
||||
public static void premain(String agentArgs, Instrumentation inst) {
|
||||
System.out.println("agentArgs: " + agentArgs);
|
||||
|
||||
if (agentArgs != null) {
|
||||
addExportsAndOpensByClassName(inst, agentArgs);
|
||||
}
|
||||
else {
|
||||
addExportsAndOpensToUnnamedModule(inst);
|
||||
}
|
||||
}
|
||||
|
||||
private static void addExportsAndOpensByClassName(Instrumentation inst, String agentArgs) {
|
||||
String[] array = agentArgs.split(",");
|
||||
try {
|
||||
String className1 = array[0];
|
||||
String className2 = array[1];
|
||||
Class<?> clazz1 = Class.forName(className1);
|
||||
Class<?> clazz2 = Class.forName(className2);
|
||||
|
||||
Module srcModule = clazz1.getModule();
|
||||
Module targetModule = clazz2.getModule();
|
||||
redefineModule(inst, srcModule, targetModule);
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void addExportsAndOpensToUnnamedModule(Instrumentation inst) {
|
||||
Module unnamedModule = ClassLoader.getSystemClassLoader().getUnnamedModule();
|
||||
Set<Module> modules = ModuleLayer.boot().modules();
|
||||
|
||||
for (Module m : modules) {
|
||||
redefineModule(inst, m, unnamedModule);
|
||||
}
|
||||
}
|
||||
|
||||
private static void redefineModule(Instrumentation inst, Module src, Module target) {
|
||||
// prepare extra reads
|
||||
Set<Module> extraReads = Collections.singleton(target);
|
||||
|
||||
// prepare extra exports
|
||||
Set<String> packages = src.getPackages();
|
||||
Map<String, Set<Module>> extraExports = new HashMap<>();
|
||||
for (String pkg : packages) {
|
||||
extraExports.put(pkg, extraReads);
|
||||
}
|
||||
|
||||
// prepare extra opens
|
||||
Map<String, Set<Module>> extraOpens = new HashMap<>();
|
||||
for (String pkg : packages) {
|
||||
extraOpens.put(pkg, extraReads);
|
||||
}
|
||||
|
||||
// prepare extra uses
|
||||
Set<Class<?>> extraUses = Collections.emptySet();
|
||||
|
||||
// prepare extra provides
|
||||
Map<Class<?>, List<Class<?>>> extraProvides = Collections.emptyMap();
|
||||
|
||||
// redefine module
|
||||
inst.redefineModule(src, extraReads, extraExports, extraOpens, extraUses, extraProvides);
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
Premain-Class: com.baeldung.agent.LoadTimeAgent
|
||||
Can-Redefine-Classes: true
|
||||
Can-Retransform-Classes: true
|
@ -0,0 +1,3 @@
|
||||
module baeldung.agent {
|
||||
requires java.instrument;
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.intermedium;
|
||||
|
||||
public class ForwardOpen {
|
||||
public static void addOpens(Class<?> clazz1, Class<?> clazz2) {
|
||||
Module currentModule = ForwardOpen.class.getModule();
|
||||
Module srcModule = clazz1.getModule();
|
||||
Module targetModule = clazz2.getModule();
|
||||
|
||||
System.out.println("current module: " + currentModule.getName());
|
||||
System.out.println("source module: " + srcModule.getName());
|
||||
System.out.println("target module: " + targetModule.getName());
|
||||
|
||||
srcModule.addOpens(clazz1.getPackageName(), targetModule);
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
module baeldung.intermedium {
|
||||
exports com.baeldung.intermedium;
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.reflected.exported;
|
||||
|
||||
class ExportedNonPublicClass {
|
||||
public static void testPublicStaticMethod() {
|
||||
System.out.println("ExportedNonPublicClass.testPublicStaticMethod()");
|
||||
}
|
||||
|
||||
private static void testPrivateStaticMethod() {
|
||||
System.out.println("ExportedNonPublicClass.testPrivateStaticMethod()");
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.reflected.exported;
|
||||
|
||||
public class ExportedPublicClass {
|
||||
public static void testPublicStaticMethod() {
|
||||
System.out.println("ExportedPublicClass.testPublicStaticMethod()");
|
||||
}
|
||||
|
||||
private static void testPrivateStaticMethod() {
|
||||
System.out.println("ExportedPublicClass.testPrivateStaticMethod()");
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.reflected.internal;
|
||||
|
||||
class InternalNonPublicClass {
|
||||
public static void testPublicStaticMethod() {
|
||||
System.out.println("InternalNonPublicClass.testPublicStaticMethod()");
|
||||
}
|
||||
|
||||
private static void testPrivateStaticMethod() {
|
||||
System.out.println("InternalNonPublicClass.testPrivateStaticMethod()");
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.reflected.internal;
|
||||
|
||||
public class InternalPublicClass {
|
||||
public static void testPublicStaticMethod() {
|
||||
System.out.println("InternalPublicClass.testPublicStaticMethod()");
|
||||
}
|
||||
|
||||
private static void testPrivateStaticMethod() {
|
||||
System.out.println("InternalPublicClass.testPrivateStaticMethod()");
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.reflected.opened;
|
||||
|
||||
class OpenedNonPublicClass {
|
||||
public static void testPublicStaticMethod() {
|
||||
System.out.println("OpenedNonPublicClass.testPublicStaticMethod()");
|
||||
}
|
||||
|
||||
private static void testPrivateStaticMethod() {
|
||||
System.out.println("OpenedNonPublicClass.testPrivateStaticMethod()");
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.reflected.opened;
|
||||
|
||||
public class OpenedPublicClass {
|
||||
public static void testPublicStaticMethod() {
|
||||
System.out.println("OpenedPublicClass.testPublicStaticMethod()");
|
||||
}
|
||||
|
||||
private static void testPrivateStaticMethod() {
|
||||
System.out.println("OpenedPublicClass.testPrivateStaticMethod()");
|
||||
}
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
module baeldung.reflected {
|
||||
exports com.baeldung.reflected.exported;
|
||||
opens com.baeldung.reflected.opened;
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.reflecting.named;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Class<?> clazz = Class.forName("com.baeldung.reflected.internal.InternalNonPublicClass");
|
||||
Method method = clazz.getDeclaredMethod("testPrivateStaticMethod");
|
||||
method.setAccessible(true);
|
||||
method.invoke(null);
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.reflecting.named;
|
||||
|
||||
import com.baeldung.intermedium.ForwardOpen;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class MainWithForwardOpen {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Class<?> currentClass = Main.class;
|
||||
Class<?> clazz = Class.forName("com.baeldung.reflected.internal.InternalNonPublicClass");
|
||||
|
||||
ForwardOpen.addOpens(clazz, currentClass);
|
||||
|
||||
Method method = clazz.getDeclaredMethod("testPrivateStaticMethod");
|
||||
method.setAccessible(true);
|
||||
method.invoke(null);
|
||||
}
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
module baeldung.reflecting.named {
|
||||
requires baeldung.intermedium;
|
||||
requires baeldung.reflected;
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.reflecting.unnamed;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Class<?> clazz = StringBuilder.class;
|
||||
Field f = clazz.getDeclaredField("serialVersionUID");
|
||||
f.setAccessible(true);
|
||||
Object value = f.get(null);
|
||||
System.out.println(value);
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package com.baeldung.list.listvsarraylist;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Locale;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class ArrayListDemo {
|
||||
|
||||
private ArrayList<Passenger> passengers = new ArrayList<>(20);
|
||||
// private LinkedList<Passenger> passengers = new LinkedList<>(); // compile time error
|
||||
|
||||
public ArrayList<Passenger> addPassenger(Passenger passenger) {
|
||||
passengers.add(passenger);
|
||||
return passengers;
|
||||
}
|
||||
|
||||
public ArrayList<Passenger> removePassenger(Passenger passenger) {
|
||||
passengers.remove(passenger);
|
||||
return passengers;
|
||||
}
|
||||
|
||||
public ArrayList<Passenger> getPassengersBySource(String source) {
|
||||
return new ArrayList<Passenger>(passengers.stream()
|
||||
.filter(it -> it.getSource().equals(source))
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
public ArrayList<Passenger> getPassengersByDestination(String destination) {
|
||||
return new ArrayList<Passenger> (passengers.stream()
|
||||
.filter(it -> it.getDestination().equals(destination))
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
public long getKidsCount(ArrayList<Passenger> passengerList) {
|
||||
return passengerList.stream()
|
||||
.filter(it -> (it.getAge() <= 10))
|
||||
.count();
|
||||
}
|
||||
|
||||
public ArrayList<Passenger> getFinalPassengersList() {
|
||||
return new ArrayList<Passenger> (Collections.unmodifiableList(passengers));
|
||||
}
|
||||
|
||||
public ArrayList<String> getServicedCountries() {
|
||||
return new ArrayList<String> (Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.baeldung.list.listvsarraylist;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class ListDemo {
|
||||
|
||||
private List<Passenger> passengers = new ArrayList<>(20);
|
||||
// private List<Passenger> passengers = new LinkedList<>(); // No compile time error
|
||||
|
||||
public List<Passenger> addPassenger(Passenger passenger) {
|
||||
passengers.add(passenger);
|
||||
return passengers;
|
||||
}
|
||||
|
||||
public List<Passenger> removePassenger(Passenger passenger) {
|
||||
passengers.remove(passenger);
|
||||
return passengers;
|
||||
}
|
||||
|
||||
public List<Passenger> getPassengersBySource(String source) {
|
||||
return passengers.stream()
|
||||
.filter(it -> it.getSource().equals(source))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Passenger> getPassengersByDestination(String destination) {
|
||||
return passengers.stream()
|
||||
.filter(it -> it.getDestination().equals(destination))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public long getKidsCount(List<Passenger> passengerList) {
|
||||
return passengerList.stream()
|
||||
.filter(it -> (it.getAge() <= 10))
|
||||
.count();
|
||||
}
|
||||
|
||||
public List<Passenger> getFinalPassengersList() {
|
||||
return Collections.unmodifiableList(passengers);
|
||||
}
|
||||
|
||||
public List<String> getServicedCountries() {
|
||||
return Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.list.listvsarraylist;
|
||||
|
||||
public class Passenger {
|
||||
|
||||
private String name;
|
||||
private int age;
|
||||
private String source;
|
||||
private String destination;
|
||||
|
||||
public Passenger(String name, int age, String source, String destination) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.source = source;
|
||||
this.destination = destination;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getSource() {
|
||||
return source;
|
||||
}
|
||||
|
||||
public void setSource(String source) {
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
public String getDestination() {
|
||||
return destination;
|
||||
}
|
||||
|
||||
public void setDestination(String destination) {
|
||||
this.destination = destination;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
package com.baeldung.list.listvsarraylist;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ArrayListDemoUnitTest {
|
||||
|
||||
ArrayListDemo application = new ArrayListDemo();
|
||||
|
||||
Passenger passenger1;
|
||||
Passenger passenger2;
|
||||
Passenger passenger3;
|
||||
|
||||
@BeforeEach
|
||||
protected void setUp() {
|
||||
passenger1 = new Passenger("Anna", 25, "London", "New York");
|
||||
passenger2 = new Passenger("Binny", 35, "New York", "London");
|
||||
passenger3 = new Passenger("Chandra", 8, "Paris", "New Delhi");
|
||||
application.addPassenger(passenger1);
|
||||
application.addPassenger(passenger2);
|
||||
application.addPassenger(passenger3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenAddedPassenger_thenReturnCurrentPassengerList() {
|
||||
ArrayList<Passenger> list = application.addPassenger(new Passenger("David", 54, "Milan", "Paris"));
|
||||
|
||||
assertNotNull(list);
|
||||
assertThat(list).hasSize(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPassengerList_whenRemovedPassenger_thenReturnCurrentPassengerList() {
|
||||
ArrayList<Passenger> list = application.removePassenger(passenger3);
|
||||
|
||||
assertNotNull(list);
|
||||
assertThat(list).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPassengerList_whenPassedWithSourceCity_thenReturnMatchingPassengerList() {
|
||||
ArrayList<Passenger> list = application.getPassengersBySource("Singapore");
|
||||
ArrayList<Passenger> list2 = application.getPassengersBySource("London");
|
||||
|
||||
assertThat(list).isEmpty();
|
||||
assertThat(list2.get(0)).isEqualTo(passenger1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPassengerList_whenPassedWithDestinationCity_thenReturnMatchingPassengerList() {
|
||||
ArrayList<Passenger> list = application.getPassengersByDestination("Singapore");
|
||||
ArrayList<Passenger> list2 = application.getPassengersByDestination("London");
|
||||
|
||||
assertThat(list).isEmpty();
|
||||
assertThat(list2.get(0)).isEqualTo(passenger2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPassengerList_whenFindKidsByAge_thenReturnKidsList() {
|
||||
ArrayList<Passenger> list = new ArrayList<>();
|
||||
list.add(passenger1);
|
||||
list.add(passenger2);
|
||||
list.add(passenger3);
|
||||
long count = application.getKidsCount(list);
|
||||
|
||||
assertThat(count).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPassengerList_whenCalledWithCollectionsFunction_thenReturnsListType() {
|
||||
ArrayList<Passenger> list = application.getFinalPassengersList();
|
||||
|
||||
assertNotNull(list);
|
||||
assertThat(list).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCurrentLocale_whenUsingStreams_thenReturnsListType() {
|
||||
ArrayList<String> servicedCountries = application.getServicedCountries();
|
||||
|
||||
assertNotNull(servicedCountries);
|
||||
assertThat(servicedCountries).hasSize(Locale.getISOCountries().length);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,92 @@
|
||||
package com.baeldung.list.listvsarraylist;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ListDemoUnitTest {
|
||||
|
||||
ListDemo application = new ListDemo();
|
||||
|
||||
Passenger passenger1;
|
||||
Passenger passenger2;
|
||||
Passenger passenger3;
|
||||
|
||||
@BeforeEach
|
||||
protected void setUp() {
|
||||
passenger1 = new Passenger("Anna", 25, "London", "New York");
|
||||
passenger2 = new Passenger("Binny", 35, "New York", "London");
|
||||
passenger3 = new Passenger("Chandra", 8, "Paris", "New Delhi");
|
||||
application.addPassenger(passenger1);
|
||||
application.addPassenger(passenger2);
|
||||
application.addPassenger(passenger3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenAddedPassenger_thenReturnCurrentPassengerList() {
|
||||
List<Passenger> list = application.addPassenger(new Passenger("David", 54, "Milan", "Paris"));
|
||||
|
||||
assertNotNull(list);
|
||||
assertThat(list).hasSize(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPresentList_whenRemovedPassenger_thenReturnCurrentPassengerList() {
|
||||
List<Passenger> list = application.removePassenger(passenger3);
|
||||
|
||||
assertNotNull(list);
|
||||
assertThat(list).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPresentList_whenPassedWithSourceCity_thenReturnMatchingPassengerList() {
|
||||
List<Passenger> list = application.getPassengersBySource("Singapore");
|
||||
List<Passenger> list2 = application.getPassengersBySource("London");
|
||||
|
||||
assertThat(list).isEmpty();
|
||||
assertThat(list2.get(0)).isEqualTo(passenger1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPresentList_whenPassedWithDestinationCity_thenReturnMatchingPassengerList() {
|
||||
List<Passenger> list = application.getPassengersByDestination("Singapore");
|
||||
List<Passenger> list2 = application.getPassengersByDestination("London");
|
||||
|
||||
assertThat(list).isEmpty();
|
||||
assertThat(list2.get(0)).isEqualTo(passenger2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPassengerList_whenFindKidsByAge_thenReturnKidsList() {
|
||||
List<Passenger> list = new ArrayList<>();
|
||||
list.add(passenger1);
|
||||
list.add(passenger2);
|
||||
list.add(passenger3);
|
||||
long count = application.getKidsCount(list);
|
||||
|
||||
assertThat(count).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPresentList_whenCalledWithCollectionsFunction_thenReturnsListType() {
|
||||
List<Passenger> list = application.getFinalPassengersList();
|
||||
|
||||
assertNotNull(list);
|
||||
assertThat(list).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCurrentLocale_whenUsingStreams_thenReturnsListType() {
|
||||
List<String> servicedCountries = application.getServicedCountries();
|
||||
|
||||
assertNotNull(servicedCountries);
|
||||
assertThat(servicedCountries).hasSize(Locale.getISOCountries().length);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package test.java.com.baeldung.list.listOfHashMaps;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ListOfHashMapsUnitTest {
|
||||
List<HashMap<String, List<String>>> booksAuthorsMapsList = new ArrayList<>();
|
||||
|
||||
@Test
|
||||
public void givenMaps_whenAddToList_thenListContainsMaps() {
|
||||
HashMap<String, List<String>> javaBooksAuthorsMap = new HashMap<>();
|
||||
HashMap<String, List<String>> phpBooksAuthorsMap = new HashMap<>();
|
||||
javaBooksAuthorsMap.put("Head First Java", Arrays.asList("Kathy Sierra", "Bert Bates"));
|
||||
javaBooksAuthorsMap.put("Effective Java", Arrays.asList("Joshua Bloch"));
|
||||
javaBooksAuthorsMap.put("OCA Java SE 8",
|
||||
Arrays.asList("Kathy Sierra", "Bert Bates", "Elisabeth Robson"));
|
||||
phpBooksAuthorsMap.put("The Joy of PHP", Arrays.asList("Alan Forbes"));
|
||||
phpBooksAuthorsMap.put("Head First PHP & MySQL",
|
||||
Arrays.asList("Lynn Beighley", "Michael Morrison"));
|
||||
|
||||
booksAuthorsMapsList.add(javaBooksAuthorsMap);
|
||||
booksAuthorsMapsList.add(phpBooksAuthorsMap);
|
||||
|
||||
assertTrue(booksAuthorsMapsList.get(0).keySet().containsAll
|
||||
(javaBooksAuthorsMap.keySet().stream().collect(Collectors.toList())));
|
||||
assertTrue(booksAuthorsMapsList.get(1).keySet().containsAll
|
||||
(phpBooksAuthorsMap.keySet().stream().collect(Collectors.toList())));
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package regex.array;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.*;
|
||||
|
||||
class RegexMatches {
|
||||
|
||||
String[] regexMatch(String strSearch)
|
||||
{
|
||||
List<String> matchesList = new ArrayList<String>();
|
||||
String stringToSearch = strSearch;
|
||||
Pattern p1 = Pattern.compile("780{1}\\d{7}");
|
||||
Matcher m1 = p1.matcher(stringToSearch);
|
||||
while (m1.find())
|
||||
{
|
||||
matchesList.add(m1.group());
|
||||
}
|
||||
int sizeOfNewArray = matchesList.size();
|
||||
String newArrayOfMatches[] = new String[sizeOfNewArray];
|
||||
matchesList.toArray(newArrayOfMatches);
|
||||
return newArrayOfMatches;
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package regex.array;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import regex.array.RegexMatches;
|
||||
|
||||
class RegexMatchesUnitTest {
|
||||
|
||||
@Test
|
||||
void whenFourNums_thenFourMatches() {
|
||||
RegexMatches rm = new RegexMatches();
|
||||
String actual[] = rm.regexMatch("7801111211fsdafasdfa 7802222222 sadfsadfsda7803333333 sadfdasfasd 7804444444");
|
||||
|
||||
assertArrayEquals(new String[] {"7801111211", "7802222222", "7803333333", "7804444444"}, actual, "success");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenThreeNums_thenThreeMatches() {
|
||||
RegexMatches rm = new RegexMatches();
|
||||
String actual[] = rm.regexMatch("7801111211fsdafasdfa 780222222 sadfsadfsda7803333333 sadfdasfasd 7804444444");
|
||||
|
||||
assertArrayEquals(new String[] {"7801111211", "7803333333", "7804444444"}, actual, "success");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenZeroNums_thenZeroMatches() {
|
||||
RegexMatches rm = new RegexMatches();
|
||||
String actual[] = rm.regexMatch("78011111fsdafasdfa 780222222 sadfsadfsda78033333 sadfdasfasd 7804444");
|
||||
|
||||
assertArrayEquals(new String[] {}, actual, "success");
|
||||
}
|
||||
}
|
97
graphql/graphql-error-handling/pom.xml
Normal file
97
graphql/graphql-error-handling/pom.xml
Normal file
@ -0,0 +1,97 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.graphql</groupId>
|
||||
<artifactId>graphql-error-handling</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>graphql-error-handling</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<lombok.version>1.18.18</lombok.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphql-spring-boot-starter</artifactId>
|
||||
<version>5.0.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphql-java-tools</artifactId>
|
||||
<version>5.2.4</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-test</artifactId>
|
||||
<scope>test</scope>
|
||||
<version>2.6.4</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphql-spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
<version>5.0.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.22.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.skyscreamer</groupId>
|
||||
<artifactId>jsonassert</artifactId>
|
||||
<version>1.5.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,46 @@
|
||||
package com.baeldung.graphql.error.handling;
|
||||
|
||||
import com.baeldung.graphql.error.handling.exception.GraphQLErrorAdapter;
|
||||
import graphql.ExceptionWhileDataFetching;
|
||||
import graphql.GraphQLError;
|
||||
import graphql.servlet.GraphQLErrorHandler;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@SpringBootApplication
|
||||
public class GraphQLErrorHandlerApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(GraphQLErrorHandlerApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public GraphQLErrorHandler errorHandler() {
|
||||
return new GraphQLErrorHandler() {
|
||||
@Override
|
||||
public List<GraphQLError> processErrors(List<GraphQLError> errors) {
|
||||
List<GraphQLError> clientErrors = errors.stream()
|
||||
.filter(this::isClientError)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<GraphQLError> serverErrors = errors.stream()
|
||||
.filter(e -> !isClientError(e))
|
||||
.map(GraphQLErrorAdapter::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<GraphQLError> e = new ArrayList<>();
|
||||
e.addAll(clientErrors);
|
||||
e.addAll(serverErrors);
|
||||
return e;
|
||||
}
|
||||
|
||||
private boolean isClientError(GraphQLError error) {
|
||||
return !(error instanceof ExceptionWhileDataFetching || error instanceof Throwable);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.graphql.error.handling.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToMany;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Entity
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class Location {
|
||||
@Id
|
||||
private String zipcode;
|
||||
|
||||
private String city;
|
||||
private String state;
|
||||
|
||||
@OneToMany(mappedBy = "location", fetch = FetchType.EAGER)
|
||||
private List<Vehicle> vehicles = new ArrayList<>();
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.graphql.error.handling.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Data
|
||||
@Entity
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class Vehicle {
|
||||
@Id
|
||||
private String vin;
|
||||
private Integer year;
|
||||
private String make;
|
||||
private String model;
|
||||
private String trim;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "fk_location")
|
||||
private Location location;
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.baeldung.graphql.error.handling.exception;
|
||||
|
||||
import graphql.ErrorType;
|
||||
import graphql.GraphQLError;
|
||||
import graphql.language.SourceLocation;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class AbstractGraphQLException extends RuntimeException implements GraphQLError {
|
||||
private Map<String, Object> parameters = new HashMap();
|
||||
|
||||
public AbstractGraphQLException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public AbstractGraphQLException(String message, Map<String, Object> additionParams) {
|
||||
this(message);
|
||||
if (additionParams != null) {
|
||||
parameters = additionParams;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return super.getMessage();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SourceLocation> getLocations() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ErrorType getErrorType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getExtensions() {
|
||||
return this.parameters;
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.baeldung.graphql.error.handling.exception;
|
||||
|
||||
import graphql.ErrorType;
|
||||
import graphql.ExceptionWhileDataFetching;
|
||||
import graphql.GraphQLError;
|
||||
import graphql.language.SourceLocation;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class GraphQLErrorAdapter implements GraphQLError {
|
||||
|
||||
private GraphQLError error;
|
||||
|
||||
public GraphQLErrorAdapter(GraphQLError error) {
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getExtensions() {
|
||||
return error.getExtensions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SourceLocation> getLocations() {
|
||||
return error.getLocations();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ErrorType getErrorType() {
|
||||
return error.getErrorType();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Object> getPath() {
|
||||
return error.getPath();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> toSpecification() {
|
||||
return error.toSpecification();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return (error instanceof ExceptionWhileDataFetching) ? ((ExceptionWhileDataFetching) error).getException().getMessage() : error.getMessage();
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.graphql.error.handling.exception;
|
||||
|
||||
public class InvalidInputException extends RuntimeException {
|
||||
public InvalidInputException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.graphql.error.handling.exception;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class VehicleAlreadyPresentException extends AbstractGraphQLException {
|
||||
|
||||
public VehicleAlreadyPresentException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public VehicleAlreadyPresentException(String message, Map<String, Object> additionParams) {
|
||||
super(message, additionParams);
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.graphql.error.handling.exception;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class VehicleNotFoundException extends AbstractGraphQLException {
|
||||
|
||||
public VehicleNotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public VehicleNotFoundException(String message, Map<String, Object> params) {
|
||||
super(message, params);
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.graphql.error.handling.repository;
|
||||
|
||||
import com.baeldung.graphql.error.handling.domain.Vehicle;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface InventoryRepository extends JpaRepository<Vehicle, String> {
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.graphql.error.handling.repository;
|
||||
|
||||
import com.baeldung.graphql.error.handling.domain.Location;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface LocationRepository extends JpaRepository<Location, String> {
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.graphql.error.handling.resolver;
|
||||
|
||||
import com.baeldung.graphql.error.handling.domain.Location;
|
||||
import com.baeldung.graphql.error.handling.domain.Vehicle;
|
||||
import com.baeldung.graphql.error.handling.service.InventoryService;
|
||||
import com.coxautodev.graphql.tools.GraphQLMutationResolver;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class Mutation implements GraphQLMutationResolver {
|
||||
private InventoryService inventoryService;
|
||||
|
||||
public Mutation(InventoryService inventoryService) {
|
||||
this.inventoryService = inventoryService;
|
||||
}
|
||||
|
||||
public Vehicle addVehicle(String vin, Integer year, String make, String model, String trim, Location location) {
|
||||
return this.inventoryService.addVehicle(vin, year, make, model, trim, location);
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.graphql.error.handling.resolver;
|
||||
|
||||
import com.baeldung.graphql.error.handling.domain.Vehicle;
|
||||
import com.baeldung.graphql.error.handling.service.InventoryService;
|
||||
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class Query implements GraphQLQueryResolver {
|
||||
private final InventoryService inventoryService;
|
||||
|
||||
public Query(InventoryService inventoryService) {
|
||||
this.inventoryService = inventoryService;
|
||||
}
|
||||
|
||||
public List<Vehicle> searchAll() {
|
||||
return this.inventoryService.searchAll();
|
||||
}
|
||||
|
||||
public List<Vehicle> searchByLocation(String zipcode) {
|
||||
return this.inventoryService.searchByLocation(zipcode);
|
||||
}
|
||||
|
||||
public Vehicle searchByVin(String vin) {
|
||||
return this.inventoryService.searchByVin(vin);
|
||||
}
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
package com.baeldung.graphql.error.handling.service;
|
||||
|
||||
import com.baeldung.graphql.error.handling.domain.Location;
|
||||
import com.baeldung.graphql.error.handling.domain.Vehicle;
|
||||
import com.baeldung.graphql.error.handling.exception.InvalidInputException;
|
||||
import com.baeldung.graphql.error.handling.exception.VehicleAlreadyPresentException;
|
||||
import com.baeldung.graphql.error.handling.exception.VehicleNotFoundException;
|
||||
import com.baeldung.graphql.error.handling.repository.InventoryRepository;
|
||||
import com.baeldung.graphql.error.handling.repository.LocationRepository;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
public class InventoryService {
|
||||
private InventoryRepository inventoryRepository;
|
||||
private LocationRepository locationRepository;
|
||||
|
||||
public InventoryService(InventoryRepository inventoryRepository, LocationRepository locationRepository) {
|
||||
this.inventoryRepository = inventoryRepository;
|
||||
this.locationRepository = locationRepository;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Vehicle addVehicle(String vin, Integer year, String make, String model, String trim, Location location) {
|
||||
Optional<Vehicle> existingVehicle = this.inventoryRepository.findById(vin);
|
||||
if (existingVehicle.isPresent()) {
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("vin", vin);
|
||||
throw new VehicleAlreadyPresentException("Failed to add vehicle. Vehicle with vin " + vin + " already present.", params);
|
||||
}
|
||||
Vehicle vehicle = Vehicle.builder()
|
||||
.vin(vin)
|
||||
.year(year)
|
||||
.make(make)
|
||||
.model(model)
|
||||
.location(location)
|
||||
.trim(trim)
|
||||
.build();
|
||||
|
||||
this.locationRepository.save(location);
|
||||
return this.inventoryRepository.save(vehicle);
|
||||
}
|
||||
|
||||
public List<Vehicle> searchAll() {
|
||||
return this.inventoryRepository.findAll();
|
||||
}
|
||||
|
||||
public List<Vehicle> searchByLocation(String zipcode) {
|
||||
if (StringUtils.isEmpty(zipcode) || zipcode.length() != 5) {
|
||||
throw new InvalidInputException("Invalid zipcode " + zipcode + " provided.");
|
||||
}
|
||||
return this.locationRepository.findById(zipcode)
|
||||
.map(Location::getVehicles)
|
||||
.orElse(new ArrayList<>());
|
||||
}
|
||||
|
||||
public Vehicle searchByVin(String vin) {
|
||||
return this.inventoryRepository.findById(vin).orElseThrow(() -> {
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("vin", vin);
|
||||
return new VehicleNotFoundException("Vehicle with vin " + vin + " not found.", params);
|
||||
});
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
graphql:
|
||||
servlet:
|
||||
mapping: /graphql
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: "jdbc:h2:mem:graphqldb"
|
||||
driverClassName: "org.h2.Driver"
|
||||
username: sa
|
||||
password:
|
||||
|
||||
initialization-mode: always
|
||||
platform: h2
|
||||
|
||||
jpa:
|
||||
show-sql: true
|
||||
properties:
|
||||
hibernate:
|
||||
dialect: org.hibernate.dialect.H2Dialect
|
||||
ddl-auto: none
|
||||
|
||||
h2:
|
||||
console.enabled: true
|
@ -0,0 +1,23 @@
|
||||
type Vehicle {
|
||||
vin: ID!
|
||||
year: Int!
|
||||
make: String!
|
||||
model: String!
|
||||
trim: String!
|
||||
}
|
||||
|
||||
input Location {
|
||||
city: String
|
||||
state: String
|
||||
zipcode: String!
|
||||
}
|
||||
|
||||
type Query {
|
||||
searchAll: [Vehicle]!
|
||||
searchByLocation(zipcode: String!): [Vehicle]!
|
||||
searchByVin(vin: String!): Vehicle
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
addVehicle(vin: ID!, year: Int!, make: String!, model: String!, trim: String, location: Location): Vehicle!
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
insert into LOCATION values('07092', 'Mountainside', 'NJ');
|
||||
insert into LOCATION values ('94118', 'San Francisco', 'CA');
|
||||
insert into LOCATION values ('10002', 'New York', 'NY');
|
||||
|
||||
insert into VEHICLE (vin, year, make, model, trim, fk_location) values('KM8JN72DX7U587496', 2007, 'Hyundai', 'Tucson', null, '07092');
|
||||
insert into VEHICLE (vin, year, make, model, trim, fk_location) values('JTKKU4B41C1023346', 2012, 'Toyota', 'Scion', 'Xd', '94118');
|
||||
insert into VEHICLE (vin, year, make, model, trim, fk_location) values('1G1JC1444PZ215071', 2000, 'Chevrolet', 'CAVALIER VL', 'RS', '07092');
|
@ -0,0 +1,55 @@
|
||||
package com.baeldung.graphql.error.handling;
|
||||
|
||||
import com.graphql.spring.boot.test.GraphQLResponse;
|
||||
import com.graphql.spring.boot.test.GraphQLTestTemplate;
|
||||
import org.json.JSONException;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.skyscreamer.jsonassert.JSONAssert;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static com.baeldung.graphql.error.handling.TestUtils.readFile;
|
||||
import static java.lang.String.format;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = GraphQLErrorHandlerApplication.class)
|
||||
public class GraphQLErrorHandlerApplicationIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private GraphQLTestTemplate graphQLTestTemplate;
|
||||
|
||||
private static final String GRAPHQL_TEST_REQUEST_PATH = "graphql/request/%s.graphql";
|
||||
private static final String GRAPHQL_TEST_RESPONSE_PATH = "graphql/response/%s.json";
|
||||
|
||||
@Test
|
||||
public void whenUnknownOperation_thenRespondWithRequestError() throws IOException, JSONException {
|
||||
String graphqlName = "request_error_unknown_operation";
|
||||
GraphQLResponse actualResponse = graphQLTestTemplate.postForResource(format(GRAPHQL_TEST_REQUEST_PATH, graphqlName));
|
||||
String expectedResponse = readFile(format(GRAPHQL_TEST_RESPONSE_PATH, graphqlName));
|
||||
|
||||
JSONAssert.assertEquals(expectedResponse, actualResponse.getRawResponse().getBody(), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInvalidSyntaxRequest_thenRespondWithRequestError() throws IOException, JSONException {
|
||||
String graphqlName = "request_error_invalid_request_syntax";
|
||||
GraphQLResponse actualResponse = graphQLTestTemplate.postForResource(format(GRAPHQL_TEST_REQUEST_PATH, graphqlName));
|
||||
String expectedResponse = readFile(format(GRAPHQL_TEST_RESPONSE_PATH, graphqlName));
|
||||
|
||||
JSONAssert.assertEquals(expectedResponse, actualResponse.getRawResponse().getBody(), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestAllNonNullField_thenRespondPartialDataWithFieldError() throws IOException, JSONException {
|
||||
String graphqlName = "field_error_request_non_null_fields_partial_response";
|
||||
GraphQLResponse actualResponse = graphQLTestTemplate.postForResource(format(GRAPHQL_TEST_REQUEST_PATH, graphqlName));
|
||||
String expectedResponse = readFile(format(GRAPHQL_TEST_RESPONSE_PATH, graphqlName));
|
||||
|
||||
JSONAssert.assertEquals(expectedResponse, actualResponse.getRawResponse().getBody(), true);
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.graphql.error.handling;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
public class TestUtils {
|
||||
public static String readFile(String path) throws IOException {
|
||||
return IOUtils.toString(
|
||||
new ClassPathResource(path).getInputStream(), Charset.defaultCharset()
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
# trim is non null but one of the record has null value for trim
|
||||
query {
|
||||
searchAll {
|
||||
vin
|
||||
year
|
||||
make
|
||||
model
|
||||
trim
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
query {
|
||||
searchByVin(vin: "error) {
|
||||
vin
|
||||
year
|
||||
make
|
||||
model
|
||||
trim
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
subscription {
|
||||
searchByVin(vin: "75024") {
|
||||
vin
|
||||
year
|
||||
make
|
||||
model
|
||||
trim
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
{
|
||||
"data": {
|
||||
"searchAll": [
|
||||
null,
|
||||
{
|
||||
"vin": "JTKKU4B41C1023346",
|
||||
"year": 2012,
|
||||
"make": "Toyota",
|
||||
"model": "Scion",
|
||||
"trim": "Xd"
|
||||
},
|
||||
{
|
||||
"vin": "1G1JC1444PZ215071",
|
||||
"year": 2000,
|
||||
"make": "Chevrolet",
|
||||
"model": "CAVALIER VL",
|
||||
"trim": "RS"
|
||||
}
|
||||
]
|
||||
},
|
||||
"errors": [
|
||||
{
|
||||
"message": "Cannot return null for non-nullable type: 'String' within parent 'Vehicle' (/searchAll[0]/trim)",
|
||||
"path": [
|
||||
"searchAll",
|
||||
0,
|
||||
"trim"
|
||||
],
|
||||
"errorType": "DataFetchingException",
|
||||
"locations": null,
|
||||
"extensions": null
|
||||
}
|
||||
]
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
{
|
||||
"data": null,
|
||||
"errors": [
|
||||
{
|
||||
"message": "Invalid Syntax",
|
||||
"locations": [
|
||||
{
|
||||
"line": 5,
|
||||
"column": 8,
|
||||
"sourceName": null
|
||||
}
|
||||
],
|
||||
"errorType": "InvalidSyntax",
|
||||
"path": null,
|
||||
"extensions": null
|
||||
}
|
||||
]
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
{
|
||||
"data": null,
|
||||
"errors": [
|
||||
{
|
||||
"errorType": "OperationNotSupported",
|
||||
"locations": [
|
||||
{
|
||||
"line": 1,
|
||||
"column": 1,
|
||||
"sourceName": null
|
||||
}
|
||||
],
|
||||
"extensions": null,
|
||||
"message": "Schema is not configured for subscriptions.",
|
||||
"path": null
|
||||
}
|
||||
]
|
||||
}
|
@ -12,7 +12,7 @@
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<repositories>
|
||||
@ -36,51 +36,15 @@
|
||||
<artifactId>graphql-java-annotations</artifactId>
|
||||
<version>${graphql-java-annotations.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.ratpack</groupId>
|
||||
<artifactId>ratpack-core</artifactId>
|
||||
<version>${ratpack-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.americanexpress.nodes</groupId>
|
||||
<artifactId>nodes</artifactId>
|
||||
<version>0.5.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphql-java</artifactId>
|
||||
<version>9.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphql-java-tools</artifactId>
|
||||
<version>5.2.4</version>
|
||||
<version>${graphql-java-tools.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphql-java-servlet</artifactId>
|
||||
<version>6.1.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.0.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.12.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-netty</artifactId>
|
||||
<version>5.11.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-client-java</artifactId>
|
||||
<version>5.11.2</version>
|
||||
<version>${graphql-java-servlet.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.graphql-java-generator</groupId>
|
||||
@ -88,15 +52,47 @@
|
||||
<version>${graphql.java.generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>5.8.2</version>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.ratpack</groupId>
|
||||
<artifactId>ratpack-core</artifactId>
|
||||
<version>${ratpack-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.americanexpress.nodes</groupId>
|
||||
<artifactId>nodes</artifactId>
|
||||
<version>${nodes.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-netty</artifactId>
|
||||
<version>${mockserver-netty.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.22.0</version>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-client-java</artifactId>
|
||||
<version>${mockserver-client-java.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@ -115,11 +111,11 @@
|
||||
<plugin>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-maven-plugin</artifactId>
|
||||
<version>10.0.7</version>
|
||||
<version>${jetty-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.graphql-java-generator</groupId>
|
||||
@ -143,12 +139,21 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<graphql-java-tools.version>5.2.4</graphql-java-tools.version>
|
||||
<graphql-java-servlet.version>6.1.3</graphql-java-servlet.version>
|
||||
<graphql-java-annotations.version>3.0.3</graphql-java-annotations.version>
|
||||
<ratpack-core.version>1.4.6</ratpack-core.version>
|
||||
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
|
||||
<graphql.java.generator.version>1.18</graphql.java.generator.version>
|
||||
<ratpack-core.version>1.9.0</ratpack-core.version>
|
||||
<nodes.version>0.5.0</nodes.version>
|
||||
<httpclient.version>4.5.13</httpclient.version>
|
||||
|
||||
<mockserver-netty.version>5.13.2</mockserver-netty.version>
|
||||
<mockserver-client-java.version>5.13.2</mockserver-client-java.version>
|
||||
|
||||
<jetty-maven-plugin.version>10.0.7</jetty-maven-plugin.version>
|
||||
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<graphql.java.generator.version>1.18</graphql.java.generator.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -19,24 +19,27 @@ import com.baeldung.graphql.utils.SchemaUtils;
|
||||
import static ratpack.jackson.Jackson.json;
|
||||
|
||||
public class UserHandler implements Handler {
|
||||
|
||||
private static final Logger LOGGER = Logger.getLogger(UserHandler.class.getSimpleName());
|
||||
private GraphQL graphql;
|
||||
private static List<User> users = new ArrayList<>();
|
||||
|
||||
private static final List<User> USERS = new ArrayList<>();
|
||||
|
||||
private final GraphQL graphql;
|
||||
|
||||
public UserHandler() throws Exception {
|
||||
graphql = new GraphQL(new UserSchema().getSchema());
|
||||
graphql = GraphQL.newGraphQL(new UserSchema().getSchema()).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(Context context) throws Exception {
|
||||
public void handle(Context context) {
|
||||
context.parse(Map.class)
|
||||
.then(payload -> {
|
||||
Map<String, Object> parameters = (Map<String, Object>) payload.get("parameters");
|
||||
ExecutionResult executionResult = graphql.execute(payload.get(SchemaUtils.QUERY)
|
||||
.toString(), null, this, parameters);
|
||||
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
if (executionResult.getErrors()
|
||||
.isEmpty()) {
|
||||
if (executionResult.getErrors().isEmpty()) {
|
||||
result.put(SchemaUtils.DATA, executionResult.getData());
|
||||
} else {
|
||||
result.put(SchemaUtils.ERRORS, executionResult.getErrors());
|
||||
@ -46,8 +49,8 @@ public class UserHandler implements Handler {
|
||||
});
|
||||
}
|
||||
|
||||
public static List<User> getUsers() {
|
||||
return users;
|
||||
public List<User> getUsers() {
|
||||
return USERS;
|
||||
}
|
||||
|
||||
public static List<User> getUsers(DataFetchingEnvironment env) {
|
||||
|
@ -12,5 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
- [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string)
|
||||
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
|
||||
- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging)
|
||||
- [Unshorten URLs with HttpClient](https://www.baeldung.com/unshorten-url-httpclient)
|
||||
- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
|
||||
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
|
||||
- More articles: [[<-- prev]](../httpclient)
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.httpclient.rare;
|
||||
package com.baeldung.httpclient.expandurl;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.collect.Lists;
|
||||
@ -22,35 +22,29 @@ import java.util.List;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class HttpClientUnshortenLiveTest {
|
||||
public class HttpClientExpandUrlLiveTest {
|
||||
|
||||
private CloseableHttpClient client;
|
||||
|
||||
// fixtures
|
||||
|
||||
@Before
|
||||
public final void before() {
|
||||
client = HttpClientBuilder.create().disableRedirectHandling().build();
|
||||
}
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void givenShortenedOnce_whenUrlIsUnshortened_thenCorrectResult() throws IOException {
|
||||
final String expectedResult = "http://www.baeldung.com/rest-versioning";
|
||||
final String actualResult = expandSingleLevel("http://bit.ly/13jEoS1");
|
||||
public final void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException {
|
||||
final String expectedResult = "https://www.baeldung.com/rest-versioning";
|
||||
final String actualResult = expandSingleLevel("http://bit.ly/3LScTri");
|
||||
assertThat(actualResult, equalTo(expectedResult));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenShortenedMultiple_whenUrlIsUnshortened_thenCorrectResult() throws IOException {
|
||||
final String expectedResult = "http://www.baeldung.com/rest-versioning";
|
||||
public final void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException {
|
||||
final String expectedResult = "https://www.baeldung.com/rest-versioning";
|
||||
final String actualResult = expand("http://t.co/e4rDDbnzmk");
|
||||
assertThat(actualResult, equalTo(expectedResult));
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
private String expand(final String urlArg) throws IOException {
|
||||
String originalUrl = urlArg;
|
||||
String newUrl = expandSingleLevel(originalUrl);
|
@ -1,6 +0,0 @@
|
||||
## Immutables
|
||||
|
||||
This module contains articles about the Immutables library.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to Immutables](https://www.baeldung.com/immutables)
|
@ -1,34 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>immutables</artifactId>
|
||||
<name>immutables</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.immutables</groupId>
|
||||
<artifactId>value</artifactId>
|
||||
<version>${immutables.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mutabilitydetector</groupId>
|
||||
<artifactId>MutabilityDetector</artifactId>
|
||||
<version>${mutabilitydetector.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<immutables.version>2.5.6</immutables.version>
|
||||
<mutabilitydetector.version>0.9.6</mutabilitydetector.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.jackson.deductionbasedpolymorphism;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
|
||||
|
||||
@JsonTypeInfo(use = Id.DEDUCTION)
|
||||
@JsonSubTypes({ @Type(ImperialSpy.class), @Type(King.class), @Type(Knight.class) })
|
||||
public interface Character {
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.jackson.deductionbasedpolymorphism;
|
||||
|
||||
public class ControlledCharacter {
|
||||
|
||||
private Character character;
|
||||
|
||||
public Character getCharacter() {
|
||||
return character;
|
||||
}
|
||||
|
||||
public void setCharacter(Character character) {
|
||||
this.character = character;
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.jackson.deductionbasedpolymorphism;
|
||||
|
||||
public class ImperialSpy implements Character {
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.jackson.deductionbasedpolymorphism;
|
||||
|
||||
public class King extends NamedCharacter {
|
||||
|
||||
private String land;
|
||||
|
||||
public String getLand() {
|
||||
return land;
|
||||
}
|
||||
|
||||
public void setLand(String land) {
|
||||
this.land = land;
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.jackson.deductionbasedpolymorphism;
|
||||
|
||||
public class Knight extends NamedCharacter {
|
||||
|
||||
private String weapon;
|
||||
|
||||
public String getWeapon() {
|
||||
return weapon;
|
||||
}
|
||||
|
||||
public void setWeapon(String weapon) {
|
||||
this.weapon = weapon;
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.jackson.deductionbasedpolymorphism;
|
||||
|
||||
public class NamedCharacter implements Character {
|
||||
|
||||
private String name;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.jackson.deductionbasedpolymorphism;
|
||||
|
||||
import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.fasterxml.jackson.databind.MapperFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.json.JsonMapper;
|
||||
|
||||
class CaseInsensitiveInferenceUnitTest {
|
||||
|
||||
private final ObjectMapper objectMapper = JsonMapper.builder()
|
||||
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
|
||||
.build();
|
||||
|
||||
@Test
|
||||
void givenACaseInsensitiveKnight_whenMapping_thenExpectKnight() throws Exception {
|
||||
String knightJson = formatJson("{'NaMe':'Ostrava, of Boletaria', 'WeaPON':'Rune Sword'}");
|
||||
|
||||
Character character = objectMapper.readValue(knightJson, Character.class);
|
||||
|
||||
assertTrue(character instanceof Knight);
|
||||
assertSame(character.getClass(), Knight.class);
|
||||
Knight knight = (Knight) character;
|
||||
assertEquals("Ostrava, of Boletaria", knight.getName());
|
||||
assertEquals("Rune Sword", knight.getWeapon());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
package com.baeldung.jackson.deductionbasedpolymorphism;
|
||||
|
||||
import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.json.JsonMapper;
|
||||
|
||||
class ContainedInferenceUnitTest {
|
||||
|
||||
private final ObjectMapper objectMapper = JsonMapper.builder()
|
||||
.build();
|
||||
|
||||
@Test
|
||||
void givenAKnightControlledCharacter_whenMapping_thenExpectAControlledCharacterWithKnight() throws Exception {
|
||||
String controlledCharacterJson = formatJson("{'character': {'name': 'Ostrava, of Boletaria', 'weapon': 'Rune Sword'}}");
|
||||
|
||||
ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class);
|
||||
Character character = controlledCharacter.getCharacter();
|
||||
|
||||
assertTrue(character instanceof Knight);
|
||||
assertSame(character.getClass(), Knight.class);
|
||||
Knight knight = (Knight) character;
|
||||
assertEquals("Ostrava, of Boletaria", knight.getName());
|
||||
assertEquals("Rune Sword", knight.getWeapon());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAKingControlledCharacter_whenMapping_thenExpectAControlledCharacterWithKing() throws Exception {
|
||||
String controlledCharacterJson = formatJson("{'character': {'name': 'King Allant', 'land': 'Boletaria'}}");
|
||||
|
||||
ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class);
|
||||
Character character = controlledCharacter.getCharacter();
|
||||
|
||||
assertTrue(character instanceof King);
|
||||
assertSame(character.getClass(), King.class);
|
||||
King king = (King) character;
|
||||
assertEquals("King Allant", king.getName());
|
||||
assertEquals("Boletaria", king.getLand());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnEmptySubtype_whenMapping_thenExpectImperialSpy() throws Exception {
|
||||
String controlledCharacterJson = formatJson("{'character': {}}");
|
||||
|
||||
ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class);
|
||||
|
||||
assertTrue(controlledCharacter.getCharacter() instanceof ImperialSpy);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenANullCharacter_whenMapping_thenExpectNullCharacter() throws Exception {
|
||||
String controlledCharacterJson = formatJson("{'character': null}");
|
||||
|
||||
ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class);
|
||||
|
||||
assertNull(controlledCharacter.getCharacter());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAAnAbsentCharacter_whenMapping_thenExpectNullCharacter() throws Exception {
|
||||
String controlledCharacterJson = formatJson("{}");
|
||||
|
||||
ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class);
|
||||
|
||||
assertNull(controlledCharacter.getCharacter());
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.jackson.deductionbasedpolymorphism;
|
||||
|
||||
public class JsonStringFormatterUtil {
|
||||
|
||||
public static String formatJson(String input) {
|
||||
return input.replaceAll("'", "\"");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package com.baeldung.jackson.deductionbasedpolymorphism;
|
||||
|
||||
import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.json.JsonMapper;
|
||||
|
||||
class SimpleInferenceUnitTest {
|
||||
|
||||
private final ObjectMapper objectMapper = JsonMapper.builder()
|
||||
.build();
|
||||
|
||||
@Test
|
||||
void givenAKnight_whenMapping_thenExpectAKnightType() throws Exception {
|
||||
String knightJson = formatJson("{'name':'Ostrava, of Boletaria', 'weapon':'Rune Sword'}");
|
||||
|
||||
Character character = objectMapper.readValue(knightJson, Character.class);
|
||||
|
||||
assertTrue(character instanceof Knight);
|
||||
assertSame(character.getClass(), Knight.class);
|
||||
Knight king = (Knight) character;
|
||||
assertEquals("Ostrava, of Boletaria", king.getName());
|
||||
assertEquals("Rune Sword", king.getWeapon());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAKing_whenMapping_thenExpectAKingType() throws Exception {
|
||||
String kingJson = formatJson("{'name':'Old King Allant', 'land':'Boletaria'}");
|
||||
|
||||
Character character = objectMapper.readValue(kingJson, Character.class);
|
||||
|
||||
assertTrue(character instanceof King);
|
||||
assertSame(character.getClass(), King.class);
|
||||
King king = (King) character;
|
||||
assertEquals("Old King Allant", king.getName());
|
||||
assertEquals("Boletaria", king.getLand());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnEmptyObject_whenMapping_thenExpectAnImperialSpy() throws Exception {
|
||||
String imperialSpyJson = "{}";
|
||||
|
||||
Character character = objectMapper.readValue(imperialSpyJson, Character.class);
|
||||
|
||||
assertTrue(character instanceof ImperialSpy);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenANullObject_whenMapping_thenExpectANullObject() throws Exception {
|
||||
Character character = objectMapper.readValue("null", Character.class);
|
||||
|
||||
assertNull(character);
|
||||
}
|
||||
|
||||
}
|
@ -5,3 +5,4 @@
|
||||
- [Determine if an Integer’s Square Root Is an Integer in Java](https://www.baeldung.com/java-find-if-square-root-is-integer)
|
||||
- [Guide to Java BigInteger](https://www.baeldung.com/java-biginteger)
|
||||
- [Automorphic Numbers in Java](https://www.baeldung.com/java-automorphic-numbers)
|
||||
- [Convert Byte Size Into a Human-Readable Format in Java](https://www.baeldung.com/java-human-readable-byte-size)
|
||||
|
@ -53,3 +53,4 @@ Enjoy it :)
|
||||
- [Intro to Performance Testing using JMeter](https://www.baeldung.com/jmeter)
|
||||
- [Configure Jenkins to Run and Show JMeter Tests](https://www.baeldung.com/ops/jenkins-and-jmeter)
|
||||
- [Write Extracted Data to a File Using JMeter](https://www.baeldung.com/jmeter-write-to-file)
|
||||
- [Basic Authentication in JMeter](https://www.baeldung.com/jmeter-basic-auth)
|
||||
|
@ -17,4 +17,5 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
|
||||
- [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway)
|
||||
- [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro)
|
||||
- [Introduction to Structurizr](https://www.baeldung.com/structurizr)
|
||||
- [Introduction to Immutables](https://www.baeldung.com/immutables)
|
||||
- More articles [[<-- prev]](../libraries-2) [[next -->]](../libraries-4)
|
||||
|
@ -112,6 +112,17 @@
|
||||
<artifactId>structurizr-plantuml</artifactId>
|
||||
<version>${structurizr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.immutables</groupId>
|
||||
<artifactId>value</artifactId>
|
||||
<version>${immutables.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mutabilitydetector</groupId>
|
||||
<artifactId>MutabilityDetector</artifactId>
|
||||
<version>${mutabilitydetector.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
@ -256,6 +267,8 @@
|
||||
<plexus-compiler.version>2.8</plexus-compiler.version>
|
||||
<errorprone.version>2.1.3</errorprone.version>
|
||||
<structurizr.version>1.0.0</structurizr.version>
|
||||
<immutables.version>2.5.6</immutables.version>
|
||||
<mutabilitydetector.version>0.9.6</mutabilitydetector.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -82,7 +82,7 @@
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
|
||||
<org.springframework.data.version>1.10.6.RELEASE</org.springframework.data.version>
|
||||
<hibernate-core.version>5.4.7.Final</hibernate-core.version>
|
||||
<hibernate-core.version>5.6.7.Final</hibernate-core.version>
|
||||
<maven.deploy.skip>true</maven.deploy.skip>
|
||||
<spring-boot.version>2.1.7.RELEASE</spring-boot.version>
|
||||
<h2.version>1.4.200</h2.version>
|
||||
|
@ -1,34 +1,51 @@
|
||||
package com.baeldung.hibernate.oneToMany.config;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.model.Cart;
|
||||
import com.baeldung.hibernate.oneToMany.model.CartOIO;
|
||||
import com.baeldung.hibernate.oneToMany.model.Item;
|
||||
import com.baeldung.hibernate.oneToMany.model.ItemOIO;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class HibernateAnnotationUtil {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateAnnotationUtil.class);
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
public static SessionFactory getSessionFactory() {
|
||||
if (sessionFactory == null) {
|
||||
sessionFactory = buildSessionFactory();
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
private static SessionFactory buildSessionFactory() {
|
||||
try {
|
||||
// Create the SessionFactory from hibernate-annotation.cfg.xml
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build();
|
||||
Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
|
||||
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
|
||||
.configure("hibernate-annotation.cfg.xml")
|
||||
.build();
|
||||
|
||||
return sessionFactory;
|
||||
Metadata metadata = new MetadataSources(serviceRegistry)
|
||||
.addAnnotatedClass(Cart.class)
|
||||
.addAnnotatedClass(CartOIO.class)
|
||||
.addAnnotatedClass(Item.class)
|
||||
.addAnnotatedClass(ItemOIO.class)
|
||||
.getMetadataBuilder()
|
||||
.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
|
||||
.build();
|
||||
|
||||
return metadata.getSessionFactoryBuilder().build();
|
||||
|
||||
} catch (Throwable ex) {
|
||||
System.err.println("Initial SessionFactory creation failed." + ex);
|
||||
ex.printStackTrace();
|
||||
LOGGER.error("Initial SessionFactory creation failed.", ex);
|
||||
throw new ExceptionInInitializerError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory() {
|
||||
if (sessionFactory == null)
|
||||
sessionFactory = buildSessionFactory();
|
||||
return sessionFactory;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,71 @@
|
||||
package com.baeldung.hibernate.oneToMany.main;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil;
|
||||
import com.baeldung.hibernate.oneToMany.model.Cart;
|
||||
import com.baeldung.hibernate.oneToMany.model.Item;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class HibernateManyIsOwningSide {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateManyIsOwningSide.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Cart cart = new Cart();
|
||||
Cart cart2 = new Cart();
|
||||
|
||||
Item item1 = new Item(cart);
|
||||
Item item2 = new Item(cart2);
|
||||
|
||||
Set<Item> itemsSet = new HashSet<>();
|
||||
itemsSet.add(item1);
|
||||
itemsSet.add(item2);
|
||||
cart.setItems(itemsSet);
|
||||
|
||||
// Get Session
|
||||
SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory();
|
||||
Session session = sessionFactory.getCurrentSession();
|
||||
|
||||
try {
|
||||
LOGGER.info("Session created");
|
||||
|
||||
// start transaction
|
||||
Transaction tx = session.beginTransaction();
|
||||
|
||||
// Save the Model object
|
||||
session.save(cart);
|
||||
session.save(cart2);
|
||||
session.save(item1);
|
||||
session.save(item2);
|
||||
|
||||
// Commit transaction
|
||||
tx.commit();
|
||||
|
||||
session = sessionFactory.getCurrentSession();
|
||||
tx = session.beginTransaction();
|
||||
|
||||
item1 = session.get(Item.class, 1L);
|
||||
item2 = session.get(Item.class, 2L);
|
||||
tx.commit();
|
||||
|
||||
LOGGER.info("item1 ID={}, Foreign Key CartOIO ID={}", item1.getId(), item1.getCart().getId());
|
||||
LOGGER.info("item2 ID={}, Foreign Key CartOIO ID={}", item2.getId(), item2.getCart().getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("Exception occurred", e);
|
||||
} finally {
|
||||
if (!sessionFactory.isClosed()) {
|
||||
LOGGER.info("Closing SessionFactory");
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,71 +0,0 @@
|
||||
package com.baeldung.hibernate.oneToMany.main;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil;
|
||||
import com.baeldung.hibernate.oneToMany.model.Cart;
|
||||
import com.baeldung.hibernate.oneToMany.model.Items;
|
||||
import com.baeldung.hibernate.oneToMany.model.ItemsOIO;
|
||||
|
||||
public class HibernateManyisOwningSide {
|
||||
public static void main(String[] args) {
|
||||
|
||||
Cart cart = new Cart();
|
||||
Cart cart2 = new Cart();
|
||||
|
||||
Items item1 = new Items(cart);
|
||||
Items item2 = new Items(cart2);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
itemsSet.add(item1);
|
||||
itemsSet.add(item2);
|
||||
|
||||
cart.setItems(itemsSet);
|
||||
|
||||
|
||||
|
||||
SessionFactory sessionFactory = null;
|
||||
Session session = null;
|
||||
Transaction tx = null;
|
||||
try {
|
||||
// Get Session
|
||||
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
|
||||
session = sessionFactory.getCurrentSession();
|
||||
System.out.println("Session created");
|
||||
// start transaction
|
||||
tx = session.beginTransaction();
|
||||
// Save the Model object
|
||||
session.save(cart);
|
||||
session.save(cart2);
|
||||
session.save(item1);
|
||||
session.save(item2);
|
||||
// Commit transaction
|
||||
tx.commit();
|
||||
session = sessionFactory.getCurrentSession();
|
||||
tx = session.beginTransaction();
|
||||
|
||||
item1 = (Items) session.get(Items.class, new Long(1));
|
||||
item2 = (Items) session.get(Items.class, new Long(2));
|
||||
tx.commit();
|
||||
|
||||
|
||||
System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCart()
|
||||
.getId());
|
||||
System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCart()
|
||||
.getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Exception occured. " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (!sessionFactory.isClosed()) {
|
||||
System.out.println("Closing SessionFactory");
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -9,57 +9,59 @@ import org.hibernate.Transaction;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil;
|
||||
import com.baeldung.hibernate.oneToMany.model.CartOIO;
|
||||
import com.baeldung.hibernate.oneToMany.model.ItemsOIO;
|
||||
import com.baeldung.hibernate.oneToMany.model.ItemOIO;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class HibernateOneIsOwningSide {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateOneIsOwningSide.class);
|
||||
|
||||
public class HibernateOneisOwningSide {
|
||||
public static void main(String[] args) {
|
||||
|
||||
CartOIO cart = new CartOIO();
|
||||
CartOIO cart2 = new CartOIO();
|
||||
|
||||
ItemsOIO item1 = new ItemsOIO(cart);
|
||||
ItemsOIO item2 = new ItemsOIO(cart2);
|
||||
Set<ItemsOIO> itemsSet = new HashSet<ItemsOIO>();
|
||||
ItemOIO item1 = new ItemOIO(cart);
|
||||
ItemOIO item2 = new ItemOIO(cart2);
|
||||
Set<ItemOIO> itemsSet = new HashSet<>();
|
||||
itemsSet.add(item1);
|
||||
itemsSet.add(item2);
|
||||
|
||||
cart.setItems(itemsSet);
|
||||
|
||||
SessionFactory sessionFactory = null;
|
||||
Session session = null;
|
||||
Transaction tx = null;
|
||||
SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory();
|
||||
Session session = sessionFactory.getCurrentSession();
|
||||
LOGGER.info("Session created");
|
||||
|
||||
Transaction tx;
|
||||
try {
|
||||
// Get Session
|
||||
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
|
||||
session = sessionFactory.getCurrentSession();
|
||||
System.out.println("Session created");
|
||||
// start transaction
|
||||
tx = session.beginTransaction();
|
||||
|
||||
// Save the Model object
|
||||
session.save(cart);
|
||||
session.save(cart2);
|
||||
session.save(item1);
|
||||
session.save(item2);
|
||||
|
||||
// Commit transaction
|
||||
tx.commit();
|
||||
|
||||
session = sessionFactory.getCurrentSession();
|
||||
tx = session.beginTransaction();
|
||||
item1 = (ItemsOIO) session.get(ItemsOIO.class, new Long(1));
|
||||
item2 = (ItemsOIO) session.get(ItemsOIO.class, new Long(2));
|
||||
item1 = session.get(ItemOIO.class, 1L);
|
||||
item2 = session.get(ItemOIO.class, 2L);
|
||||
tx.commit();
|
||||
|
||||
System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCartOIO()
|
||||
.getId());
|
||||
System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCartOIO()
|
||||
.getId());
|
||||
LOGGER.info("item1 ID={}, Foreign Key CartOIO ID={}", item1.getId(), item1.getCartOIO().getId());
|
||||
LOGGER.info("item2 ID={}, Foreign Key CartOIO ID={}", item2.getId(), item2.getCartOIO().getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Exception occured. " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
LOGGER.error("Exception occurred", e);
|
||||
} finally {
|
||||
if (!sessionFactory.isClosed()) {
|
||||
System.out.println("Closing SessionFactory");
|
||||
LOGGER.info("Closing SessionFactory");
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
@ -9,52 +9,53 @@ import org.hibernate.Transaction;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil;
|
||||
import com.baeldung.hibernate.oneToMany.model.Cart;
|
||||
import com.baeldung.hibernate.oneToMany.model.Items;
|
||||
import com.baeldung.hibernate.oneToMany.model.Item;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class HibernateOneToManyAnnotationMain {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateOneToManyAnnotationMain.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Cart cart = new Cart();
|
||||
|
||||
Items item1 = new Items(cart);
|
||||
Items item2 = new Items(cart);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
Item item1 = new Item(cart);
|
||||
Item item2 = new Item(cart);
|
||||
Set<Item> itemsSet = new HashSet<>();
|
||||
itemsSet.add(item1);
|
||||
itemsSet.add(item2);
|
||||
|
||||
cart.setItems(itemsSet);
|
||||
|
||||
|
||||
SessionFactory sessionFactory = null;
|
||||
Session session = null;
|
||||
Transaction tx = null;
|
||||
SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory();
|
||||
Session session = sessionFactory.getCurrentSession();
|
||||
LOGGER.info("Session created");
|
||||
|
||||
try {
|
||||
// Get Session
|
||||
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
|
||||
session = sessionFactory.getCurrentSession();
|
||||
System.out.println("Session created");
|
||||
// start transaction
|
||||
tx = session.beginTransaction();
|
||||
Transaction tx = session.beginTransaction();
|
||||
|
||||
// Save the Model object
|
||||
session.save(cart);
|
||||
session.save(item1);
|
||||
session.save(item2);
|
||||
|
||||
// Commit transaction
|
||||
tx.commit();
|
||||
System.out.println("Cart ID=" + cart.getId());
|
||||
System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId());
|
||||
System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId());
|
||||
|
||||
LOGGER.info("Cart ID={}", cart.getId());
|
||||
LOGGER.info("item1 ID={}, Foreign Key Cart ID={}", item1.getId(), item1.getCart().getId());
|
||||
LOGGER.info("item2 ID={}, Foreign Key Cart ID={}", item2.getId(), item2.getCart().getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Exception occured. " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
LOGGER.error("Exception occurred", e);
|
||||
} finally {
|
||||
if (!sessionFactory.isClosed()) {
|
||||
System.out.println("Closing SessionFactory");
|
||||
LOGGER.info("Closing SessionFactory");
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -19,9 +19,8 @@ public class Cart {
|
||||
@Column(name = "cart_id")
|
||||
private long id;
|
||||
|
||||
|
||||
@OneToMany(mappedBy = "cart")
|
||||
private Set<Items> items;
|
||||
private Set<Item> items;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
@ -31,12 +30,11 @@ public class Cart {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
public Set<Items> getItems() {
|
||||
public Set<Item> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(Set<Items> items) {
|
||||
public void setItems(Set<Item> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
|
@ -9,8 +9,6 @@ import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.persistence.Table;
|
||||
|
||||
|
||||
|
||||
@Entity
|
||||
@Table(name = "CARTOIO")
|
||||
public class CartOIO {
|
||||
@ -21,7 +19,7 @@ public class CartOIO {
|
||||
|
||||
@OneToMany
|
||||
@JoinColumn(name = "cart_id") // we need to duplicate the physical information
|
||||
private Set<ItemsOIO> items;
|
||||
private Set<ItemOIO> items;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
@ -31,11 +29,11 @@ public class CartOIO {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Set<ItemsOIO> getItems() {
|
||||
public Set<ItemOIO> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(Set<ItemsOIO> items) {
|
||||
public void setItems(Set<ItemOIO> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user