Fixed conflicts

This commit is contained in:
amit2103 2018-12-16 16:45:48 +05:30
commit ea25895da1
310 changed files with 5235 additions and 1371 deletions

View File

@ -28,14 +28,14 @@ public class Log {
System.out.println("Had " + count + " commits overall on current branch");
logs = git.log()
.add(repository.resolve("remotes/origin/testbranch"))
.add(repository.resolve(git.getRepository().getFullBranch()))
.call();
count = 0;
for (RevCommit rev : logs) {
System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
count++;
}
System.out.println("Had " + count + " commits overall on test-branch");
System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch());
logs = git.log()
.all()

View File

@ -1,3 +1,5 @@
package com.baeldung.jgit;
import com.baeldung.jgit.helper.Helper;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.ObjectReader;

View File

@ -1,4 +1,4 @@
package com.baeldung.string;
package com.baeldung.algorithms.string;
import java.util.HashSet;
import java.util.Set;

View File

@ -1,4 +1,4 @@
package com.baeldung.string;
package com.baeldung.algorithms.string;
import static org.junit.Assert.assertEquals;
import java.util.HashSet;

View File

@ -33,6 +33,11 @@
<artifactId>jgrapht-core</artifactId>
<version>${org.jgrapht.core.version}</version>
</dependency>
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-ext</artifactId>
<version>${org.jgrapht.ext.version}</version>
</dependency>
<dependency>
<groupId>pl.allegro.finance</groupId>
<artifactId>tradukisto</artifactId>
@ -83,6 +88,7 @@
<commons-math3.version>3.6.1</commons-math3.version>
<tradukisto.version>1.0.1</tradukisto.version>
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
<org.jgrapht.ext.version>1.0.1</org.jgrapht.ext.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
</properties>

View File

@ -0,0 +1,47 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertTrue;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.junit.Before;
import org.junit.Test;
import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.util.mxCellRenderer;
public class GraphImageGenerationUnitTest {
static DefaultDirectedGraph<String, DefaultEdge> g;
@Before
public void createGraph() throws IOException {
File imgFile = new File("src/test/resources/graph.png");
imgFile.createNewFile();
g = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
String x1 = "x1";
String x2 = "x2";
String x3 = "x3";
g.addVertex(x1);
g.addVertex(x2);
g.addVertex(x3);
g.addEdge(x1, x2);
g.addEdge(x2, x3);
g.addEdge(x3, x1);
}
@Test
public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g);
mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent());
File imgFile = new File("src/test/resources/graph.png");
BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null);
ImageIO.write(image, "PNG", imgFile);
assertTrue(imgFile.exists());
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

@ -34,7 +34,7 @@ public class MergeSort {
while (i < left && j < right) {
if (l[i] < r[j])
if (l[i] <= r[j])
a[k++] = l[i++];
else
a[k++] = r[j++];

View File

@ -0,0 +1,12 @@
#!/usr/local/bin/java --source 11
import java.util.Arrays;
public class Addition
{
public static void main(String[] args) {
System.out.println(Arrays.stream(args)
.mapToInt(Integer::parseInt)
.sum());
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.interfaces.multiinheritance;
public abstract interface Fly{
void fly();
}

View File

@ -0,0 +1,5 @@
package com.baeldung.interfaces.multiinheritance;
public interface Transform {
void transform();
}

View File

@ -0,0 +1,13 @@
package com.baeldung.interfaces.multiinheritance;
public class Vehicle implements Fly, Transform {
@Override
public void fly() {
System.out.println("I can Fly!!");
}
@Override
public void transform() {
System.out.println("I can Transform!!");
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.interfaces.polymorphysim;
public class Circle implements Shape {
private double radius;
public Circle(double radius){
this.radius = radius;
}
@Override
public String name() {
return "Circle";
}
@Override
public double area() {
return Math.PI * (radius * radius);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.interfaces.polymorphysim;
import java.util.ArrayList;
public class DisplayShape {
private ArrayList<Shape> shapes;
public DisplayShape() {
shapes = new ArrayList<>();
}
public void add(Shape shape) {
shapes.add(shape);
}
public void display() {
for (Shape shape : shapes) {
System.out.println(shape.name() + " area: " + shape.area());
}
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.interfaces.polymorphysim;
public class MainPolymorphic {
public static void main(String[] args){
Shape circleShape = new Circle(2);
Shape squareShape = new Square(2);
DisplayShape displayShape = new DisplayShape();
displayShape.add(circleShape);
displayShape.add(squareShape);
displayShape.display();
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.interfaces.polymorphysim;
public interface Shape {
public abstract String name();
public abstract double area();
}

View File

@ -0,0 +1,20 @@
package com.baeldung.interfaces.polymorphysim;
public class Square implements Shape {
private double width;
public Square(double width) {
this.width = width;
}
@Override
public String name() {
return "Square";
}
@Override
public double area() {
return width * width;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.interfaces;
import com.baeldung.interfaces.polymorphysim.Circle;
import com.baeldung.interfaces.polymorphysim.Shape;
import com.baeldung.interfaces.polymorphysim.Square;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class PolymorphysimUnitTest {
@Test
public void whenInterfacePointsToCircle_CircleAreaMethodisBeingCalled(){
double expectedArea = 12.566370614359172;
Shape circle = new Circle(2);
double actualArea = circle.area();
Assertions.assertThat(actualArea).isEqualTo(expectedArea);
}
@Test
public void whenInterfacePointsToSquare_SquareAreaMethodisBeingCalled(){
double expectedArea = 4;
Shape square = new Square(2);
double actualArea = square.area();
Assertions.assertThat(actualArea).isEqualTo(expectedArea);
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.list.multidimensional;
import java.util.ArrayList;
public class ArrayListOfArrayList {
public static void main(String args[]) {
int vertex = 5;
ArrayList<ArrayList<Integer>> graph = new ArrayList<>(vertex);
//Initializing each element of ArrayList with ArrayList
for(int i=0; i< vertex; i++) {
graph.add(new ArrayList<Integer>());
}
//We can add any number of columns to each row
graph.get(0).add(1);
graph.get(0).add(5);
graph.get(1).add(0);
graph.get(1).add(2);
graph.get(2).add(1);
graph.get(2).add(3);
graph.get(3).add(2);
graph.get(3).add(4);
graph.get(4).add(3);
graph.get(4).add(5);
//Printing all the edges
for(int i=0; i<vertex; i++) {
for(int j=0; j<graph.get(i).size(); j++) {
System.out.println("Edge between vertex "+i+"and "+graph.get(i).get(j));
}
}
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.list.multidimensional;
import java.util.ArrayList;
public class ThreeDimensionalArrayList {
public static void main(String args[]) {
int x_axis_length = 2;
int y_axis_length = 2;
int z_axis_length = 2;
ArrayList< ArrayList< ArrayList<String> > > space = new ArrayList<>(x_axis_length);
//Initializing each element of ArrayList with ArrayList< ArrayList<String> >
for(int i=0; i< x_axis_length; i++) {
space.add(new ArrayList< ArrayList<String> >(y_axis_length));
for(int j =0; j< y_axis_length; j++) {
space.get(i).add(new ArrayList<String>(z_axis_length));
}
}
//Set Red color for points (0,0,0) and (0,0,1)
space.get(0).get(0).add("Red");
space.get(0).get(0).add("Red");
//Set Blue color for points (0,1,0) and (0,1,1)
space.get(0).get(1).add("Blue");
space.get(0).get(1).add("Blue");
//Set Green color for points (1,0,0) and (1,0,1)
space.get(1).get(0).add("Green");
space.get(1).get(0).add("Green");
//Set Yellow color for points (1,1,0) and (1,1,1)
space.get(1).get(1).add("Yellow");
space.get(1).get(1).add("Yellow");
//Printing colors for all the points
for(int i=0; i<x_axis_length; i++) {
for(int j=0; j<y_axis_length; j++) {
for(int k=0; k<z_axis_length; k++) {
System.out.println("Color of point ("+i+","+j+","+k+") is :"+space.get(i).get(j).get(k));
}
}
}
}
}

View File

@ -26,7 +26,6 @@
- [ExecutorService - Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads)
- [wait and notify() Methods in Java](http://www.baeldung.com/java-wait-notify)
- [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule)
- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer)
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)

View File

@ -45,6 +45,7 @@ public class FileDownload {
FileOutputStream fileOutputStream = new FileOutputStream(localFilename); FileChannel fileChannel = fileOutputStream.getChannel()) {
fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
fileOutputStream.close();
}
}

View File

@ -1,3 +0,0 @@
=========
## Core Java Net

View File

@ -0,0 +1,7 @@
=========
## Core Java Networking
### Relevant Articles
- [Connecting Through Proxy Servers in Core Java](https://www.baeldung.com/java-connect-via-proxy-server)

View File

@ -1,10 +1,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-net</artifactId>
<artifactId>core-java-networking</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-net</name>
<name>core-java-networking</name>
<parent>
<groupId>com.baeldung</groupId>
@ -14,6 +14,6 @@
</parent>
<build>
<finalName>core-java-net</finalName>
<finalName>core-java-networking</finalName>
</build>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.basicsyntax;
public class SimpleAddition {
public static void main(String[] args) {
int a = 10;
int b = 5;
double c = a + b;
System.out.println( a + " + " + b + " = " + c);
}
}

View File

@ -0,0 +1,171 @@
package com.baeldung.java.properties;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import org.junit.Test;
public class PropertiesUnitTest {
@Test
public void givenPropertyValue_whenPropertiesFileLoaded_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
String catalogConfigPath = rootPath + "catalog";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
Properties catalogProps = new Properties();
catalogProps.load(new FileInputStream(catalogConfigPath));
String appVersion = appProps.getProperty("version");
assertEquals("1.0", appVersion);
assertEquals("files", catalogProps.getProperty("c1"));
}
@Test
public void givenPropertyValue_whenXMLPropertiesFileLoaded_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String iconConfigPath = rootPath + "icons.xml";
Properties iconProps = new Properties();
iconProps.loadFromXML(new FileInputStream(iconConfigPath));
assertEquals("icon1.jpg", iconProps.getProperty("fileIcon"));
}
@Test
public void givenAbsentProperty_whenPropertiesFileLoaded_thenReturnsDefault() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
String appVersion = appProps.getProperty("version");
String appName = appProps.getProperty("name", "defaultName");
String appGroup = appProps.getProperty("group", "baeldung");
String appDownloadAddr = appProps.getProperty("downloadAddr");
assertEquals("1.0", appVersion);
assertEquals("TestApp", appName);
assertEquals("baeldung", appGroup);
assertNull(appDownloadAddr);
}
@Test(expected = Exception.class)
public void givenImproperObjectCasting_whenPropertiesFileLoaded_thenThrowsException() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
float appVerFloat = (float) appProps.get("version");
}
@Test
public void givenPropertyValue_whenPropertiesSet_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
appProps.setProperty("name", "NewAppName");
appProps.setProperty("downloadAddr", "www.baeldung.com/downloads");
String newAppName = appProps.getProperty("name");
assertEquals("NewAppName", newAppName);
String newAppDownloadAddr = appProps.getProperty("downloadAddr");
assertEquals("www.baeldung.com/downloads", newAppDownloadAddr);
}
@Test
public void givenPropertyValueNull_whenPropertiesRemoved_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
String versionBeforeRemoval = appProps.getProperty("version");
assertEquals("1.0", versionBeforeRemoval);
appProps.remove("version");
String versionAfterRemoval = appProps.getProperty("version");
assertNull(versionAfterRemoval);
}
@Test
public void whenPropertiesStoredInFile_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));
String newAppConfigPropertiesFile = rootPath + "newApp.properties";
appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file");
String newAppConfigXmlFile = rootPath + "newApp.xml";
appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file");
}
@Test
public void givenPropertyValueAbsent_LoadsValuesFromDefaultProperties() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String defaultConfigPath = rootPath + "default.properties";
Properties defaultProps = new Properties();
defaultProps.load(new FileInputStream(defaultConfigPath));
String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties(defaultProps);
appProps.load(new FileInputStream(appConfigPath));
String appName = appProps.getProperty("name");
String appVersion = appProps.getProperty("version");
String defaultSite = appProps.getProperty("site");
assertEquals("1.0", appVersion);
assertEquals("TestApp", appName);
assertEquals("www.google.com", defaultSite);
}
@Test
public void givenPropertiesSize_whenPropertyFileLoaded_thenCorrect() throws IOException {
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appPropsPath = rootPath + "app.properties";
Properties appProps = new Properties();
appProps.load(new FileInputStream(appPropsPath));
appProps.list(System.out); // list all key-value pairs
Enumeration<Object> valueEnumeration = appProps.elements();
while (valueEnumeration.hasMoreElements()) {
System.out.println(valueEnumeration.nextElement());
}
Enumeration<Object> keyEnumeration = appProps.keys();
while (keyEnumeration.hasMoreElements()) {
System.out.println(keyEnumeration.nextElement());
}
int size = appProps.size();
assertEquals(3, size);
}
}

View File

@ -0,0 +1,3 @@
version=1.0
name=TestApp
date=2016-11-12

View File

@ -0,0 +1,3 @@
c1=files
c2=images
c3=videos

View File

@ -0,0 +1,4 @@
site=www.google.com
name=DefaultAppName
topic=Properties
category=core-java

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>xml example</comment>
<entry key="fileIcon">icon1.jpg</entry>
<entry key="imageIcon">icon2.jpg</entry>
<entry key="videoIcon">icon3.jpg</entry>
</properties>

View File

@ -72,6 +72,17 @@
<artifactId>injekt-core</artifactId>
<version>1.16.1</version>
</dependency>
<dependency>
<groupId>uy.kohesive.kovert</groupId>
<artifactId>kovert-vertx</artifactId>
<version>[1.5.0,1.6.0)</version>
<exclusions>
<exclusion>
<groupId>nl.komponents.kovenant</groupId>
<artifactId>kovenant</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,73 @@
package com.baeldung.kovert
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.core.HttpVerb
import uy.kohesive.kovert.core.Location
import uy.kohesive.kovert.core.Verb
import uy.kohesive.kovert.core.VerbAlias
import uy.kohesive.kovert.vertx.bindController
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class AnnotatedServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(AnnotatedServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
AnnotatedServer().start()
}
}
@VerbAlias("show", HttpVerb.GET)
class AnnotatedController {
fun RoutingContext.showStringById(id: String) = id
@Verb(HttpVerb.GET)
@Location("/ping/:id")
fun RoutingContext.ping(id: String) = id
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", AnnotatedServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
bindController(AnnotatedController(), "api")
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}

View File

@ -0,0 +1,75 @@
package com.baeldung.kovert
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.core.HttpErrorCode
import uy.kohesive.kovert.core.HttpErrorCodeWithBody
import uy.kohesive.kovert.core.HttpErrorForbidden
import uy.kohesive.kovert.vertx.bindController
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class ErrorServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(ErrorServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
ErrorServer().start()
}
}
class ErrorController {
fun RoutingContext.getForbidden() {
throw HttpErrorForbidden()
}
fun RoutingContext.getError() {
throw HttpErrorCode("Something went wrong", 590)
}
fun RoutingContext.getErrorbody() {
throw HttpErrorCodeWithBody("Something went wrong", 591, "Body here")
}
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", ErrorServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
bindController(ErrorController(), "api")
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.kovert
import com.fasterxml.jackson.annotation.JsonProperty
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.vertx.bindController
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class JsonServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(JsonServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
JsonServer().start()
}
}
data class Person(
@JsonProperty("_id")
val id: String,
val name: String,
val job: String
)
class JsonController {
fun RoutingContext.getPersonById(id: String) = Person(
id = id,
name = "Tony Stark",
job = "Iron Man"
)
fun RoutingContext.putPersonById(id: String, person: Person) = person
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", JsonServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
bindController(JsonController(), "api")
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.kovert
import io.vertx.ext.web.Router
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class NoopServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(NoopServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
NoopServer().start()
}
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", NoopServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.kovert
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.vertx.bindController
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class SecuredServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(SecuredServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
SecuredServer().start()
}
}
class SecuredContext(private val routingContext: RoutingContext) {
val authenticated = routingContext.request().getHeader("Authorization") == "Secure"
}
class SecuredController {
fun SecuredContext.getSecured() = this.authenticated
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SecuredServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
bindController(SecuredController(), "api")
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.kovert
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.vertx.bindController
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class SimpleServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(SimpleServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
SimpleServer().start()
}
}
class SimpleController {
fun RoutingContext.getStringById(id: String) = id
fun RoutingContext.get_truncatedString_by_id(id: String, length: Int = 1) = id.subSequence(0, length)
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SimpleServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
bindController(SimpleController(), "api")
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}

View File

@ -0,0 +1,15 @@
{
kovert: {
vertx: {
clustered: false
}
server: {
listeners: [
{
host: "0.0.0.0"
port: "8000"
}
]
}
}
}

View File

@ -2,4 +2,4 @@
This is a sample project for the [deeplearning4j](https://deeplearning4j.org) library.
### Relevant Articles:
- [A Guide to deeplearning4j](http://www.baeldung.com/deeplearning4j)
- [A Guide to Deeplearning4j](http://www.baeldung.com/deeplearning4j)

View File

@ -1,2 +0,0 @@
### Relevant Articles:
- [Guide to Flips For Spring](http://www.baeldung.com/guide-to-flips-for-spring/)

View File

@ -1,65 +0,0 @@
<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>flips</groupId>
<artifactId>flips</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>flips</name>
<parent>
<artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot-starter-web.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot-starter-test.version}</version>
</dependency>
<dependency>
<groupId>com.github.feature-flip</groupId>
<artifactId>flips-web</artifactId>
<version>${flips-web.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<!-- Check for the most recent available version: https://projectlombok.org/changelog.html -->
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<spring-boot-starter-web.version>1.5.10.RELEASE</spring-boot-starter-web.version>
<spring-boot-starter-test.version>1.5.9.RELEASE</spring-boot-starter-test.version>
<flips-web.version>1.0.1</flips-web.version>
<lombok.version>1.16.18</lombok.version>
</properties>
</project>

View File

@ -1,15 +0,0 @@
package com.baeldung.flips;
import org.flips.describe.config.FlipWebContextConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
@SpringBootApplication
@Import(FlipWebContextConfiguration.class)
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run(ApplicationConfig.class, args);
}
}

View File

@ -1,65 +0,0 @@
package com.baeldung.flips.controller;
import com.baeldung.flips.model.Foo;
import com.baeldung.flips.service.FlipService;
import org.flips.annotation.FlipOnDateTime;
import org.flips.annotation.FlipOnDaysOfWeek;
import org.flips.annotation.FlipOnEnvironmentProperty;
import org.flips.annotation.FlipOnProfiles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.time.DayOfWeek;
import java.util.List;
@RestController
public class FlipController {
private FlipService flipService;
@Autowired
public FlipController(FlipService flipService) {
this.flipService = flipService;
}
@RequestMapping(value = "/foos", method = RequestMethod.GET)
@FlipOnProfiles(activeProfiles = "dev")
public List<Foo> getAllFoos() {
return flipService.getAllFoos();
}
@RequestMapping(value = "/foo/{id}", method = RequestMethod.GET)
@FlipOnDaysOfWeek(daysOfWeek = {
DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY,
DayOfWeek.FRIDAY, DayOfWeek.SATURDAY, DayOfWeek.SUNDAY
})
public Foo getFooByNewId(@PathVariable int id) {
return flipService.getFooById(id).orElse(new Foo("Not Found", -1));
}
@RequestMapping(value = "/foo/last", method = RequestMethod.GET)
@FlipOnDateTime(cutoffDateTimeProperty = "last.active.after")
public Foo getLastFoo() {
return flipService.getLastFoo();
}
@RequestMapping(value = "/foo/first", method = RequestMethod.GET)
@FlipOnDateTime(cutoffDateTimeProperty = "first.active.after")
public Foo getFirstFoo() {
return flipService.getLastFoo();
}
@RequestMapping(value = "/foos/{id}", method = RequestMethod.GET)
@FlipOnEnvironmentProperty(property = "feature.foo.by.id", expectedValue = "Y")
public Foo getFooById(@PathVariable int id) {
return flipService.getFooById(id).orElse(new Foo("Not Found", -1));
}
@RequestMapping(value = "/foo/new", method = RequestMethod.GET)
public Foo getNewThing() {
return flipService.getNewFoo();
}
}

View File

@ -1,12 +0,0 @@
package com.baeldung.flips.model;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@Data
@RequiredArgsConstructor
public class Foo {
@NonNull private final String name;
@NonNull private final int id;
}

View File

@ -1,50 +0,0 @@
package com.baeldung.flips.service;
import com.baeldung.flips.model.Foo;
import org.flips.annotation.FlipBean;
import org.flips.annotation.FlipOnSpringExpression;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class FlipService {
private final List<Foo> foos;
public FlipService() {
foos = new ArrayList<>();
foos.add(new Foo("Foo1", 1));
foos.add(new Foo("Foo2", 2));
foos.add(new Foo("Foo3", 3));
foos.add(new Foo("Foo4", 4));
foos.add(new Foo("Foo5", 5));
foos.add(new Foo("Foo6", 6));
}
public List<Foo> getAllFoos() {
return foos;
}
public Optional<Foo> getFooById(int id) {
return foos.stream().filter(foo -> (foo.getId() == id)).findFirst();
}
@FlipBean(with = NewFlipService.class)
@FlipOnSpringExpression(expression = "(2 + 2) == 4")
public Foo getNewFoo() {
return new Foo("New Foo!", 99);
}
public Foo getLastFoo() {
return foos.get(foos.size() - 1);
}
public Foo getFirstFoo() {
return foos.get(0);
}
}

View File

@ -1,13 +0,0 @@
package com.baeldung.flips.service;
import com.baeldung.flips.model.Foo;
import org.springframework.stereotype.Service;
@Service
public class NewFlipService {
public Foo getNewFoo() {
return new Foo("Shiny New Foo!", 100);
}
}

View File

@ -1,5 +0,0 @@
feature.foo.by.id=Y
feature.new.foo=Y
last.active.after=2018-03-14T00:00:00Z
first.active.after=2999-03-15T00:00:00Z
logging.level.org.flips=info

View File

@ -1,74 +0,0 @@
package com.baeldung.flips.controller;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {
"feature.foo.by.id=Y",
"feature.new.foo=Y",
"last.active.after=2018-03-14T00:00:00Z",
"first.active.after=2999-03-15T00:00:00Z",
"logging.level.org.flips=info"
}, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
@ActiveProfiles("dev")
public class FlipControllerIntegrationTest {
@Autowired private MockMvc mvc;
@Test
public void givenValidDayOfWeek_APIAvailable() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/foo/1"))
.andExpect(MockMvcResultMatchers.status().is(200))
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1")))
.andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1)));
}
@Test
public void givenValidDate_APIAvailable() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/foo/last"))
.andExpect(MockMvcResultMatchers.status().is(200))
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo6")))
.andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(6)));
}
@Test
public void givenInvalidDate_APINotAvailable() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/foo/first"))
.andExpect(MockMvcResultMatchers.status().is(501));
}
@Test
public void givenCorrectProfile_APIAvailable() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/foos"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(6)));
}
@Test
public void givenPropertySet_APIAvailable() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/foos/1"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1")))
.andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1)));
}
@Test
public void getValidExpression_FlipBean() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/foo/new"))
.andExpect(MockMvcResultMatchers.status().is(200))
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Shiny New Foo!")))
.andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(100)));
}
}

View File

@ -0,0 +1,228 @@
package com.baeldung.java.map.compare;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapContaining.hasKey;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import com.google.common.base.Equivalence;
import com.google.common.collect.MapDifference;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.Maps;
public class HashMapComparisonUnitTest {
Map<String, String> asiaCapital1;
Map<String, String> asiaCapital2;
Map<String, String> asiaCapital3;
Map<String, String[]> asiaCity1;
Map<String, String[]> asiaCity2;
Map<String, String[]> asiaCity3;
@Before
public void setup(){
asiaCapital1 = new HashMap<String, String>();
asiaCapital1.put("Japan", "Tokyo");
asiaCapital1.put("South Korea", "Seoul");
asiaCapital2 = new HashMap<String, String>();
asiaCapital2.put("South Korea", "Seoul");
asiaCapital2.put("Japan", "Tokyo");
asiaCapital3 = new HashMap<String, String>();
asiaCapital3.put("Japan", "Tokyo");
asiaCapital3.put("China", "Beijing");
asiaCity1 = new HashMap<String, String[]>();
asiaCity1.put("Japan", new String[] { "Tokyo", "Osaka" });
asiaCity1.put("South Korea", new String[] { "Seoul", "Busan" });
asiaCity2 = new HashMap<String, String[]>();
asiaCity2.put("South Korea", new String[] { "Seoul", "Busan" });
asiaCity2.put("Japan", new String[] { "Tokyo", "Osaka" });
asiaCity3 = new HashMap<String, String[]>();
asiaCity3.put("Japan", new String[] { "Tokyo", "Osaka" });
asiaCity3.put("China", new String[] { "Beijing", "Hong Kong" });
}
@Test
public void whenCompareTwoHashMapsUsingEquals_thenSuccess() {
assertTrue(asiaCapital1.equals(asiaCapital2));
assertFalse(asiaCapital1.equals(asiaCapital3));
}
@Test
public void whenCompareTwoHashMapsWithArrayValuesUsingEquals_thenFail() {
assertFalse(asiaCity1.equals(asiaCity2));
}
@Test
public void whenCompareTwoHashMapsUsingStreamAPI_thenSuccess() {
assertTrue(areEqual(asiaCapital1, asiaCapital2));
assertFalse(areEqual(asiaCapital1, asiaCapital3));
}
@Test
public void whenCompareTwoHashMapsWithArrayValuesUsingStreamAPI_thenSuccess() {
assertTrue(areEqualWithArrayValue(asiaCity1, asiaCity2));
assertFalse(areEqualWithArrayValue(asiaCity1, asiaCity3));
}
@Test
public void whenCompareTwoHashMapKeys_thenSuccess() {
assertTrue(asiaCapital1.keySet().equals(asiaCapital2.keySet()));
assertFalse(asiaCapital1.keySet().equals(asiaCapital3.keySet()));
}
@Test
public void whenCompareTwoHashMapKeyValuesUsingStreamAPI_thenSuccess() {
Map<String, String> asiaCapital3 = new HashMap<String, String>();
asiaCapital3.put("Japan", "Tokyo");
asiaCapital3.put("South Korea", "Seoul");
asiaCapital3.put("China", "Beijing");
Map<String, String> asiaCapital4 = new HashMap<String, String>();
asiaCapital4.put("South Korea", "Seoul");
asiaCapital4.put("Japan", "Osaka");
asiaCapital4.put("China", "Beijing");
Map<String, Boolean> result = areEqualKeyValues(asiaCapital3, asiaCapital4);
assertEquals(3, result.size());
assertThat(result, hasEntry("Japan", false));
assertThat(result, hasEntry("South Korea", true));
assertThat(result, hasEntry("China", true));
}
@Test
public void givenDifferentMaps_whenGetDiffUsingGuava_thenSuccess() {
Map<String, String> asia1 = new HashMap<String, String>();
asia1.put("Japan", "Tokyo");
asia1.put("South Korea", "Seoul");
asia1.put("India", "New Delhi");
Map<String, String> asia2 = new HashMap<String, String>();
asia2.put("Japan", "Tokyo");
asia2.put("China", "Beijing");
asia2.put("India", "Delhi");
MapDifference<String, String> diff = Maps.difference(asia1, asia2);
Map<String, ValueDifference<String>> entriesDiffering = diff.entriesDiffering();
assertFalse(diff.areEqual());
assertEquals(1, entriesDiffering.size());
assertThat(entriesDiffering, hasKey("India"));
assertEquals("New Delhi", entriesDiffering.get("India").leftValue());
assertEquals("Delhi", entriesDiffering.get("India").rightValue());
}
@Test
public void givenDifferentMaps_whenGetEntriesOnOneSideUsingGuava_thenSuccess() {
Map<String, String> asia1 = new HashMap<String, String>();
asia1.put("Japan", "Tokyo");
asia1.put("South Korea", "Seoul");
asia1.put("India", "New Delhi");
Map<String, String> asia2 = new HashMap<String, String>();
asia2.put("Japan", "Tokyo");
asia2.put("China", "Beijing");
asia2.put("India", "Delhi");
MapDifference<String, String> diff = Maps.difference(asia1, asia2);
Map<String, String> entriesOnlyOnRight = diff.entriesOnlyOnRight();
Map<String, String> entriesOnlyOnLeft = diff.entriesOnlyOnLeft();
assertEquals(1, entriesOnlyOnRight.size());
assertThat(entriesOnlyOnRight, hasEntry("China", "Beijing"));
assertEquals(1, entriesOnlyOnLeft.size());
assertThat(entriesOnlyOnLeft, hasEntry("South Korea", "Seoul"));
}
@Test
public void givenDifferentMaps_whenGetCommonEntriesUsingGuava_thenSuccess() {
Map<String, String> asia1 = new HashMap<String, String>();
asia1.put("Japan", "Tokyo");
asia1.put("South Korea", "Seoul");
asia1.put("India", "New Delhi");
Map<String, String> asia2 = new HashMap<String, String>();
asia2.put("Japan", "Tokyo");
asia2.put("China", "Beijing");
asia2.put("India", "Delhi");
MapDifference<String, String> diff = Maps.difference(asia1, asia2);
Map<String, String> entriesInCommon = diff.entriesInCommon();
assertEquals(1, entriesInCommon.size());
assertThat(entriesInCommon, hasEntry("Japan", "Tokyo"));
}
@Test
public void givenSimilarMapsWithArrayValue_whenCompareUsingGuava_thenFail() {
MapDifference<String, String[]> diff = Maps.difference(asiaCity1, asiaCity2);
assertFalse(diff.areEqual());
}
@Test
public void givenSimilarMapsWithArrayValue_whenCompareUsingGuavaEquivalence_thenSuccess() {
Equivalence<String[]> eq = new Equivalence<String[]>() {
@Override
protected boolean doEquivalent(String[] a, String[] b) {
return Arrays.equals(a, b);
}
@Override
protected int doHash(String[] value) {
return value.hashCode();
}
};
MapDifference<String, String[]> diff = Maps.difference(asiaCity1, asiaCity2, eq);
assertTrue(diff.areEqual());
diff = Maps.difference(asiaCity1, asiaCity3, eq);
assertFalse(diff.areEqual());
}
// ===========================================================================
private boolean areEqual(Map<String, String> first, Map<String, String> second) {
if (first.size() != second.size()) {
return false;
}
return first.entrySet()
.stream()
.allMatch(e -> e.getValue()
.equals(second.get(e.getKey())));
}
private boolean areEqualWithArrayValue(Map<String, String[]> first, Map<String, String[]> second) {
if (first.size() != second.size()) {
return false;
}
return first.entrySet()
.stream()
.allMatch(e -> Arrays.equals(e.getValue(), second.get(e.getKey())));
}
private Map<String, Boolean> areEqualKeyValues(Map<String, String> first, Map<String, String> second) {
return first.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().equals(second.get(e.getKey()))));
}
}

View File

@ -8,6 +8,7 @@ import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
@ -51,6 +52,16 @@ public class DateDiffUnitTest {
assertEquals(diff, 6);
}
@Test
public void givenTwoDateTimesInJava8_whenDifferentiatingInSeconds_thenWeGetTen() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime tenSecondsLater = now.plusSeconds(10);
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
assertEquals(diff, 10);
}
@Test
public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() {
LocalDateTime ldt = LocalDateTime.now();
@ -60,6 +71,16 @@ public class DateDiffUnitTest {
assertEquals(diff, 6);
}
@Test
public void givenTwoDateTimesInJava8_whenDifferentiatingInSecondsUsingUntil_thenWeGetTen() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime tenSecondsLater = now.plusSeconds(10);
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
assertEquals(diff, 10);
}
@Test
public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() {
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();

View File

@ -1,5 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>java-streams</artifactId>
<version>0.1.0-SNAPSHOT</version>
@ -74,6 +74,11 @@
<artifactId>aspectjweaver</artifactId>
<version>${asspectj.version}</version>
</dependency>
<dependency>
<groupId>pl.touk</groupId>
<artifactId>throwing-function</artifactId>
<version>${throwing-function.version}</version>
</dependency>
</dependencies>
<build>
@ -108,8 +113,9 @@
<protonpack.version>1.15</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<joda.version>2.10</joda.version>
<throwing-function.version>1.3</throwing-function.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<assertj.version>3.11.1</assertj.version>
<asspectj.version>1.8.9</asspectj.version>
</properties>
</project>

View File

@ -0,0 +1,55 @@
package com.baeldung.stream.filter;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Customer {
private String name;
private int points;
private String profilePhotoUrl;
public Customer(String name, int points) {
this(name, points, "");
}
public Customer(String name, int points, String profilePhotoUrl) {
this.name = name;
this.points = points;
this.profilePhotoUrl = profilePhotoUrl;
}
public String getName() {
return name;
}
public int getPoints() {
return points;
}
public boolean hasOver(int points) {
return this.points > points;
}
public boolean hasOverThousandPoints() {
return this.points > 100;
}
public boolean hasValidProfilePhoto() throws IOException {
URL url = new URL(this.profilePhotoUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
}
public boolean hasValidProfilePhotoWithoutCheckedException() {
try {
URL url = new URL(this.profilePhotoUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,159 @@
package com.baeldung.stream.filter;
import org.junit.jupiter.api.Test;
import pl.touk.throwing.ThrowingPredicate;
import pl.touk.throwing.exception.WrappedException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
public class StreamFilterUnitTest {
@Test
public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() {
Customer john = new Customer("John P.", 15);
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1);
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> customersWithMoreThan100Points = customers
.stream()
.filter(c -> c.getPoints() > 100)
.collect(Collectors.toList());
assertThat(customersWithMoreThan100Points).hasSize(2);
assertThat(customersWithMoreThan100Points).contains(sarah, charles);
}
@Test
public void givenListOfCustomers_whenFilterByPointsAndName_thenGetOne() {
Customer john = new Customer("John P.", 15);
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1);
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> charlesWithMoreThan100Points = customers
.stream()
.filter(c -> c.getPoints() > 100 && c
.getName()
.startsWith("Charles"))
.collect(Collectors.toList());
assertThat(charlesWithMoreThan100Points).hasSize(1);
assertThat(charlesWithMoreThan100Points).contains(charles);
}
@Test
public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() {
Customer john = new Customer("John P.", 15);
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1);
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> customersWithMoreThan100Points = customers
.stream()
.filter(Customer::hasOverThousandPoints)
.collect(Collectors.toList());
assertThat(customersWithMoreThan100Points).hasSize(2);
assertThat(customersWithMoreThan100Points).contains(sarah, charles);
}
@Test
public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() {
Optional<Customer> john = Optional.of(new Customer("John P.", 15));
Optional<Customer> sarah = Optional.of(new Customer("Sarah M.", 200));
Optional<Customer> mary = Optional.of(new Customer("Mary T.", 300));
List<Optional<Customer>> customers = Arrays.asList(john, sarah, Optional.empty(), mary, Optional.empty());
List<Customer> customersWithMoreThan100Points = customers
.stream()
.flatMap(c -> c
.map(Stream::of)
.orElseGet(Stream::empty))
.filter(Customer::hasOverThousandPoints)
.collect(Collectors.toList());
assertThat(customersWithMoreThan100Points).hasSize(2);
assertThat(customersWithMoreThan100Points).contains(sarah.get(), mary.get());
}
@Test
public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
assertThatThrownBy(() -> customers
.stream()
.filter(Customer::hasValidProfilePhotoWithoutCheckedException)
.count()).isInstanceOf(RuntimeException.class);
}
@Test
public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
assertThatThrownBy(() -> customers
.stream()
.filter((ThrowingPredicate.unchecked(Customer::hasValidProfilePhoto)))
.collect(Collectors.toList())).isInstanceOf(WrappedException.class);
}
@Test
public void givenListOfCustomers_whenFilterWithTryCatch_thenGetTwo() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150);
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
List<Customer> customersWithValidProfilePhoto = customers
.stream()
.filter(c -> {
try {
return c.hasValidProfilePhoto();
} catch (IOException e) {
//handle exception
}
return false;
})
.collect(Collectors.toList());
assertThat(customersWithValidProfilePhoto).hasSize(2);
assertThat(customersWithValidProfilePhoto).contains(john, mary);
}
@Test
public void givenListOfCustomers_whenFilterWithTryCatchAndRuntime_thenThrowException() {
List<Customer> customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150),
new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"));
assertThatThrownBy(() -> customers
.stream()
.filter(c -> {
try {
return c.hasValidProfilePhoto();
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.toList())).isInstanceOf(RuntimeException.class);
}
}

View File

@ -0,0 +1,135 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
public class ConvertStringToListUnitTest {
private final String countries = "Russia,Germany,England,France,Italy";
private final String ranks = "1,2,3,4,5, 6,7";
private final String emptyStrings = ",,,,,";
private final List<String> expectedCountriesList = Arrays.asList("Russia", "Germany", "England", "France", "Italy");
private final List<Integer> expectedRanksList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
private final List<String> expectedEmptyStringsList = Arrays.asList("", "", "", "", "", "");
@Test
public void givenString_thenGetListOfStringByJava() {
List<String> convertedCountriesList = Arrays.asList(countries.split(",", -1));
assertEquals(expectedCountriesList, convertedCountriesList);
}
@Test
public void givenString_thenGetListOfStringByApache() {
List<String> convertedCountriesList = Arrays.asList(StringUtils.splitPreserveAllTokens(countries, ","));
assertEquals(expectedCountriesList, convertedCountriesList);
}
@Test
public void givenString_thenGetListOfStringByGuava() {
List<String> convertedCountriesList = Splitter.on(",")
.trimResults()
.splitToList(countries);
assertEquals(expectedCountriesList, convertedCountriesList);
}
@Test
public void givenString_thenGetListOfStringByJava8() {
List<String> convertedCountriesList = Stream.of(countries.split(",", -1))
.collect(Collectors.toList());
assertEquals(expectedCountriesList, convertedCountriesList);
}
@Test
public void givenString_thenGetListOfIntegerByJava() {
String[] convertedRankArray = ranks.split(",");
List<Integer> convertedRankList = new ArrayList<Integer>();
for (String number : convertedRankArray) {
convertedRankList.add(Integer.parseInt(number.trim()));
}
assertEquals(expectedRanksList, convertedRankList);
}
@Test
public void givenString_thenGetListOfIntegerByGuava() {
List<Integer> convertedRankList = Lists.transform(Splitter.on(",")
.trimResults()
.splitToList(ranks), new Function<String, Integer>() {
@Override
public Integer apply(String input) {
return Integer.parseInt(input.trim());
}
});
assertEquals(expectedRanksList, convertedRankList);
}
@Test
public void givenString_thenGetListOfIntegerByJava8() {
List<Integer> convertedRankList = Stream.of(ranks.split(","))
.map(String::trim)
.map(Integer::parseInt)
.collect(Collectors.toList());
assertEquals(expectedRanksList, convertedRankList);
}
@Test
public void givenString_thenGetListOfIntegerByApache() {
String[] convertedRankArray = StringUtils.split(ranks, ",");
List<Integer> convertedRankList = new ArrayList<Integer>();
for (String number : convertedRankArray) {
convertedRankList.add(Integer.parseInt(number.trim()));
}
assertEquals(expectedRanksList, convertedRankList);
}
@Test
public void givenEmptyStrings_thenGetListOfStringByJava() {
List<String> convertedEmptyStringsList = Arrays.asList(emptyStrings.split(",", -1));
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
}
@Test
public void givenEmptyStrings_thenGetListOfStringByApache() {
List<String> convertedEmptyStringsList = Arrays.asList(StringUtils.splitPreserveAllTokens(emptyStrings, ","));
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
}
@Test
public void givenEmptyStrings_thenGetListOfStringByGuava() {
List<String> convertedEmptyStringsList = Splitter.on(",")
.trimResults()
.splitToList(emptyStrings);
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
}
@Test
public void givenEmptyStrings_thenGetListOfStringByJava8() {
List<String> convertedEmptyStringsList = Stream.of(emptyStrings.split(",", -1))
.collect(Collectors.toList());
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
}
}

View File

@ -1,7 +1,5 @@
### Relevant articles
- [Intro to JHipster](http://www.baeldung.com/jhipster)
# baeldung
This application was generated using JHipster 4.0.8, you can find documentation and help at [https://jhipster.github.io/documentation-archive/v4.0.8](https://jhipster.github.io/documentation-archive/v4.0.8).

View File

@ -33,6 +33,16 @@
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>javax.json.bind</groupId>

View File

@ -0,0 +1,41 @@
package com.baeldung.escape;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import org.json.JSONObject;
class JsonEscape {
String escapeJson(String input) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", input);
return jsonObject.toString();
}
String escapeGson(String input) {
JsonObject gsonObject = new JsonObject();
gsonObject.addProperty("message", input);
return gsonObject.toString();
}
String escapeJackson(String input) throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(new Payload(input));
}
static class Payload {
String message;
Payload(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.escape;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class JsonEscapeUnitTest {
private JsonEscape testedInstance;
private static final String EXPECTED = "{\"message\":\"Hello \\\"World\\\"\"}";
@BeforeEach
void setUp() {
testedInstance = new JsonEscape();
}
@Test
void escapeJson() {
String actual = testedInstance.escapeJson("Hello \"World\"");
assertEquals(EXPECTED, actual);
}
@Test
void escapeGson() {
String actual = testedInstance.escapeGson("Hello \"World\"");
assertEquals(EXPECTED, actual);
}
@Test
void escapeJackson() throws JsonProcessingException {
String actual = testedInstance.escapeJackson("Hello \"World\"");
assertEquals(EXPECTED, actual);
}
}

View File

@ -658,6 +658,12 @@
<version>${suanshu.version}</version>
</dependency>
<dependency>
<groupId>org.derive4j</groupId>
<artifactId>derive4j</artifactId>
<version>${derive4j.version}</version>
<optional>true</optional>
</dependency>
</dependencies>
<repositories>
@ -881,6 +887,7 @@
<fugue.version>4.5.1</fugue.version>
<maven-bundle-plugin.version>3.3.0</maven-bundle-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<derive4j.version>1.1.0</derive4j.version>
</properties>
</project>

View File

@ -0,0 +1,10 @@
package com.baeldung.derive4j.adt;
import org.derive4j.Data;
import java.util.function.Function;
@Data
interface Either<A,B>{
<X> X match(Function<A, X> left, Function<B, X> right);
}

View File

@ -0,0 +1,21 @@
package com.baeldung.derive4j.lazy;
import org.derive4j.Data;
import org.derive4j.Derive;
import org.derive4j.Make;
@Data(value = @Derive(
inClass = "{ClassName}Impl",
make = {Make.lazyConstructor, Make.constructors}
))
public interface LazyRequest {
interface Cases<R>{
R GET(String path);
R POST(String path, String body);
R PUT(String path, String body);
R DELETE(String path);
}
<R> R match(LazyRequest.Cases<R> method);
}

View File

@ -0,0 +1,15 @@
package com.baeldung.derive4j.pattern;
import org.derive4j.Data;
@Data
interface HTTPRequest {
interface Cases<R>{
R GET(String path);
R POST(String path, String body);
R PUT(String path, String body);
R DELETE(String path);
}
<R> R match(Cases<R> method);
}

View File

@ -0,0 +1,19 @@
package com.baeldung.derive4j.pattern;
public class HTTPResponse {
private int statusCode;
private String responseBody;
public int getStatusCode() {
return statusCode;
}
public String getResponseBody() {
return responseBody;
}
public HTTPResponse(int statusCode, String responseBody) {
this.statusCode = statusCode;
this.responseBody = responseBody;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.derive4j.pattern;
public class HTTPServer {
public static String GET_RESPONSE_BODY = "Success!";
public static String PUT_RESPONSE_BODY = "Resource Created!";
public static String POST_RESPONSE_BODY = "Resource Updated!";
public static String DELETE_RESPONSE_BODY = "Resource Deleted!";
public HTTPResponse acceptRequest(HTTPRequest request) {
return HTTPRequests.caseOf(request)
.GET((path) -> new HTTPResponse(200, GET_RESPONSE_BODY))
.POST((path,body) -> new HTTPResponse(201, POST_RESPONSE_BODY))
.PUT((path,body) -> new HTTPResponse(200, PUT_RESPONSE_BODY))
.DELETE(path -> new HTTPResponse(200, DELETE_RESPONSE_BODY));
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.derive4j.adt;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Optional;
import java.util.function.Function;
@RunWith(MockitoJUnitRunner.class)
public class EitherUnitTest {
@Test
public void testEitherIsCreatedFromRight() {
Either<Exception, String> either = Eithers.right("Okay");
Optional<Exception> leftOptional = Eithers.getLeft(either);
Optional<String> rightOptional = Eithers.getRight(either);
Assertions.assertThat(leftOptional).isEmpty();
Assertions.assertThat(rightOptional).hasValue("Okay");
}
@Test
public void testEitherIsMatchedWithRight() {
Either<Exception, String> either = Eithers.right("Okay");
Function<Exception, String> leftFunction = Mockito.mock(Function.class);
Function<String, String> rightFunction = Mockito.mock(Function.class);
either.match(leftFunction, rightFunction);
Mockito.verify(rightFunction, Mockito.times(1)).apply("Okay");
Mockito.verify(leftFunction, Mockito.times(0)).apply(Mockito.any(Exception.class));
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.derive4j.lazy;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.function.Supplier;
public class LazyRequestUnitTest {
@Test
public void givenLazyContstructedRequest_whenRequestIsReferenced_thenRequestIsLazilyContructed() {
LazyRequestSupplier mockSupplier = Mockito.spy(new LazyRequestSupplier());
LazyRequest request = LazyRequestImpl.lazy(() -> mockSupplier.get());
Mockito.verify(mockSupplier, Mockito.times(0)).get();
Assert.assertEquals(LazyRequestImpl.getPath(request), "http://test.com/get");
Mockito.verify(mockSupplier, Mockito.times(1)).get();
}
class LazyRequestSupplier implements Supplier<LazyRequest> {
@Override
public LazyRequest get() {
return LazyRequestImpl.GET("http://test.com/get");
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.derive4j.pattern;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class HTTPRequestUnitTest {
public static HTTPServer server;
@BeforeClass
public static void setUp() {
server = new HTTPServer();
}
@Test
public void givenHttpGETRequest_whenRequestReachesServer_thenProperResponseIsReturned() {
HTTPRequest postRequest = HTTPRequests.POST("http://test.com/post", "Resource");
HTTPResponse response = server.acceptRequest(postRequest);
Assert.assertEquals(201, response.getStatusCode());
Assert.assertEquals(HTTPServer.POST_RESPONSE_BODY, response.getResponseBody());
}
}

View File

@ -1,6 +1,8 @@
package com.baeldung.fj;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
@ -30,7 +32,7 @@ public class FunctionalJavaUnitTest {
List<Integer> fList1 = fList.map(timesTwo);
List<Integer> fList2 = fList.map(i -> i * 2);
assertEquals(fList1.equals(fList2), true);
assertTrue(fList1.equals(fList2));
}
@Test
@ -41,7 +43,7 @@ public class FunctionalJavaUnitTest {
List<Integer> fList2 = fList.map(plusOne).map(timesTwo);
Show.listShow(Show.intShow).println(fList2);
assertEquals(fList1.equals(fList2), false);
assertFalse(fList1.equals(fList2));
}
@Test
@ -49,10 +51,8 @@ public class FunctionalJavaUnitTest {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
List<Boolean> evenListTrueResult = List.list(false, true, false, true);
List<Boolean> evenListFalseResult = List.list(true, false, false, true);
assertEquals(evenList.equals(evenListTrueResult), true);
assertEquals(evenList.equals(evenListFalseResult), false);
assertTrue(evenList.equals(evenListTrueResult));
}
@Test
@ -60,10 +60,8 @@ public class FunctionalJavaUnitTest {
List<Integer> fList = List.list(3, 4, 5, 6);
fList = fList.map(i -> i + 100);
List<Integer> resultList = List.list(103, 104, 105, 106);
List<Integer> falseResultList = List.list(15, 504, 105, 106);
assertEquals(fList.equals(resultList), true);
assertEquals(fList.equals(falseResultList), false);
assertTrue(fList.equals(resultList));
}
@Test
@ -71,23 +69,19 @@ public class FunctionalJavaUnitTest {
Array<Integer> array = Array.array(3, 4, 5, 6);
Array<Integer> filteredArray = array.filter(isEven);
Array<Integer> result = Array.array(4, 6);
Array<Integer> wrongResult = Array.array(3, 5);
assertEquals(filteredArray.equals(result), true);
assertEquals(filteredArray.equals(wrongResult), false);
assertTrue(filteredArray.equals(result));
}
@Test
public void checkForLowerCase_givenStringArray_returnResult() {
Array<String> array = Array.array("Welcome", "To", "baeldung");
assertTrue(array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)));
Array<String> array2 = Array.array("Welcome", "To", "Baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
Boolean isAll = array.forall(s -> List.fromString(s).forall(Characters.isLowerCase));
assertEquals(isExist, true);
assertEquals(isExist2, false);
assertEquals(isAll, false);
assertFalse(array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase)));
assertFalse(array.forall(s -> List.fromString(s).forall(Characters.isLowerCase)));
}
@Test
@ -102,9 +96,9 @@ public class FunctionalJavaUnitTest {
Option<Integer> result2 = n2.bind(function);
Option<Integer> result3 = n3.bind(function);
assertEquals(result1, Option.none());
assertEquals(result2, Option.some(102));
assertEquals(result3, Option.none());
assertEquals(Option.none(), result1);
assertEquals(Option.some(102), result2);
assertEquals(Option.none(), result3);
}
@Test
@ -112,11 +106,11 @@ public class FunctionalJavaUnitTest {
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sumAll = intArray.foldLeft(Integers.add, 0);
assertEquals(sumAll, 260);
assertEquals(260, sumAll);
int sumEven = intArray.filter(isEven).foldLeft(Integers.add, 0);
assertEquals(sumEven, 148);
assertEquals(148, sumEven);
}
}

View File

@ -1,2 +0,0 @@
This pom will be ued only temporary until we migrate parent-boot-2 to 2.1.0 for ticket BAEL-10354

View File

@ -1,85 +0,0 @@
<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>parent-boot-2.0-temp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<description>Temporary Parent for all Spring Boot 2.0.x modules</description>
<!-- This pom will be ued only temporary until we migrate parent-boot-2 to 2.1.0 for ticket BAEL-10354 -->
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>${start-class}</mainClass>
<!-- this is necessary as we're not using the Boot parent -->
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<profile>
<id>thin-jar</id>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<!-- The following enables the "thin jar" deployment option. -->
<dependency>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-thin-layout</artifactId>
<version>${thin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<rest-assured.version>3.1.0</rest-assured.version>
<!-- plugins -->
<thin.version>1.0.11.RELEASE</thin.version>
<spring-boot.version>2.0.5.RELEASE</spring-boot.version>
</properties>
</project>

View File

@ -0,0 +1,4 @@
## Relevant articles:
- [Guide to Hibernate OGM](http://www.baeldung.com/xxxx)

View File

@ -0,0 +1,60 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>hibernate-ogm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hibernate-ogm</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<!-- MongoDB -->
<dependency>
<groupId>org.hibernate.ogm</groupId>
<artifactId>hibernate-ogm-mongodb</artifactId>
<version>5.4.0.Final</version>
</dependency>
<!-- Neo4j -->
<dependency>
<groupId>org.hibernate.ogm</groupId>
<artifactId>hibernate-ogm-neo4j</artifactId>
<version>5.4.0.Final</version>
</dependency>
<!-- Narayana JTA -->
<dependency>
<groupId>org.jboss.narayana.jta</groupId>
<artifactId>narayana-jta</artifactId>
<version>5.5.23.Final</version>
</dependency>
<!-- Testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<version>1.4</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>hibernate-ogm</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,54 @@
package com.baeldung.hibernate.ogm;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.GenericGenerator;
@Entity
public class Article {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String articleId;
private String articleTitle;
@ManyToOne
private Author author;
// constructors, getters and setters...
Article() {
}
public Article(String articleTitle) {
this.articleTitle = articleTitle;
}
public String getArticleId() {
return articleId;
}
public void setArticleId(String articleId) {
this.articleId = articleId;
}
public String getArticleTitle() {
return articleTitle;
}
public void setArticleTitle(String articleTitle) {
this.articleTitle = articleTitle;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.hibernate.ogm;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import org.hibernate.annotations.GenericGenerator;
@Entity
public class Author {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String authorId;
private String authorName;
@ManyToOne
private Editor editor;
@OneToMany(mappedBy = "author", cascade = CascadeType.PERSIST)
private Set<Article> authoredArticles = new HashSet<>();
// constructors, getters and setters...
Author() {
}
public Author(String authorName) {
this.authorName = authorName;
}
public String getAuthorId() {
return authorId;
}
public void setAuthorId(String authorId) {
this.authorId = authorId;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public Editor getEditor() {
return editor;
}
public void setEditor(Editor editor) {
this.editor = editor;
}
public Set<Article> getAuthoredArticles() {
return authoredArticles;
}
public void setAuthoredArticles(Set<Article> authoredArticles) {
this.authoredArticles = authoredArticles;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.hibernate.ogm;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.hibernate.annotations.GenericGenerator;
@Entity
public class Editor {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String editorId;
private String editorName;
@OneToMany(mappedBy = "editor", cascade = CascadeType.PERSIST)
private Set<Author> assignedAuthors = new HashSet<>();
// constructors, getters and setters...
Editor() {
}
public Editor(String editorName) {
this.editorName = editorName;
}
public String getEditorId() {
return editorId;
}
public void setEditorId(String editorId) {
this.editorId = editorId;
}
public String getEditorName() {
return editorName;
}
public void setEditorName(String editorName) {
this.editorName = editorName;
}
public Set<Author> getAssignedAuthors() {
return assignedAuthors;
}
public void setAssignedAuthors(Set<Author> assignedAuthors) {
this.assignedAuthors = assignedAuthors;
}
}

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<!-- MongoDB -->
<persistence-unit name="ogm-mongodb" transaction-type="JTA">
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<properties>
<property name="hibernate.ogm.datastore.provider" value="MONGODB" />
<property name="hibernate.ogm.datastore.database" value="TestDB" />
<property name="hibernate.ogm.datastore.create_database" value="true" />
</properties>
</persistence-unit>
<!-- Neo4j -->
<persistence-unit name="ogm-neo4j" transaction-type="JTA">
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<properties>
<property name="hibernate.ogm.datastore.provider" value="NEO4J_EMBEDDED" />
<property name="hibernate.ogm.datastore.database" value="TestDB" />
<property name="hibernate.ogm.neo4j.database_path" value="target/test_data_dir" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,92 @@
package com.baeldung.hibernate.ogm;
import static org.fest.assertions.Assertions.assertThat;
import java.util.Map;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.transaction.TransactionManager;
import org.junit.Test;
public class EditorUnitTest {
/*
@Test
public void givenMongoDB_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-mongodb");
Editor editor = generateTestData();
persistTestData(entityManagerFactory, editor);
loadAndVerifyTestData(entityManagerFactory, editor);
}
*/
@Test
public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j");
Editor editor = generateTestData();
persistTestData(entityManagerFactory, editor);
loadAndVerifyTestData(entityManagerFactory, editor);
}
private void persistTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception {
TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager();
EntityManager entityManager;
transactionManager.begin();
entityManager = entityManagerFactory.createEntityManager();
entityManager.persist(editor);
entityManager.close();
transactionManager.commit();
}
private void loadAndVerifyTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception {
TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager();
EntityManager entityManager;
transactionManager.begin();
entityManager = entityManagerFactory.createEntityManager();
Editor loadedEditor = entityManager.find(Editor.class, editor.getEditorId());
assertThat(loadedEditor).isNotNull();
assertThat(loadedEditor.getEditorName()).isEqualTo("Tom");
assertThat(loadedEditor.getAssignedAuthors()).onProperty("authorName")
.containsOnly("Maria", "Mike");
Map<String, Author> loadedAuthors = loadedEditor.getAssignedAuthors()
.stream()
.collect(Collectors.toMap(Author::getAuthorName, e -> e));
assertThat(loadedAuthors.get("Maria")
.getAuthoredArticles()).onProperty("articleTitle")
.containsOnly("Basic of Hibernate OGM");
assertThat(loadedAuthors.get("Mike")
.getAuthoredArticles()).onProperty("articleTitle")
.containsOnly("Intermediate of Hibernate OGM", "Advanced of Hibernate OGM");
entityManager.close();
transactionManager.commit();
}
private Editor generateTestData() {
Editor tom = new Editor("Tom");
Author maria = new Author("Maria");
Author mike = new Author("Mike");
Article basic = new Article("Basic of Hibernate OGM");
Article intermediate = new Article("Intermediate of Hibernate OGM");
Article advanced = new Article("Advanced of Hibernate OGM");
maria.getAuthoredArticles()
.add(basic);
basic.setAuthor(maria);
mike.getAuthoredArticles()
.add(intermediate);
intermediate.setAuthor(mike);
mike.getAuthoredArticles()
.add(advanced);
advanced.setAuthor(mike);
tom.getAssignedAuthors()
.add(maria);
maria.setEditor(tom);
tom.getAssignedAuthors()
.add(mike);
mike.setEditor(tom);
return tom;
}
}

View File

@ -36,6 +36,11 @@
<artifactId>hibernate-spatial</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
@ -51,6 +56,16 @@
<artifactId>hibernate-testing</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.9.5</version>
</dependency>
</dependencies>
<build>
@ -69,6 +84,7 @@
<mariaDB4j.version>2.2.3</mariaDB4j.version>
<h2database.version>1.4.196</h2database.version>
<assertj-core.version>3.8.0</assertj-core.version>
<jackson.version>2.8.11.3</jackson.version>
</properties>
</project>

View File

@ -0,0 +1,114 @@
package com.baeldung.hibernate.operations;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.baeldung.hibernate.pojo.Movie;
/**
*
*Class to illustrate the usage of EntityManager API.
*/
public class HibernateOperations {
private static final EntityManagerFactory emf;
/**
* Static block for creating EntityManagerFactory. The Persistence class looks for META-INF/persistence.xml in the classpath.
*/
static {
emf = Persistence.createEntityManagerFactory("com.baeldung.movie_catalog");
}
/**
* Static method returning EntityManager.
* @return EntityManager
*/
public static EntityManager getEntityManager() {
return emf.createEntityManager();
}
/**
* Saves the movie entity into the database. Here we are using Application Managed EntityManager, hence should handle transactions by ourselves.
*/
public void saveMovie() {
EntityManager em = HibernateOperations.getEntityManager();
em.getTransaction()
.begin();
Movie movie = new Movie();
movie.setId(1L);
movie.setMovieName("The Godfather");
movie.setReleaseYear(1972);
movie.setLanguage("English");
em.persist(movie);
em.getTransaction()
.commit();
}
/**
* Method to illustrate the querying support in EntityManager when the result is a single object.
* @return Movie
*/
public Movie queryForMovieById() {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = (Movie) em.createQuery("SELECT movie from Movie movie where movie.id = ?1")
.setParameter(1, new Long(1L))
.getSingleResult();
return movie;
}
/**
* Method to illustrate the querying support in EntityManager when the result is a list.
* @return
*/
public List<?> queryForMovies() {
EntityManager em = HibernateOperations.getEntityManager();
List<?> movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1")
.setParameter(1, "English")
.getResultList();
return movies;
}
/**
* Method to illustrate the usage of find() method.
* @param movieId
* @return Movie
*/
public Movie getMovie(Long movieId) {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = em.find(Movie.class, new Long(movieId));
return movie;
}
/**
* Method to illustrate the usage of merge() function.
*/
public void mergeMovie() {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = getMovie(1L);
em.detach(movie);
movie.setLanguage("Italian");
em.getTransaction()
.begin();
em.merge(movie);
em.getTransaction()
.commit();
}
/**
* Method to illustrate the usage of remove() function.
*/
public void removeMovie() {
EntityManager em = HibernateOperations.getEntityManager();
em.getTransaction()
.begin();
Movie movie = em.find(Movie.class, new Long(1L));
em.remove(movie);
em.getTransaction()
.commit();
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.hibernate.persistjson;
import java.io.IOException;
import java.util.Map;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Entity
@Table(name = "Customers")
public class Customer {
@Id
private int id;
private String firstName;
private String lastName;
private String customerAttributeJSON;
@Convert(converter = HashMapConverter.class)
private Map<String, Object> customerAttributes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCustomerAttributeJSON() {
return customerAttributeJSON;
}
public void setCustomerAttributeJSON(String customerAttributeJSON) {
this.customerAttributeJSON = customerAttributeJSON;
}
public Map<String, Object> getCustomerAttributes() {
return customerAttributes;
}
public void setCustomerAttributes(Map<String, Object> customerAttributes) {
this.customerAttributes = customerAttributes;
}
private static final ObjectMapper objectMapper = new ObjectMapper();
public void serializeCustomerAttributes() throws JsonProcessingException {
this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes);
}
public void deserializeCustomerAttributes() throws IOException {
this.customerAttributes = objectMapper.readValue(customerAttributeJSON, Map.class);
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.hibernate.persistjson;
import java.io.IOException;
import java.util.Map;
import javax.persistence.AttributeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.hibernate.interceptors.CustomInterceptor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HashMapConverter implements AttributeConverter<Map<String, Object>, String> {
private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(Map<String, Object> customerInfo) {
String customerInfoJson = null;
try {
customerInfoJson = objectMapper.writeValueAsString(customerInfo);
} catch (final JsonProcessingException e) {
logger.error("JSON writing error", e);
}
return customerInfoJson;
}
@Override
public Map<String, Object> convertToEntityAttribute(String customerInfoJSON) {
Map<String, Object> customerInfo = null;
try {
customerInfo = objectMapper.readValue(customerInfoJSON, Map.class);
} catch (final IOException e) {
logger.error("JSON reading error", e);
}
return customerInfo;
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "MOVIE")
public class Movie {
@Id
private Long id;
private String movieName;
private Integer releaseYear;
private String language;
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public Integer getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(Integer releaseYear) {
this.releaseYear = releaseYear;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="com.baeldung.movie_catalog">
<description>Hibernate EntityManager Demo</description>
<class>com.baeldung.hibernate.pojo.Movie</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,111 @@
package com.baeldung.hibernate.persistjson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PersistJSONUnitTest {
private Session session;
@Before
public void init() {
try {
Configuration configuration = new Configuration();
Properties properties = new Properties();
properties.load(Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("hibernate-persistjson.properties"));
configuration.setProperties(properties);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
.build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(Customer.class);
SessionFactory factory = metadataSources.buildMetadata()
.buildSessionFactory();
session = factory.openSession();
} catch (HibernateException | IOException e) {
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
}
}
@After
public void close() {
if (session != null)
session.close();
}
@Test
public void givenCustomer_whenCallingSerializeCustomerAttributes_thenAttributesAreConverted() throws IOException {
Customer customer = new Customer();
customer.setFirstName("first name");
customer.setLastName("last name");
Map<String, Object> attributes = new HashMap<>();
attributes.put("address", "123 Main Street");
attributes.put("zipcode", 12345);
customer.setCustomerAttributes(attributes);
customer.serializeCustomerAttributes();
String serialized = customer.getCustomerAttributeJSON();
customer.setCustomerAttributeJSON(serialized);
customer.deserializeCustomerAttributes();
Map<String, Object> deserialized = customer.getCustomerAttributes();
assertEquals("123 Main Street", deserialized.get("address"));
}
@Test
public void givenCustomer_whenSaving_thenAttributesAreConverted() {
Customer customer = new Customer();
customer.setFirstName("first name");
customer.setLastName("last name");
Map<String, Object> attributes = new HashMap<>();
attributes.put("address", "123 Main Street");
attributes.put("zipcode", 12345);
customer.setCustomerAttributes(attributes);
session.beginTransaction();
int id = (int) session.save(customer);
session.flush();
session.clear();
Customer result = session.createNativeQuery("select * from Customers where Customers.id = :id", Customer.class)
.setParameter("id", id)
.getSingleResult();
assertEquals(2, result.getCustomerAttributes()
.size());
}
}

View File

@ -0,0 +1,7 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop

View File

@ -6,4 +6,9 @@ jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.hbm2ddl.auto=create-drop
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=5
hibernate.c3p0.timeout=1800

View File

@ -1,2 +1 @@
### Relevant Articles:
- [Guide to CockroachDB in Java](http://www.baeldung.com/cockroachdb-java)

View File

@ -1,13 +1,12 @@
package com.baeldung.jpa.stringcast;
import com.sun.istack.internal.Nullable;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class QueryExecutor {
public static List<String[]> executeNativeQueryNoCastCheck(String statement, EntityManager em) {
@ -24,10 +23,7 @@ public class QueryExecutor {
}
if (results.get(0) instanceof String) {
return ((List<String>) results)
.stream()
.map(s -> new String[] { s })
.collect(Collectors.toList());
return ((List<String>) results).stream().map(s -> new String[] { s }).collect(Collectors.toList());
} else {
return (List<String[]>) results;
}

View File

@ -1,5 +1,4 @@
### Relevant Articles:
- [Intro to Jedis the Java Redis Client Library](http://www.baeldung.com/jedis-java-redis-client-library)
- [A Guide to Redis with Redisson](http://www.baeldung.com/redis-redisson)
- [Intro to Lettuce the Java Redis Client Library](http://www.baeldung.com/lettuce-java-redis-client-library)
- [Introduction to Lettuce the Java Redis Client](https://www.baeldung.com/java-redis-lettuce)

View File

@ -1,8 +1,13 @@
package com.baeldung.dao.repositories.product;
import com.baeldung.domain.product.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Integer> {
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface ProductRepository extends PagingAndSortingRepository<Product, Integer> {
List<Product> findAllByPrice(double price, Pageable pageable);
}

View File

@ -19,6 +19,17 @@ public class Product {
super();
}
private Product(int id, String name, double price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
public static Product from(int id, String name, double price) {
return new Product(id, name, price);
}
public int getId() {
return id;
}
@ -46,7 +57,11 @@ public class Product {
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Product [name=").append(name).append(", id=").append(id).append("]");
builder.append("Product [name=")
.append(name)
.append(", id=")
.append(id)
.append("]");
return builder.toString();
}
}

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