Merge branch 'master' into master

This commit is contained in:
Ahmed Tawila 2017-09-16 20:47:17 +02:00 committed by GitHub
commit 0bc5f8df30
142 changed files with 2597 additions and 1507 deletions

View File

@ -8,3 +8,4 @@
- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers) - [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)
- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm) - [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search) - [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search)
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)

View File

@ -0,0 +1,2 @@
### Relevant articles
- [Introduction to Apache Shiro](http://www.baeldung.com/apache-shiro)

2
bootique/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to Bootique](http://www.baeldung.com/bootique)

View File

@ -16,3 +16,4 @@
- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional) - [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams) - [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) - [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)

View File

@ -18,7 +18,7 @@ public class BaeldungSychronizedBlockTest {
IntStream.range(0, 1000) IntStream.range(0, 1000)
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask)); .forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS); service.awaitTermination(500, TimeUnit.MILLISECONDS);
assertEquals(1000, synchronizedBlocks.getCount()); assertEquals(1000, synchronizedBlocks.getCount());
} }
@ -29,7 +29,7 @@ public class BaeldungSychronizedBlockTest {
IntStream.range(0, 1000) IntStream.range(0, 1000)
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask)); .forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
service.awaitTermination(100, TimeUnit.MILLISECONDS); service.awaitTermination(500, TimeUnit.MILLISECONDS);
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount()); assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
} }

View File

@ -99,4 +99,10 @@
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror) - [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid) - [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char) - [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode)
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
- [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string)
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) - [Period and Duration in Java](http://www.baeldung.com/java-period-duration)

View File

@ -211,6 +211,11 @@
<artifactId>jmh-generator-annprocess</artifactId> <artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version> <version>1.19</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -239,6 +244,7 @@
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<configuration> <configuration>
<excludes> <excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude> <exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude> <exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude> <exclude>**/*ManualTest.java</exclude>
@ -373,30 +379,7 @@
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
@ -431,6 +414,31 @@
</systemPropertyVariables> </systemPropertyVariables>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase>-->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
</profile> </profile>
@ -461,7 +469,7 @@
<protonpack.version>1.13</protonpack.version> <protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version> <streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version> <vavr.version>0.9.0</vavr.version>
<!-- testing --> <!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version> <org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>

View File

@ -1,20 +1,23 @@
package com.baeldung.encoderdecoder; package com.baeldung.encoderdecoder;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.is;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriUtils;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.*;
public class EncoderDecoderUnitTest { public class EncoderDecoderUnitTest {
@ -76,19 +79,20 @@ public class EncoderDecoderUnitTest {
private String encodePath(String path) { private String encodePath(String path) {
try { try {
path = new URI(null, null, path, null).getPath(); path = UriUtils.encodePath(path, "UTF-8");
} catch (URISyntaxException e) { } catch (UnsupportedEncodingException e) {
LOGGER.error("Error encoding parameter {}", e.getMessage(), e); LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
} }
return path; return path;
} }
@Test @Test
public void givenPath_thenEncodeDecodePath() throws URISyntaxException { public void givenPathSegment_thenEncodeDecode() throws UnsupportedEncodingException {
URI uri = new URI(null, null, "/Path 1/Path+2", null); String pathSegment = "/Path 1/Path+2";
String encodedPathSegment = encodePath(pathSegment);
Assert.assertEquals("/Path 1/Path+2", uri.getPath()); String decodedPathSegment = UriUtils.decode(encodedPathSegment, "UTF-8");
Assert.assertEquals("/Path%201/Path+2", uri.getRawPath()); Assert.assertEquals("/Path%201/Path+2", encodedPathSegment);
Assert.assertEquals("/Path 1/Path+2", decodedPathSegment);
} }
@Test @Test

View File

@ -8,10 +8,10 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
public class NioEchoIntegrationTest { public class NioEchoLiveTest {
Process server; private Process server;
EchoClient client; private EchoClient client;
@Before @Before
public void setup() throws IOException, InterruptedException { public void setup() throws IOException, InterruptedException {

View File

@ -21,9 +21,9 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
public class JdbcIntegrationTest { public class JdbcLiveTest {
private static final Logger LOG = Logger.getLogger(JdbcIntegrationTest.class); private static final Logger LOG = Logger.getLogger(JdbcLiveTest.class);
private Connection con; private Connection con;

View File

@ -9,7 +9,7 @@ import java.io.IOException;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
public class UDPIntegrationTest { public class UDPLiveTest {
private EchoClient client; private EchoClient client;
@Before @Before

View File

@ -7,7 +7,7 @@ import java.io.IOException;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class BroadcastIntegrationTest { public class BroadcastLiveTest {
private BroadcastingClient client; private BroadcastingClient client;
@Test @Test

View File

@ -7,7 +7,7 @@ import java.io.IOException;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class MulticastIntegrationTest { public class MulticastLiveTest {
private MulticastingClient client; private MulticastingClient client;
@Test @Test

View File

@ -7,7 +7,7 @@ import java.io.File;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class ScreenshotIntegrationTest { public class ScreenshotLiveTest {
private Screenshot screenshot = new Screenshot("Screenshot.jpg"); private Screenshot screenshot = new Screenshot("Screenshot.jpg");
private File file = new File("Screenshot.jpg"); private File file = new File("Screenshot.jpg");

View File

@ -0,0 +1,5 @@
package org.baeldung.java.diamond;
public class Car<T extends Engine> implements Vehicle<T> {
}

View File

@ -0,0 +1,13 @@
package org.baeldung.java.diamond;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class DiamondOperatorUnitTest {
@Test
public void whenCreateCarUsingDiamondOperator_thenSuccess() {
Car<Diesel> myCar = new Car<>();
assertNotNull(myCar);
}
}

View File

@ -0,0 +1,10 @@
package org.baeldung.java.diamond;
public class Diesel implements Engine {
@Override
public void start() {
System.out.println("Started Diesel...");
}
}

View File

@ -0,0 +1,6 @@
package org.baeldung.java.diamond;
public interface Engine {
void start();
}

View File

@ -0,0 +1,5 @@
package org.baeldung.java.diamond;
public interface Vehicle<T extends Engine> {
}

View File

@ -0,0 +1,17 @@
package org.baeldung.java.rawtypes;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class RawTypesTest {
@Test
public void shouldCreateListUsingRawTypes() {
@SuppressWarnings("rawtypes")
List myList = new ArrayList();
myList.add(new Object());
myList.add("2");
myList.add(new Integer(1));
}
}

74
geotools/pom.xml Normal file
View File

@ -0,0 +1,74 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>geotools</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>geotools</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>${geotools-shapefile.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-swing</artifactId>
<version>${geotools-swing.version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net repository</name>
<url>http://download.java.net/maven/2</url>
</repository>
<repository>
<id>osgeo</id>
<name>Open Source Geospatial Foundation Repository</name>
<url>http://download.osgeo.org/webdav/geotools/</url>
</repository>
<repository>
<snapshots>
<enabled>true</enabled>
</snapshots>
<id>opengeo</id>
<name>OpenGeo Maven Repository</name>
<url>http://repo.opengeo.org</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<geotools.version>15.2</geotools.version>
<geotools-swing.version>15.2</geotools-swing.version>
<geotools-shapefile.version>15.2</geotools-shapefile.version>
</properties>
</project>

View File

@ -1,12 +1,8 @@
package com.baeldung.geotools; package com.baeldung.geotools;
import java.io.File; import com.vividsolutions.jts.geom.Coordinate;
import java.io.Serializable; import com.vividsolutions.jts.geom.GeometryFactory;
import java.util.ArrayList; import com.vividsolutions.jts.geom.Point;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.geotools.data.DataUtilities; import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction; import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction; import org.geotools.data.Transaction;
@ -23,9 +19,13 @@ import org.geotools.swing.data.JFileDataStoreChooser;
import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.simple.SimpleFeatureType;
import com.vividsolutions.jts.geom.Coordinate; import java.io.File;
import com.vividsolutions.jts.geom.GeometryFactory; import java.io.Serializable;
import com.vividsolutions.jts.geom.Point; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class ShapeFile { public class ShapeFile {
@ -41,22 +41,117 @@ public class ShapeFile {
SimpleFeatureType CITY = createFeatureType(); SimpleFeatureType CITY = createFeatureType();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); addLocations(CITY, collection);
addLocations(featureBuilder, collection);
File shapeFile = getNewShapeFile(); File shapeFile = getNewShapeFile();
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<String, Serializable>(); Map<String, Serializable> params = new HashMap<String, Serializable>();
ShapefileDataStore dataStore = setDataStoreParams(dataStoreFactory, params, shapeFile, CITY);
writeToFile(dataStore, collection);
}
static SimpleFeatureType createFeatureType() {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Location");
builder.setCRS(DefaultGeographicCRS.WGS84);
builder.add("Location", Point.class);
builder.length(15)
.add("Name", String.class);
return builder.buildFeatureType();
}
static void addLocations(SimpleFeatureType CITY, DefaultFeatureCollection collection) {
Map<String, List<Double>> locations = new HashMap<>();
double lat = 13.752222;
double lng = 100.493889;
addToLocationMap("Bangkok", lat, lng, locations);
lat = 53.083333;
lng = -0.15;
addToLocationMap("New York", lat, lng, locations);
lat = -33.925278;
lng = 18.423889;
addToLocationMap("Cape Town", lat, lng, locations);
lat = -33.859972;
lng = 151.211111;
addToLocationMap("Sydney", lat, lng, locations);
lat = 45.420833;
lng = -75.69;
addToLocationMap("Ottawa", lat, lng, locations);
lat = 30.07708;
lng = 31.285909;
addToLocationMap("Cairo", lat, lng, locations);
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
locations.entrySet().stream()
.map(toFeature(CITY, geometryFactory))
.forEach(collection::add);
}
private static Function<Map.Entry<String, List<Double>>, SimpleFeature> toFeature(SimpleFeatureType CITY, GeometryFactory geometryFactory) {
return location -> {
Point point = geometryFactory.createPoint(
new Coordinate(location.getValue()
.get(0), location.getValue().get(1)));
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY);
featureBuilder.add(point);
featureBuilder.add(location.getKey());
return featureBuilder.buildFeature(null);
};
}
private static void addToLocationMap(String name, double lat, double lng, Map<String, List<Double>> locations) {
List<Double> coordinates = new ArrayList<>();
coordinates.add(lat);
coordinates.add(lng);
locations.put(name, coordinates);
}
private static File getNewShapeFile() {
String filePath = new File(".").getAbsolutePath() + FILE_NAME;
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save shapefile");
chooser.setSelectedFile(new File(filePath));
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
System.exit(0);
}
return chooser.getSelectedFile();
}
private static ShapefileDataStore setDataStoreParams(ShapefileDataStoreFactory dataStoreFactory, Map<String, Serializable> params, File shapeFile, SimpleFeatureType CITY) throws Exception {
params.put("url", shapeFile.toURI() params.put("url", shapeFile.toURI()
.toURL()); .toURL());
params.put("create spatial index", Boolean.TRUE); params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
dataStore.createSchema(CITY); dataStore.createSchema(CITY);
return dataStore;
}
private static void writeToFile(ShapefileDataStore dataStore, DefaultFeatureCollection collection) throws Exception {
// If you decide to use the TYPE type and create a Data Store with it, // If you decide to use the TYPE type and create a Data Store with it,
// You will need to uncomment this line to set the Coordinate Reference System // You will need to uncomment this line to set the Coordinate Reference System
// newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); // newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
@ -73,11 +168,9 @@ public class ShapeFile {
try { try {
featureStore.addFeatures(collection); featureStore.addFeatures(collection);
transaction.commit(); transaction.commit();
} catch (Exception problem) { } catch (Exception problem) {
problem.printStackTrace(); problem.printStackTrace();
transaction.rollback(); transaction.rollback();
} finally { } finally {
transaction.close(); transaction.close();
} }
@ -86,102 +179,5 @@ public class ShapeFile {
System.out.println(typeName + " does not support read/write access"); System.out.println(typeName + " does not support read/write access");
System.exit(1); System.exit(1);
} }
} }
public static SimpleFeatureType createFeatureType() {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Location");
builder.setCRS(DefaultGeographicCRS.WGS84);
builder.add("Location", Point.class);
builder.length(15)
.add("Name", String.class);
SimpleFeatureType CITY = builder.buildFeatureType();
return CITY;
}
public static void addLocations(SimpleFeatureBuilder featureBuilder, DefaultFeatureCollection collection) {
Map<String, List<Double>> locations = new HashMap<>();
double lat = 13.752222;
double lng = 100.493889;
String name = "Bangkok";
addToLocationMap(name, lat, lng, locations);
lat = 53.083333;
lng = -0.15;
name = "New York";
addToLocationMap(name, lat, lng, locations);
lat = -33.925278;
lng = 18.423889;
name = "Cape Town";
addToLocationMap(name, lat, lng, locations);
lat = -33.859972;
lng = 151.211111;
name = "Sydney";
addToLocationMap(name, lat, lng, locations);
lat = 45.420833;
lng = -75.69;
name = "Ottawa";
addToLocationMap(name, lat, lng, locations);
lat = 30.07708;
lng = 31.285909;
name = "Cairo";
addToLocationMap(name, lat, lng, locations);
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
for (Map.Entry<String, List<Double>> location : locations.entrySet()) {
Point point = geometryFactory.createPoint(new Coordinate(location.getValue()
.get(0),
location.getValue()
.get(1)));
featureBuilder.add(point);
featureBuilder.add(name);
SimpleFeature feature = featureBuilder.buildFeature(null);
collection.add(feature);
}
}
private static void addToLocationMap(String name, double lat, double lng, Map<String, List<Double>> locations) {
List<Double> coordinates = new ArrayList<>();
coordinates.add(lat);
coordinates.add(lng);
locations.put(name, coordinates);
}
private static File getNewShapeFile() {
String filePath = new File(".").getAbsolutePath() + FILE_NAME;
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save shapefile");
chooser.setSelectedFile(new File(filePath));
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
System.exit(0);
}
File shapeFile = chooser.getSelectedFile();
if (shapeFile.equals(filePath)) {
System.out.println("Error: cannot replace " + filePath);
System.exit(0);
}
return shapeFile;
}
} }

View File

@ -7,21 +7,16 @@ import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.junit.Test; import org.junit.Test;
import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.simple.SimpleFeatureType;
public class GeoToolsUnitTestTest { public class GeoToolsUnitTest {
@Test @Test
public void givenFeatureType_whenAddLocations_returnFeatureCollection() { public void givenFeatureType_whenAddLocations_returnFeatureCollection() {
DefaultFeatureCollection collection = new DefaultFeatureCollection(); DefaultFeatureCollection collection = new DefaultFeatureCollection();
SimpleFeatureType CITY = ShapeFile.createFeatureType(); SimpleFeatureType CITY = ShapeFile.createFeatureType();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); ShapeFile.addLocations(CITY, collection);
ShapeFile.addLocations(featureBuilder, collection);
assertNotNull(collection); assertNotNull(collection);
} }
} }

2
grpc/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to gRPC](http://www.baeldung.com/grpc-introduction)

View File

@ -0,0 +1,42 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.beanvalidation</groupId>
<artifactId>beanvalidation</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>beanvalidation</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.beanvalidation.application;
import javax.validation.Validation;
import javax.validation.Validator;
import com.baeldung.beanvalidation.model.User;
public class Application {
public static void main( String[] args ) {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
User user = new User();
user.setName("Mary");
user.setEmail("no-email");
user.setAge(36);
validator.validate(user).stream().forEach(violation -> System.out.println(violation.getMessage()));
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.beanvalidation.container;
import java.util.Optional;
import javax.validation.constraints.Positive;
public class IntegerContainer {
private Optional<@Positive(message = "Value must be a positive integer") Integer> container = Optional.empty();
public void addElement(int element) {
container = Optional.of(element);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.beanvalidation.container;
import java.util.ArrayList;
import java.util.List;
import javax.validation.constraints.NotNull;
public class StringContainer {
private List<@NotNull String> container = new ArrayList<>();
public void addElement(String element) {
container.add(element);
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.beanvalidation.model;
import java.io.Serializable;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull(message = "Name cannot be null")
@Size(min = 2, max = 32, message = "Name must be between 2 and 32 characters")
private String name;
@Email(message = "Email must be a well-formed email address")
private String email;
@Min(value = 1, message = "Age must not be lesser than 1")
@Max(value = 99, message = "Age must not be greater than 99")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.beanvalidation.service;
public interface EntityService {
public String toString();
public void processEntity();
}

View File

@ -0,0 +1,45 @@
package com.baeldung.beanvalidation.service;
import java.io.Serializable;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.baeldung.beanvalidation.model.User;
public class UserService implements EntityService, Serializable {
private static final long serialVersionUID = 1L;
@Valid
private User user;
@NotNull(message = "FileName cannot be null")
@Size(min = 5, max = 10, message = "FileName must be between 5 and 10 characters")
private String fileName;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
@Override
public void processEntity() {
// process the user here
}
@Override
public String toString() {
return "UserService [user=" + user + ", fileName=" + fileName + "]";
}
}

View File

@ -0,0 +1,134 @@
package com.baeldung.beanvalidation;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.beanvalidation.container.IntegerContainer;
import com.baeldung.beanvalidation.container.StringContainer;
import com.baeldung.beanvalidation.model.User;
import com.baeldung.beanvalidation.service.UserService;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
public class ValidationTest {
private static Validator validator;
private static User user;
@BeforeClass
public static void setUpHibernateValidatorInstance() {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
@BeforeClass
public static void setUpUserInstance() {
user = new User();
}
@AfterClass
public static void tearDownHibernateValidatorInstance() {
validator = null;
}
@AfterClass
public static void tearDownUserInstance() {
user = null;
}
@Test
public void givenNullName_whenValidated_thenMessageDescriptorForName() {
user.setName(null);
user.setEmail("mary@domain.com");
user.setAge(36);
assertEquals("Name cannot be null", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenInvalidEmail_whenValidated_thenMessageDescriptorforEmail() {
user.setName("Mary");
user.setEmail("no-email");
user.setAge(36);
assertEquals("Email must be a well-formed email address", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenAgeLesserThanLowerBound_whenValidated_thenMessageDescriptorforAge() {
user.setName("Mary");
user.setEmail("mary@domain.com");
user.setAge(0);
assertEquals("Age must not be lesser than 1", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenAgeGreaterThanUpperBound_whenValidated_thenMessageDescriptorforAge() {
user.setName("Mary");
user.setEmail("mary@domain.com");
user.setAge(100);
assertEquals("Age must not be greater than 99", validator.validate(user).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenNullFileName_whenValidated_thenMessageDescriptorforFileName() {
user.setName("Mary");
user.setEmail("mary@domain.com");
user.setAge(36);
UserService userService = new UserService();
userService.setFileName(null);
userService.setUser(user);
assertEquals("FileName cannot be null", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenFileNameShortherThanLowerBound_whenValidated_thenMessageDescriptorforFileName() {
user.setName("Mary");
user.setEmail("mary@domain.com");
user.setAge(36);
UserService userService = new UserService();
userService.setFileName("");
userService.setUser(user);
assertEquals("FileName must be between 5 and 10 characters", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenFileNameLongerThanUpperBound_whenValidated_thenMessageDescriptorforFileName() {
user.setName("Mary");
user.setEmail("mary@domain.com");
user.setAge(36);
UserService userService = new UserService();
userService.setFileName("waytoolongfilename");
userService.setUser(user);
assertEquals("FileName must be between 5 and 10 characters", validator.validate(userService).stream().map(violation -> violation.getMessage()).collect(Collectors.joining()));
}
@Test
public void givenNullUserAndNullFileName_whenValidated_thenTwoConstraintViolations() {
user.setName(null);
user.setEmail("mary@domain.com");
user.setAge(36);
UserService userService = new UserService();
userService.setFileName(null);
userService.setUser(user);
Set<ConstraintViolation<UserService>> constraintViolations = validator.validate(userService);
assertEquals(2, constraintViolations.size());
}
@Test
public void givenNullElement_whenValidated_thenOneConstraintViolation() {
StringContainer container = new StringContainer();
container.addElement(null);
Set<ConstraintViolation<StringContainer>> constraintViolations = validator.validate(container);
assertEquals(1, constraintViolations.size());
}
@Test
public void givenNegativeInteger_whenValidated_thenOneConstraintViolation() {
IntegerContainer container = new IntegerContainer();
container.addElement(-1);
Set<ConstraintViolation<IntegerContainer>> constraintViolations = validator.validate(container);
assertEquals(1, constraintViolations.size());
}
}

View File

@ -5,3 +5,4 @@
- [Introduction to JAX-WS](http://www.baeldung.com/jax-ws) - [Introduction to JAX-WS](http://www.baeldung.com/jax-ws)
- [A Guide to Java EE Web-Related Annotations](http://www.baeldung.com/javaee-web-annotations) - [A Guide to Java EE Web-Related Annotations](http://www.baeldung.com/javaee-web-annotations)
- [Introduction to Testing with Arquillian](http://www.baeldung.com/arquillian) - [Introduction to Testing with Arquillian](http://www.baeldung.com/arquillian)
- [Securing Java EE with Spring Security](http://www.baeldung.com/java-ee-spring-security)

View File

@ -22,7 +22,7 @@ import com.baeldung.arquillian.Component;
import com.baeldung.arquillian.ConvertToLowerCase; import com.baeldung.arquillian.ConvertToLowerCase;
@RunWith(Arquillian.class) @RunWith(Arquillian.class)
public class ArquillianTest { public class ArquillianLiveTest {
@Deployment @Deployment
public static JavaArchive createDeployment() { public static JavaArchive createDeployment() {

View File

@ -5,3 +5,5 @@
- [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) - [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test)
- [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests)
- [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) - [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions)
- [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters)

View File

@ -13,4 +13,7 @@
- [Overview of Kotlin Collections API](http://www.baeldung.com/kotlin-collections-api) - [Overview of Kotlin Collections API](http://www.baeldung.com/kotlin-collections-api)
- [Converting a List to Map in Kotlin](http://www.baeldung.com/kotlin-list-to-map) - [Converting a List to Map in Kotlin](http://www.baeldung.com/kotlin-list-to-map)
- [Data Classes in Kotlin](http://www.baeldung.com/kotlin-data-classes) - [Data Classes in Kotlin](http://www.baeldung.com/kotlin-data-classes)
- [Delegated Properties in Kotlin](http://www.baeldung.com/kotlin-delegated-properties)
- [Sealed Classes in Kotlin](http://www.baeldung.com/kotlin-sealed-classes)

View File

@ -0,0 +1,12 @@
package com.baeldung.kotlin
class JvmSample(text:String) {
@JvmField
val sampleText:String = text
}
class CompanionSample {
companion object {
@JvmField val MAX_LIMIT = 20
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.kotlin
import org.junit.Before
import org.junit.Test
import kotlin.test.assertTrue
class JvmSampleTest {
var sample = ""
@Before
fun setUp() {
sample = JvmSample("Hello!").sampleText
}
@Test
fun givenField_whenCheckValue_thenMatchesValue() {
assertTrue(sample == "Hello!")
}
@Test
fun givenStaticVariable_whenCheckValue_thenMatchesValue() {
// Sample when is treated as a static variable
assertTrue(CompanionSample.MAX_LIMIT == 20)
}
}

2
libraries-data/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant articles
- [Introduction to Reladomo](http://www.baeldung.com/reladomo)

View File

@ -30,8 +30,17 @@
- [Introduction to Neuroph](http://www.baeldung.com/neuroph) - [Introduction to Neuroph](http://www.baeldung.com/neuroph)
- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) - [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue)
- [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) - [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss)
- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception)
- [Introduction to PCollections](http://www.baeldung.com/java-pcollections)
- [Introduction to Hoverfly in Java](http://www.baeldung.com/hoverfly)
- [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain)
- [Introduction to Eclipse Collections](http://www.baeldung.com/eclipse-collections)
- [DistinctBy in Java Stream API](http://www.baeldung.com/java-streams-distinct-by)
- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv)
- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference)
- [Introduction to NoException](http://www.baeldung.com/no-exception) - [Introduction to NoException](http://www.baeldung.com/no-exception)
- [Introduction to FunctionalJava](http://www.baeldung.com/functional-java) - [Introduction to FunctionalJava](http://www.baeldung.com/functional-java)
- [Apache Commons IO](http://www.baeldung.com/apache-commons-io)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -140,7 +140,7 @@
<artifactId>unit-ri</artifactId> <artifactId>unit-ri</artifactId>
<version>1.0.3</version> <version>1.0.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId> <artifactId>commons-collections4</artifactId>
<version>${commons.collections.version}</version> <version>${commons.collections.version}</version>
@ -487,21 +487,7 @@
<artifactId>vavr</artifactId> <artifactId>vavr</artifactId>
<version>${vavr.version}</version> <version>${vavr.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-swing</artifactId>
<version>${geotools.version}</version>
</dependency>
<!-- Retrofit --> <!-- Retrofit -->
<dependency> <dependency>
<groupId>com.squareup.retrofit2</groupId> <groupId>com.squareup.retrofit2</groupId>
@ -517,6 +503,11 @@
<groupId>com.squareup.retrofit2</groupId> <groupId>com.squareup.retrofit2</groupId>
<artifactId>adapter-rxjava</artifactId> <artifactId>adapter-rxjava</artifactId>
<version>${retrofit.version}</version> <version>${retrofit.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
<version>3.9.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.darwinsys</groupId> <groupId>com.darwinsys</groupId>
@ -591,19 +582,6 @@
<name>Java.net repository</name> <name>Java.net repository</name>
<url>http://download.java.net/maven/2</url> <url>http://download.java.net/maven/2</url>
</repository> </repository>
<repository>
<id>osgeo</id>
<name>Open Source Geospatial Foundation Repository</name>
<url>http://download.osgeo.org/webdav/geotools/</url>
</repository>
<repository>
<snapshots>
<enabled>true</enabled>
</snapshots>
<id>opengeo</id>
<name>OpenGeo Maven Repository</name>
<url>http://repo.opengeo.org</url>
</repository>
<repository> <repository>
<snapshots> <snapshots>
<enabled>false</enabled> <enabled>false</enabled>
@ -657,11 +635,12 @@
<eclipse-collections.version>8.2.0</eclipse-collections.version> <eclipse-collections.version>8.2.0</eclipse-collections.version>
<streamex.version>0.6.5</streamex.version> <streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version> <vavr.version>0.9.0</vavr.version>
<geotools.version>15.2</geotools.version> <joda-time.version>2.9.9</joda-time.version>
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
<retrofit.version>2.3.0</retrofit.version> <retrofit.version>2.3.0</retrofit.version>
<joda-time.version>2.9.9</joda-time.version> <joda-time.version>2.9.9</joda-time.version>
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version> <hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
<protonpack.version>1.14</protonpack.version> <protonpack.version>1.14</protonpack.version>
<unit-ri.version>1.0.3</unit-ri.version> <unit-ri.version>1.0.3</unit-ri.version>
<cache.version>1.0.0</cache.version> <cache.version>1.0.0</cache.version>
<hazelcast.version>3.8.4</hazelcast.version> <hazelcast.version>3.8.4</hazelcast.version>

View File

@ -0,0 +1,11 @@
package com.baeldung.commons.lang3;
import org.apache.commons.lang3.concurrent.LazyInitializer;
public class SampleLazyInitializer extends LazyInitializer<SampleObject> {
@Override
protected SampleObject initialize() {
return new SampleObject();
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.commons.lang3;
public class SampleObject {
//Ignored
}

View File

@ -0,0 +1,58 @@
package com.baeldung.retrofitguide;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class GitHubServiceGenerator {
private static final String BASE_URL = "https://api.github.com/";
private static Retrofit.Builder builder
= new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
private static OkHttpClient.Builder httpClient
= new OkHttpClient.Builder();
private static HttpLoggingInterceptor logging
= new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BASIC);
public static <S> S createService(Class<S> serviceClass) {
if (!httpClient.interceptors().contains(logging)) {
httpClient.addInterceptor(logging);
builder.client(httpClient.build());
retrofit = builder.build();
}
return retrofit.create(serviceClass);
}
public static <S> S createService(Class<S> serviceClass, final String token) {
if (token != null) {
httpClient.interceptors().clear();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.header("Authorization", token);
Request request = builder.build();
return chain.proceed(request);
}
});
builder.client(httpClient.build());
retrofit = builder.build();
}
return retrofit.create(serviceClass);
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.retrofitguide;
import java.io.IOException;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Main {
public static void main(String[] args) {
//Manual creation
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
UserService service = retrofit.create(UserService.class);
//Using GitHubServiceGenerator
service = GitHubServiceGenerator.createService(UserService.class);
Call<User> callSync = service.getUser("eugenp");
Call<User> callAsync = service.getUser("eugenp");
try {
Response<User> response = callSync.execute();
User user = response.body();
System.out.println(user);
} catch (IOException ex) {
}
// Execute the call asynchronously. Get a positive or negative callback.
callAsync.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
System.out.println(user);
}
@Override
public void onFailure(Call<User> call, Throwable throwable) {
System.out.println(throwable);
}
});
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.retrofitguide;
public class User {
private String login;
private long id;
private String url;
private String company;
private String blog;
private String email;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getBlog() {
return blog;
}
public void setBlog(String blog) {
this.blog = blog;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.retrofitguide;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface UserService {
@GET("/users")
public Call<List<User>> getUsers(@Query("per_page") int per_page, @Query("page") int page);
@GET("/users/{username}")
public Call<User> getUser(@Path("username") String username);
}

View File

@ -1,6 +1,7 @@
package com.baeldung.commons.lang3; package com.baeldung.commons.lang3;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
@ -12,12 +13,14 @@ import java.beans.PropertyChangeListener;
import java.io.File; import java.io.File;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Locale; import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import org.apache.commons.lang3.ArchUtils; import org.apache.commons.lang3.ArchUtils;
import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.arch.Processor; import org.apache.commons.lang3.arch.Processor;
import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.apache.commons.lang3.concurrent.ConcurrentRuntimeException; import org.apache.commons.lang3.concurrent.ConcurrentRuntimeException;
import org.apache.commons.lang3.concurrent.ConcurrentUtils; import org.apache.commons.lang3.concurrent.ConcurrentUtils;
import org.apache.commons.lang3.event.EventUtils; import org.apache.commons.lang3.event.EventUtils;
@ -97,22 +100,37 @@ public class Lang3UtilsTest {
public void testAddEventListenerThrowsException() { public void testAddEventListenerThrowsException() {
final ExceptionEventSource src = new ExceptionEventSource(); final ExceptionEventSource src = new ExceptionEventSource();
try { try {
EventUtils.addEventListener(src, PropertyChangeListener.class, new PropertyChangeListener() { EventUtils.addEventListener(src, PropertyChangeListener.class, (PropertyChangeEvent e) -> {
@Override /* Change event*/});
public void propertyChange(final PropertyChangeEvent e) {
// Do nothing!
}
});
fail("Add method should have thrown an exception, so method should fail."); fail("Add method should have thrown an exception, so method should fail.");
} catch (final RuntimeException e) { } catch (final RuntimeException e) {
} }
} }
@Test
public void ConcurrentExceptionSample() throws ConcurrentException {
final Error err = new AssertionError("Test");
try {
ConcurrentUtils.handleCause(new ExecutionException(err));
fail("Error not thrown!");
} catch (final Error e) {
assertEquals("Wrong error", err, e);
}
}
public static class ExceptionEventSource { public static class ExceptionEventSource {
public void addPropertyChangeListener(final PropertyChangeListener listener) { public void addPropertyChangeListener(final PropertyChangeListener listener) {
throw new RuntimeException(); throw new RuntimeException();
} }
} }
@Test
public void testLazyInitializer() throws Exception {
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
SampleObject sampleObjectOne = sampleLazyInitializer.get();
SampleObject sampleObjectTwo = sampleLazyInitializer.get();
assertEquals(sampleObjectOne, sampleObjectTwo);
}
} }

View File

@ -0,0 +1,79 @@
package com.baeldung.fj;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import fj.F;
import fj.data.Array;
import fj.data.List;
import fj.data.Option;
import fj.function.Characters;
import fj.function.Integers;
public class FunctionalJavaTest {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
@Test
public void calculateEvenNumbers_givenIntList_returnTrue() {
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);
}
@Test
public void mapList_givenIntList_returnResult() {
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);
}
@Test
public void filterList_givenIntList_returnResult() {
Array<Integer> array = Array.array(3, 4, 5, 6);
Array<Integer> filteredArray = array.filter(Integers.even);
Array<Integer> result = Array.array(4, 6);
Array<Integer> wrongResult = Array.array(3, 5);
assertEquals(filteredArray.equals(result), true);
assertEquals(filteredArray.equals(wrongResult), false);
}
@Test
public void checkForLowerCase_givenStringArray_returnResult() {
Array<String> array = Array.array("Welcome", "To", "baeldung");
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));
assertEquals(isExist, true);
assertEquals(isExist2, false);
}
@Test
public void checkOptions_givenOptions_returnResult() {
Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2);
F<Integer, Option<Integer>> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
Option<Integer> result1 = n1.bind(f1);
Option<Integer> result2 = n2.bind(f1);
assertEquals(result1, Option.none());
assertEquals(result2, Option.some(102));
}
@Test
public void foldLeft_givenArray_returnResult() {
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0);
assertEquals(sum, 260);
}
}

View File

@ -9,11 +9,14 @@ import javax.cache.configuration.FactoryBuilder;
import javax.cache.configuration.MutableConfiguration; import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider; import javax.cache.spi.CachingProvider;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
public class CacheLoaderTest { public class CacheLoaderTest {
private static final String CACHE_NAME = "SimpleCache";
private Cache<Integer, String> cache; private Cache<Integer, String> cache;
@Before @Before
@ -25,6 +28,12 @@ public class CacheLoaderTest {
this.cache = cacheManager.createCache("SimpleCache", config); this.cache = cacheManager.createCache("SimpleCache", config);
} }
@After
public void tearDown() {
Caching.getCachingProvider()
.getCacheManager().destroyCache(CACHE_NAME);
}
@Test @Test
public void whenReadingFromStorage_thenCorrect() { public void whenReadingFromStorage_thenCorrect() {
for (int i = 1; i < 4; i++) { for (int i = 1; i < 4; i++) {
@ -32,4 +41,4 @@ public class CacheLoaderTest {
assertEquals("fromCache" + i, value); assertEquals("fromCache" + i, value);
} }
} }
} }

View File

@ -1,6 +1,8 @@
package com.baeldung.jcache; package com.baeldung.jcache;
import static org.junit.Assert.assertEquals; import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.cache.Cache; import javax.cache.Cache;
import javax.cache.CacheManager; import javax.cache.CacheManager;
@ -8,25 +10,32 @@ import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration; import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider; import javax.cache.spi.CachingProvider;
import org.junit.Before; import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class EntryProcessorTest { public class EntryProcessorTest {
private static final String CACHE_NAME = "MyCache";
private Cache<String, String> cache; private Cache<String, String> cache;
@Before @Before
public void instantiateCache() { public void instantiateCache() {
CachingProvider cachingProvider = Caching.getCachingProvider(); CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager(); CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration<String, String> config = new MutableConfiguration<String, String>(); MutableConfiguration<String, String> config = new MutableConfiguration<>();
this.cache = cacheManager.createCache("MyCache", config); this.cache = cacheManager.createCache(CACHE_NAME, config);
this.cache.put("key", "value"); this.cache.put("key", "value");
} }
@After
public void tearDown() {
Caching.getCachingProvider()
.getCacheManager().destroyCache(CACHE_NAME);
}
@Test @Test
public void whenModifyValue_thenCorrect() { public void whenModifyValue_thenCorrect() {
this.cache.invoke("key", new SimpleEntryProcessor()); this.cache.invoke("key", new SimpleEntryProcessor());
assertEquals("value - modified", cache.get("key")); assertEquals("value - modified", cache.get("key"));
} }
} }

View File

@ -1,6 +1,8 @@
package com.baeldung.jcache; package com.baeldung.jcache;
import static org.junit.Assert.assertEquals; import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.cache.Cache; import javax.cache.Cache;
import javax.cache.CacheManager; import javax.cache.CacheManager;
@ -10,14 +12,15 @@ import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
import javax.cache.configuration.MutableConfiguration; import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider; import javax.cache.spi.CachingProvider;
import org.junit.Before; import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class EventListenerTest { public class EventListenerTest {
private static final String CACHE_NAME = "MyCache";
private Cache<String, String> cache; private Cache<String, String> cache;
private SimpleCacheEntryListener listener; private SimpleCacheEntryListener listener;
MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration; private MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration;
@Before @Before
public void setup() { public void setup() {
@ -28,9 +31,16 @@ public class EventListenerTest {
this.listener = new SimpleCacheEntryListener(); this.listener = new SimpleCacheEntryListener();
} }
@After
public void tearDown() {
Caching.getCachingProvider()
.getCacheManager().destroyCache(CACHE_NAME);
}
@Test @Test
public void whenRunEvent_thenCorrect() throws InterruptedException { public void whenRunEvent_thenCorrect() throws InterruptedException {
this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<String, String>(FactoryBuilder.factoryOf(this.listener), null, false, true); this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder
.factoryOf(this.listener), null, false, true);
this.cache.registerCacheEntryListener(this.listenerConfiguration); this.cache.registerCacheEntryListener(this.listenerConfiguration);
assertEquals(false, this.listener.getCreated()); assertEquals(false, this.listener.getCreated());
@ -42,4 +52,5 @@ public class EventListenerTest {
this.cache.put("key", "newValue"); this.cache.put("key", "newValue");
assertEquals(true, this.listener.getUpdated()); assertEquals(true, this.listener.getUpdated());
} }
}
}

View File

@ -1,6 +1,6 @@
package com.baeldung.jcache; package com.baeldung.jcache;
import static org.junit.Assert.assertEquals; import org.junit.Test;
import javax.cache.Cache; import javax.cache.Cache;
import javax.cache.CacheManager; import javax.cache.CacheManager;
@ -8,7 +8,7 @@ import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration; import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider; import javax.cache.spi.CachingProvider;
import org.junit.Test; import static org.junit.Assert.assertEquals;
public class JCacheTest { public class JCacheTest {
@ -24,4 +24,4 @@ public class JCacheTest {
assertEquals("value2", cache.get("key2")); assertEquals("value2", cache.get("key2"));
cacheManager.close(); cacheManager.close();
} }
} }

View File

@ -16,7 +16,7 @@ import com.baeldung.retrofit.models.Repository;
import retrofit2.Retrofit; import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.converter.gson.GsonConverterFactory;
public class GitHubBasicApiTest { public class GitHubBasicApiLiveTest {
GitHubBasicApi gitHub; GitHubBasicApi gitHub;

View File

@ -1,3 +1,4 @@
### Relevant articles ### Relevant articles
- [Intro to Log4j2 Appenders, Layouts and Filters](http://www.baeldung.com/log4j2-appenders-layouts-filters) - [Intro to Log4j2 Appenders, Layouts and Filters](http://www.baeldung.com/log4j2-appenders-layouts-filters)
- [Log4j 2 and Lambda Expressions](http://www.baeldung.com/log4j-2-lazy-logging)

View File

@ -22,10 +22,9 @@ public class ArticleController {
.mapToObj(i -> generateArticle("Article Title " + i)) .mapToObj(i -> generateArticle("Article Title " + i))
.collect(Collectors.toList()); .collect(Collectors.toList());
Map<String, Object> modelMap = new HashMap<>(); model.put("articles", articles);
modelMap.put("articles", articles);
return new ModelAndView("index", modelMap); return new ModelAndView("index", model);
} }
private Article generateArticle(String title) { private Article generateArticle(String title) {

View File

@ -57,7 +57,7 @@
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build --> <!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
<module>geotools</module>
<module>groovy-spock</module> <module>groovy-spock</module>
<module>gson</module> <module>gson</module>
<module>guava</module> <module>guava</module>

View File

@ -3,3 +3,5 @@
- [Introduction to Ratpack](http://www.baeldung.com/ratpack) - [Introduction to Ratpack](http://www.baeldung.com/ratpack)
- [Ratpack Google Guice Integration](http://www.baeldung.com/ratpack-google-guice) - [Ratpack Google Guice Integration](http://www.baeldung.com/ratpack-google-guice)
- [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot) - [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot)
- [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix)

View File

@ -2,3 +2,4 @@
- [Dealing with Backpressure with RxJava](http://www.baeldung.com/rxjava-backpressure) - [Dealing with Backpressure with RxJava](http://www.baeldung.com/rxjava-backpressure)
- [How to Test RxJava?](http://www.baeldung.com/rxjava-testing) - [How to Test RxJava?](http://www.baeldung.com/rxjava-testing)
- [Implementing Custom Operators in RxJava](http://www.baeldung.com/rxjava-custom-operators)

View File

@ -19,6 +19,18 @@
<artifactId>rxjava</artifactId> <artifactId>rxjava</artifactId>
<version>${rx.java.version}</version> <version>${rx.java.version}</version>
</dependency> </dependency>
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjava</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>1.7.0</version>
</dependency>
</dependencies> </dependencies>
<properties> <properties>

View File

@ -9,7 +9,8 @@ public class ConnectableObservableImpl {
public static void main(String[] args) throws InterruptedException { public static void main(String[] args) throws InterruptedException {
ConnectableObservable<Long> connectable = Observable.interval(200, TimeUnit.MILLISECONDS).publish(); ConnectableObservable<Long> connectable
= Observable.interval(200, TimeUnit.MILLISECONDS).publish();
connectable.subscribe(System.out::println); connectable.subscribe(System.out::println);
System.out.println("Connect"); System.out.println("Connect");

View File

@ -3,12 +3,22 @@ package com.baelding.rxjava;
import rx.Observable; import rx.Observable;
import rx.observables.BlockingObservable; import rx.observables.BlockingObservable;
import java.util.Arrays;
import java.util.List;
public class ObservableImpl { public class ObservableImpl {
public static void main(String[] args) { static Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; static String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; static String[] titles = {"title"};
public static List<String> titleList = Arrays.asList(titles);
public static Observable<String> getTitle() {
return Observable.from(titleList);
}
public static void main(String[] args) {
System.out.println("-------Just-----------"); System.out.println("-------Just-----------");
Observable<String> observable = Observable.just("Hello"); Observable<String> observable = Observable.just("Hello");
@ -28,14 +38,9 @@ public class ObservableImpl {
System.out.println(); System.out.println();
System.out.println("-------FlatMap-----------"); System.out.println("-------FlatMap-----------");
Observable.from(letters) Observable.just("book1", "book2")
.flatMap((letter) -> { .flatMap(s -> getTitle())
String[] returnStrings = {letter.toUpperCase(), letter.toLowerCase()}; .subscribe(System.out::print);
return Observable.from(returnStrings);
})
.subscribe(
System.out::print
);
System.out.println(); System.out.println();
System.out.println("--------Scan----------"); System.out.println("--------Scan----------");
@ -55,16 +60,12 @@ public class ObservableImpl {
System.out.println("-------Filter-----------"); System.out.println("-------Filter-----------");
Observable.from(numbers) Observable.from(numbers)
.filter(i -> (i % 2 == 1)) .filter(i -> (i % 2 == 1))
.subscribe( .subscribe(System.out::println);
System.out::println
);
System.out.println("------DefaultIfEmpty------------"); System.out.println("------DefaultIfEmpty------------");
Observable.empty() Observable.empty()
.defaultIfEmpty("Observable is empty") .defaultIfEmpty("Observable is empty")
.subscribe( .subscribe(System.out::println);
System.out::println
);
System.out.println("------DefaultIfEmpty-2-----------"); System.out.println("------DefaultIfEmpty-2-----------");
Observable.from(letters) Observable.from(letters)

View File

@ -13,8 +13,9 @@ public class ResourceManagement {
return resource; return resource;
}, },
r -> Observable.create(o -> { r -> Observable.create(o -> {
for (Character c : r.toCharArray()) for (Character c : r.toCharArray()) {
o.onNext(c); o.onNext(c);
}
o.onCompleted(); o.onCompleted();
}), }),
r -> System.out.println("Disposed: " + r) r -> System.out.println("Disposed: " + r)

View File

@ -1,69 +1,73 @@
package com.baelding.rxjava; package com.baelding.rxjava;
import rx.Observable; import rx.Observer;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject; import rx.subjects.PublishSubject;
public class SubjectImpl { public class SubjectImpl {
public static final String[] subscriber1 = {""}; public static Integer subscriber1 = 0;
public static final String[] subscriber2 = {""}; public static Integer subscriber2 = 0;
public static String subjectMethod() throws InterruptedException { public static Integer subjectMethod() {
PublishSubject<Integer> subject = PublishSubject.create();
String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; subject.subscribe(getFirstObserver());
Long signal = 500L;
PublishSubject<String> subject;
synchronized (signal) { subject.onNext(1);
subject = PublishSubject.create(); subject.onNext(2);
subject.subscribe( subject.onNext(3);
(letter) -> {
subscriber1[0] += letter;
System.out.println("Subscriber 1: " + subscriber1[0]);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (letter.equals("c")) {
synchronized (signal) {
signal.notify();
}
}
}
);
}
Observable.from(letters) subject.subscribe(getSecondObserver());
.subscribeOn(Schedulers.computation())
.subscribe( subject.onNext(4);
subject::onNext, subject.onCompleted();
subject::onError, return subscriber1 + subscriber2;
() -> { }
System.out.println("Subscriber 1 completed ");
subject.onCompleted();
synchronized (signal) { public static Observer<Integer> getFirstObserver() {
signal.notify(); return new Observer<Integer>() {
}
@Override
public void onNext(Integer value) {
subscriber1 += value;
System.out.println("Subscriber1: " + value);
} }
);
synchronized (signal) { @Override
signal.wait(); public void onError(Throwable e) {
subject.subscribe( System.out.println("error");
(letter) -> { }
subscriber2[0] += letter;
System.out.println("Subscriber 2: " + subscriber2[0]);
},
subject::onError,
() -> System.out.println("Subscriber 2 completed ")
);
}
synchronized (signal) { @Override
signal.wait(); public void onCompleted() {
return subscriber1[0] + subscriber2[0]; System.out.println("Subscriber1 completed");
} }
};
}
public static Observer<Integer> getSecondObserver() {
return new Observer<Integer>() {
@Override
public void onNext(Integer value) {
subscriber2 += value;
System.out.println("Subscriber2: " + value);
}
@Override
public void onError(Throwable e) {
System.out.println("error");
}
@Override
public void onCompleted() {
System.out.println("Subscriber2 completed");
}
};
}
public static void main(String[] args) throws InterruptedException {
System.out.println(subjectMethod());
} }
} }

View File

@ -6,6 +6,7 @@ import rx.observables.ConnectableObservable;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.assertTrue;
@ -13,15 +14,14 @@ public class ConnectableObservableTest {
@Test @Test
public void givenConnectableObservable_whenConnect_thenGetMessage() throws InterruptedException { public void givenConnectableObservable_whenConnect_thenGetMessage() throws InterruptedException {
final String[] result = {""}; String[] result = {""};
ConnectableObservable<Long> connectable = Observable.interval(200, TimeUnit.MILLISECONDS).publish(); ConnectableObservable<Long> connectable
= Observable.interval(500, TimeUnit.MILLISECONDS).publish();
connectable.subscribe(i -> result[0] += i); connectable.subscribe(i -> result[0] += i);
assertFalse(result[0].equals("01")); assertFalse(result[0].equals("01"));
connectable.connect(); connectable.connect();
Thread.currentThread().sleep(500); await()
.until(() -> assertTrue(result[0].equals("01")));
assertTrue(result[0].equals("01"));
} }
} }

View File

@ -2,10 +2,8 @@ package com.baeldung.rxjava;
import org.junit.Test; import org.junit.Test;
import rx.Observable; import rx.Observable;
import rx.observables.ConnectableObservable;
import java.util.concurrent.TimeUnit;
import static com.baelding.rxjava.ObservableImpl.getTitle;
import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.assertTrue;
public class ObservableTest { public class ObservableTest {
@ -24,41 +22,23 @@ public class ObservableTest {
String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
Observable<String> observable = Observable.from(letters); Observable<String> observable = Observable.from(letters);
observable.subscribe( observable.subscribe(
//onNext i -> result += i,
(i) -> { Throwable::printStackTrace,
result += i; () -> result += "_Complete"
},
//onError
(t) -> {
t.printStackTrace();
},
//onCompleted
() -> {
result += "Complete";
}
); );
assertTrue(result.equals("abcdefgComplete")); assertTrue(result.equals("abcdefg_Complete"));
} }
@Test @Test
public void givenArray_whenConvertsObservabletoBlockingObservable_thenReturnFirstElement() { public void givenArray_whenConvertsObservabletoBlockingObservable_thenReturnFirstElement() {
String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
Observable<String> observable = Observable.from(letters); Observable<String> observable = Observable.from(letters);
String blockingObservable = observable.toBlocking().first(); String blockingObservable = observable.toBlocking().first();
observable.subscribe( observable.subscribe(
//onNext i -> result += i,
(i) -> { Throwable::printStackTrace,
result += i; () -> result += "_Completed"
},
//onError
(t) -> {
t.printStackTrace();
},
//onCompleted
() -> {
result += "Complete";
}
); );
assertTrue(String.valueOf(result.charAt(0)).equals(blockingObservable)); assertTrue(String.valueOf(result.charAt(0)).equals(blockingObservable));
} }
@ -68,45 +48,31 @@ public class ObservableTest {
String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
Observable.from(letters) Observable.from(letters)
.map((letter) -> { .map(String::toUpperCase)
return letter.toUpperCase(); .subscribe(letter -> result += letter);
})
.subscribe((letter) -> {
result += letter;
});
assertTrue(result.equals("ABCDEFG")); assertTrue(result.equals("ABCDEFG"));
} }
@Test @Test
public void givenArray_whenFlatMapAndSubscribe_thenReturnUpperAndLowerCaseLetters() { public void givenArray_whenFlatMapAndSubscribe_thenReturnUpperAndLowerCaseLetters() {
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
Observable.from(letters) Observable.just("book1", "book2")
.flatMap((letter) -> { .flatMap(s -> getTitle())
String[] returnStrings = {letter.toUpperCase(), letter.toLowerCase()}; .subscribe(l -> result += l);
return Observable.from(returnStrings);
})
.subscribe((letter) -> {
result += letter;
});
assertTrue(result.equals("AaBbCcDdEeFfGg")); assertTrue(result.equals("titletitle"));
} }
@Test @Test
public void givenArray_whenScanAndSubscribe_thenReturnTheSumOfAllLetters() { public void givenArray_whenScanAndSubscribe_thenReturnTheSumOfAllLetters() {
String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; String[] letters = {"a", "b", "c"};
Observable.from(letters) Observable.from(letters)
.scan(new StringBuilder(), (buffer, nextLetter) -> { .scan(new StringBuilder(), StringBuilder::append)
return buffer.append(nextLetter); .subscribe(total -> result += total.toString());
})
.subscribe((total) -> {
result = total.toString();
});
assertTrue(result.equals("abcdefg")); assertTrue(result.equals("aababc"));
} }
@Test @Test
@ -116,18 +82,16 @@ public class ObservableTest {
String[] ODD = {""}; String[] ODD = {""};
Observable.from(numbers) Observable.from(numbers)
.groupBy((i) -> { .groupBy(i -> 0 == (i % 2) ? "EVEN" : "ODD")
return 0 == (i % 2) ? "EVEN" : "ODD"; .subscribe(group ->
}) group.subscribe((number) -> {
.subscribe((group) -> { if (group.getKey().toString().equals("EVEN")) {
group.subscribe((number) -> { EVEN[0] += number;
if (group.getKey().toString().equals("EVEN")) { } else {
EVEN[0] += number; ODD[0] += number;
} else { }
ODD[0] += number; })
} );
});
});
assertTrue(EVEN[0].equals("0246810")); assertTrue(EVEN[0].equals("0246810"));
assertTrue(ODD[0].equals("13579")); assertTrue(ODD[0].equals("13579"));
@ -138,12 +102,8 @@ public class ObservableTest {
Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Observable.from(numbers) Observable.from(numbers)
.filter((i) -> { .filter(i -> (i % 2 == 1))
return (i % 2 == 1); .subscribe(i -> result += i);
})
.subscribe((i) -> {
result += i;
});
assertTrue(result.equals("13579")); assertTrue(result.equals("13579"));
} }
@ -152,10 +112,8 @@ public class ObservableTest {
public void givenEmptyObservable_whenDefaultIfEmpty_thenGetDefaultMessage() { public void givenEmptyObservable_whenDefaultIfEmpty_thenGetDefaultMessage() {
Observable.empty() Observable.empty()
.defaultIfEmpty("Observable is empty") .defaultIfEmpty("Observable is empty")
.subscribe((s) -> { .subscribe(s -> result += s);
result += s;
});
assertTrue(result.equals("Observable is empty")); assertTrue(result.equals("Observable is empty"));
} }
@ -165,11 +123,9 @@ public class ObservableTest {
String[] letters = {"a", "b", "c", "d", "e", "f", "g"}; String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
Observable.from(letters) Observable.from(letters)
.defaultIfEmpty("Observable is empty") .defaultIfEmpty("Observable is empty")
.first() .first()
.subscribe((s) -> { .subscribe(s -> result += s);
result += s;
});
assertTrue(result.equals("a")); assertTrue(result.equals("a"));
} }
@ -180,12 +136,8 @@ public class ObservableTest {
final Integer[] sum = {0}; final Integer[] sum = {0};
Observable.from(numbers) Observable.from(numbers)
.takeWhile((i) -> { .takeWhile(i -> i < 5)
return i < 5; .subscribe(s -> sum[0] += s);
})
.subscribe((s) -> {
sum[0] += s;
});
assertTrue(sum[0] == 10); assertTrue(sum[0] == 10);
} }

View File

@ -10,32 +10,25 @@ public class ResourceManagementTest {
@Test @Test
public void givenResource_whenUsingOberservable_thenCreatePrintDisposeResource() throws InterruptedException { public void givenResource_whenUsingOberservable_thenCreatePrintDisposeResource() throws InterruptedException {
final String[] result = {""}; String[] result = {""};
Observable<Character> values = Observable.using( Observable<Character> values = Observable.using(
//a factory function that creates a disposable resource () -> {
() -> { return "MyResource";
String resource = "MyResource"; },
return resource; r -> {
}, return Observable.create(o -> {
//a factory function that creates an Observable for (Character c : r.toCharArray())
(resource) -> { o.onNext(c);
return Observable.create(o -> { o.onCompleted();
for (Character c : resource.toCharArray()) });
o.onNext(c); },
o.onCompleted(); r -> System.out.println("Disposed: " + r)
});
},
//a function that disposes of the resource
(resource) -> System.out.println("Disposed: " + resource)
); );
values.subscribe( values.subscribe(
v -> result[0] += v, v -> result[0] += v,
e -> result[0] += e e -> result[0] += e
); );
assertTrue(result[0].equals("MyResource")); assertTrue(result[0].equals("MyResource"));
} }
} }

View File

@ -10,19 +10,15 @@ public class SingleTest {
@Test @Test
public void givenSingleObservable_whenSuccess_thenGetMessage() throws InterruptedException { public void givenSingleObservable_whenSuccess_thenGetMessage() throws InterruptedException {
final String[] result = {""}; String[] result = {""};
Single<String> single = Observable.just("Hello").toSingle() Single<String> single = Observable.just("Hello")
.doOnSuccess( .toSingle()
(i) -> { .doOnSuccess(i -> result[0] += i)
result[0] += i; .doOnError(error -> {
}) throw new RuntimeException(error.getMessage());
.doOnError( });
(error) -> {
throw new RuntimeException(error.getMessage());
});
single.subscribe(); single.subscribe();
assertTrue(result[0].equals("Hello")); assertTrue(result[0].equals("Hello"));
} }
} }

View File

@ -2,16 +2,25 @@ package com.baeldung.rxjava;
import com.baelding.rxjava.SubjectImpl; import com.baelding.rxjava.SubjectImpl;
import org.junit.Test; import org.junit.Test;
import rx.subjects.PublishSubject;
import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.assertTrue;
public class SubjectTest { public class SubjectTest {
@Test @Test
public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubjectAfterLetterC_thenSecondSubscriberBeginsToPrint() throws InterruptedException { public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd(){
String result = SubjectImpl.subjectMethod(); PublishSubject<Integer> subject = PublishSubject.create();
String subscribers = SubjectImpl.subscriber1[0] + SubjectImpl.subscriber2[0];
assertTrue(subscribers.equals(result)); subject.subscribe(SubjectImpl.getFirstObserver());
subject.onNext(1);
subject.onNext(2);
subject.onNext(3);
subject.subscribe(SubjectImpl.getSecondObserver());
subject.onNext(4);
subject.onCompleted();
assertTrue(SubjectImpl.subscriber1 + SubjectImpl.subscriber2 == 14);
} }
} }

View File

@ -0,0 +1,141 @@
package com.baeldung.rxjava.onerror;
import io.reactivex.Observable;
import io.reactivex.exceptions.CompositeException;
import io.reactivex.observers.TestObserver;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.assertTrue;
/**
* @author aiet
*/
public class ExceptionHandlingTest {
private Error UNKNOWN_ERROR = new Error("unknown error");
private Exception UNKNOWN_EXCEPTION = new Exception("unknown exception");
@Test
public void givenSubscriberAndError_whenHandleOnErrorReturn_thenResumed() {
TestObserver testObserver = new TestObserver();
Observable
.error(UNKNOWN_ERROR)
.onErrorReturn(Throwable::getMessage)
.subscribe(testObserver);
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertValueCount(1);
testObserver.assertValue("unknown error");
}
@Test
public void givenSubscriberAndError_whenHandleOnErrorResume_thenResumed() {
TestObserver testObserver = new TestObserver();
Observable
.error(UNKNOWN_ERROR)
.onErrorResumeNext(Observable.just("one", "two"))
.subscribe(testObserver);
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertValueCount(2);
testObserver.assertValues("one", "two");
}
@Test
public void givenSubscriberAndError_whenHandleOnErrorResumeItem_thenResumed() {
TestObserver testObserver = new TestObserver();
Observable
.error(UNKNOWN_ERROR)
.onErrorReturnItem("singleValue")
.subscribe(testObserver);
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertValueCount(1);
testObserver.assertValue("singleValue");
}
@Test
public void givenSubscriberAndError_whenHandleOnErrorResumeFunc_thenResumed() {
TestObserver testObserver = new TestObserver();
Observable
.error(UNKNOWN_ERROR)
.onErrorResumeNext(throwable -> {
return Observable.just(throwable.getMessage(), "nextValue");
})
.subscribe(testObserver);
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertValueCount(2);
testObserver.assertValues("unknown error", "nextValue");
}
@Test
public void givenSubscriberAndError_whenChangeStateOnError_thenErrorThrown() {
TestObserver testObserver = new TestObserver();
final AtomicBoolean state = new AtomicBoolean(false);
Observable
.error(UNKNOWN_ERROR)
.doOnError(throwable -> state.set(true))
.subscribe(testObserver);
testObserver.assertError(UNKNOWN_ERROR);
testObserver.assertNotComplete();
testObserver.assertNoValues();
assertTrue("state should be changed", state.get());
}
@Test
public void givenSubscriberAndError_whenExceptionOccurOnError_thenCompositeExceptionThrown() {
TestObserver testObserver = new TestObserver();
Observable
.error(UNKNOWN_ERROR)
.doOnError(throwable -> {
throw new RuntimeException("unexcepted");
})
.subscribe(testObserver);
testObserver.assertError(CompositeException.class);
testObserver.assertNotComplete();
testObserver.assertNoValues();
}
@Test
public void givenSubscriberAndException_whenHandleOnException_thenResumed() {
TestObserver testObserver = new TestObserver();
Observable
.error(UNKNOWN_EXCEPTION)
.onExceptionResumeNext(Observable.just("exceptionResumed"))
.subscribe(testObserver);
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertValueCount(1);
testObserver.assertValue("exceptionResumed");
}
@Test
public void givenSubscriberAndError_whenHandleOnException_thenNotResumed() {
TestObserver testObserver = new TestObserver();
Observable
.error(UNKNOWN_ERROR)
.onExceptionResumeNext(Observable.just("exceptionResumed"))
.subscribe(testObserver);
testObserver.assertError(UNKNOWN_ERROR);
testObserver.assertNotComplete();
}
}

View File

@ -0,0 +1,149 @@
package com.baeldung.rxjava.onerror;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertTrue;
/**
* @author aiet
*/
public class OnErrorRetryTest {
private Error UNKNOWN_ERROR = new Error("unknown error");
@Test
public void givenSubscriberAndError_whenRetryOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
.retry(1)
.subscribe(testObserver);
testObserver.assertError(UNKNOWN_ERROR);
testObserver.assertNotComplete();
testObserver.assertNoValues();
assertTrue("should call twice", atomicCounter.get() == 2);
}
@Test
public void givenSubscriberAndError_whenRetryConditionallyOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
.retry((integer, throwable) -> integer < 4)
.subscribe(testObserver);
testObserver.assertError(UNKNOWN_ERROR);
testObserver.assertNotComplete();
testObserver.assertNoValues();
assertTrue("should call 4 times", atomicCounter.get() == 4);
}
@Test
public void givenSubscriberAndError_whenRetryUntilOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(UNKNOWN_ERROR)
.retryUntil(() -> atomicCounter.incrementAndGet() > 3)
.subscribe(testObserver);
testObserver.assertError(UNKNOWN_ERROR);
testObserver.assertNotComplete();
testObserver.assertNoValues();
assertTrue("should call 4 times", atomicCounter.get() == 4);
}
@Test
public void givenSubscriberAndError_whenRetryWhenOnError_thenRetryConfirmed() {
TestObserver testObserver = new TestObserver();
Exception noretryException = new Exception("don't retry");
Observable
.error(UNKNOWN_ERROR)
.retryWhen(throwableObservable -> Observable.error(noretryException))
.subscribe(testObserver);
testObserver.assertError(noretryException);
testObserver.assertNotComplete();
testObserver.assertNoValues();
}
@Test
public void givenSubscriberAndError_whenRetryWhenOnError_thenCompleted() {
TestObserver testObserver = new TestObserver();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
.retryWhen(throwableObservable -> Observable.empty())
.subscribe(testObserver);
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertNoValues();
assertTrue("should not retry", atomicCounter.get() == 0);
}
@Test
public void givenSubscriberAndError_whenRetryWhenOnError_thenResubscribed() {
TestObserver testObserver = new TestObserver();
AtomicInteger atomicCounter = new AtomicInteger(0);
Observable
.error(() -> {
atomicCounter.incrementAndGet();
return UNKNOWN_ERROR;
})
.retryWhen(throwableObservable -> Observable.just("anything"))
.subscribe(testObserver);
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertNoValues();
assertTrue("should retry once", atomicCounter.get() == 1);
}
@Test
public void givenSubscriberAndError_whenRetryWhenForMultipleTimesOnError_thenResumed() {
TestObserver testObserver = new TestObserver();
long before = System.currentTimeMillis();
Observable
.error(UNKNOWN_ERROR)
.retryWhen(throwableObservable -> throwableObservable
.zipWith(Observable.range(1, 3), (throwable, integer) -> integer)
.flatMap(integer -> {
System.out.println("retried " + integer + " times");
return Observable.timer(integer, TimeUnit.SECONDS);
}))
.blockingSubscribe(testObserver);
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertNoValues();
long secondsElapsed = (System.currentTimeMillis() - before) / 1000;
assertTrue("6 seconds should elapse", secondsElapsed == 6);
}
}

View File

@ -66,7 +66,6 @@
<dependency> <dependency>
<groupId>com.fasterxml.jackson.module</groupId> <groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId> <artifactId>jackson-module-kotlin</artifactId>
<version>2.8.7</version>
</dependency> </dependency>
<!-- runtime and test scoped --> <!-- runtime and test scoped -->

View File

@ -14,16 +14,19 @@ public class LiveTest {
private static String APP_ROOT = "http://localhost:8081"; private static String APP_ROOT = "http://localhost:8081";
@Test @Test
public void givenUser_whenResourceCreatedWithNullName_then400BadRequest() { public void givenUser_whenResourceCreatedWithNullName_then400BadRequest() {
final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()).body(resourceWithNullName()).post(APP_ROOT + "/foos"); final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString())
.body(resourceWithNullName())
.post(APP_ROOT + "/foos");
assertEquals(400, response.getStatusCode()); assertEquals(400, response.getStatusCode());
} }
@Test @Test
public void givenUser_whenResourceCreated_then201Created() { public void givenUser_whenResourceCreated_then201Created() {
final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString()).body(resourceString()).post(APP_ROOT + "/foos"); final Response response = givenAuth("user", "pass").contentType(MediaType.APPLICATION_JSON.toString())
.body(resourceString())
.post(APP_ROOT + "/foos");
assertEquals(201, response.getStatusCode()); assertEquals(201, response.getStatusCode());
} }
@ -32,21 +35,22 @@ public class LiveTest {
final Response response = givenAuth("user", "pass").get(APP_ROOT + "/foos"); final Response response = givenAuth("user", "pass").get(APP_ROOT + "/foos");
assertEquals(200, response.getStatusCode()); assertEquals(200, response.getStatusCode());
}*/ }*/
// //
private final String resourceWithNullName() { private final String resourceWithNullName() {
return "{\"name\":null}"; return "{\"name\":null}";
} }
private final String resourceString() { private final String resourceString() {
return "{\"name\":\"" + randomAlphabetic(8) + "\"}"; return "{\"name\":\"" + randomAlphabetic(8) + "\"}";
} }
private final RequestSpecification givenAuth(String username, String password) { private final RequestSpecification givenAuth(String username, String password) {
return RestAssured.given().auth().preemptive().basic(username, password); return RestAssured.given()
.auth()
.preemptive()
.basic(username, password);
} }
} }

View File

@ -9,3 +9,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) - [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web)
- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) - [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching)
- [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) - [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient)
- [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans)

View File

@ -1,188 +1,196 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>spring-5</artifactId> <artifactId>spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>spring-5</name> <name>spring-5</name>
<description>spring 5 sample project about new features</description> <description>spring 5 sample project about new features</description>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M1</version> <version>2.0.0.M1</version>
<relativePath /> <!-- lookup parent from repository --> <relativePath /> <!-- lookup parent from repository -->
</parent> </parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId> <artifactId>spring-boot-starter-security</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId> <artifactId>spring-boot-starter-validation</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId> <artifactId>spring-boot-starter-webflux</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.projectreactor</groupId> <groupId>org.projectreactor</groupId>
<artifactId>reactor-spring</artifactId> <artifactId>reactor-spring</artifactId>
<version>1.0.1.RELEASE</version> <version>${reactor-spring.version}</version>
</dependency> </dependency>
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>${jsonb-api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-json_1.1_spec</artifactId>
<version>${geronimo-json_1.1_spec.version}</version>
</dependency>
<dependency>
<groupId>org.apache.johnzon</groupId>
<artifactId>johnzon-jsonb</artifactId>
<version>${johnzon.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- utils --> <!-- runtime and test scoped -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- runtime and test scoped --> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-boot-devtools</artifactId> <artifactId>spring-test</artifactId>
<scope>runtime</scope> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.springframework.boot</groupId>
<groupId>com.h2database</groupId> <artifactId>spring-boot-starter-test</artifactId>
<artifactId>h2</artifactId> <scope>test</scope>
<scope>runtime</scope> </dependency>
</dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>spring-test</artifactId> <artifactId>junit-jupiter-api</artifactId>
</dependency> <version>${junit.jupiter.version}</version>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-test</artifactId> <groupId>org.junit.jupiter</groupId>
<scope>test</scope> <artifactId>junit-jupiter-engine</artifactId>
</dependency> <version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency> </dependencies>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.Spring5Application</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>
<build> <plugin>
<plugins> <groupId>org.apache.maven.plugins</groupId>
<plugin> <artifactId>maven-surefire-plugin</artifactId>
<groupId>org.springframework.boot</groupId> <configuration>
<artifactId>spring-boot-maven-plugin</artifactId> <forkCount>3</forkCount>
<configuration> <reuseForks>true</reuseForks>
<mainClass>com.baeldung.Spring5Application</mainClass> <parallel>methods</parallel>
<layout>JAR</layout> <useUnlimitedThreads>true</useUnlimitedThreads>
</configuration> <excludes>
</plugin> <exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<plugin> <repositories>
<groupId>org.apache.maven.plugins</groupId> <repository>
<artifactId>maven-surefire-plugin</artifactId> <id>spring-snapshots</id>
<version>${maven-surefire-plugin.version}</version> <name>Spring Snapshots</name>
<configuration> <url>https://repo.spring.io/snapshot</url>
<forkCount>3</forkCount> <snapshots>
<reuseForks>true</reuseForks> <enabled>true</enabled>
<excludes> </snapshots>
<exclude>**/*IntegrationTest.java</exclude> </repository>
<exclude>**/*LiveTest.java</exclude> <repository>
</excludes> <id>spring-milestones</id>
</configuration> <name>Spring Milestones</name>
</plugin> <url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<plugin> <properties>
<groupId>org.apache.maven.plugins</groupId> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<artifactId>maven-surefire-plugin</artifactId> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<version>${maven-surefire-plugin.version}</version> <java.version>1.8</java.version>
<configuration> <junit.platform.version>1.0.0-M4</junit.platform.version>
<parallel>methods</parallel> <junit.jupiter.version>5.0.0-M4</junit.jupiter.version>
<useUnlimitedThreads>true</useUnlimitedThreads> <maven-surefire-plugin.version>2.20</maven-surefire-plugin.version>
</configuration> <spring.version>5.0.0.RC2</spring.version>
</plugin> <reactor-spring.version>1.0.1.RELEASE</reactor-spring.version>
<johnzon.version>1.1.3</johnzon.version>
</plugins> <jsonb-api.version>1.0</jsonb-api.version>
</build> <geronimo-json_1.1_spec.version>1.0</geronimo-json_1.1_spec.version>
</properties>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<junit.platform.version>1.0.0-M4</junit.platform.version>
<junit.jupiter.version>5.0.0-M4</junit.jupiter.version>
<maven-surefire-plugin.version>2.20</maven-surefire-plugin.version>
<spring.version>5.0.0.RC2</spring.version>
</properties>
</project> </project>

View File

@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication @SpringBootApplication
@ComponentScan(basePackages = {"com.baeldung.web"}) @ComponentScan(basePackages = { "com.baeldung.web" })
public class Spring5Application { public class Spring5Application {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -17,28 +17,25 @@ import static org.springframework.web.reactive.function.server.ServerResponse.ok
public class FormHandler { public class FormHandler {
Mono<ServerResponse> handleLogin(ServerRequest request) { Mono<ServerResponse> handleLogin(ServerRequest request) {
return request return request.body(toFormData())
.body(toFormData()) .map(MultiValueMap::toSingleValueMap)
.map(MultiValueMap::toSingleValueMap) .filter(formData -> "baeldung".equals(formData.get("user")))
.filter(formData -> "baeldung".equals(formData.get("user"))) .filter(formData -> "you_know_what_to_do".equals(formData.get("token")))
.filter(formData -> "you_know_what_to_do".equals(formData.get("token"))) .flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class))
.flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class)) .switchIfEmpty(ServerResponse.badRequest()
.switchIfEmpty(ServerResponse.badRequest().build()); .build());
} }
Mono<ServerResponse> handleUpload(ServerRequest request) { Mono<ServerResponse> handleUpload(ServerRequest request) {
return request return request.body(toDataBuffers())
.body(toDataBuffers()) .collectList()
.collectList() .flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString())));
.flatMap(dataBuffers -> ok()
.body(fromObject(extractData(dataBuffers).toString())));
} }
private AtomicLong extractData(List<DataBuffer> dataBuffers) { private AtomicLong extractData(List<DataBuffer> dataBuffers) {
AtomicLong atomicLong = new AtomicLong(0); AtomicLong atomicLong = new AtomicLong(0);
dataBuffers.forEach(d -> atomicLong.addAndGet(d dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
.asByteBuffer() .array().length));
.array().length));
return atomicLong; return atomicLong;
} }
} }

View File

@ -40,28 +40,25 @@ public class FunctionalSpringBootApplication {
private RouterFunction<ServerResponse> routingFunction() { private RouterFunction<ServerResponse> routingFunction() {
FormHandler formHandler = new FormHandler(); FormHandler formHandler = new FormHandler();
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
.bodyToMono(Actor.class) .doOnNext(actors::add)
.doOnNext(actors::add) .then(ok().build()));
.then(ok().build()));
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/login"), formHandler::handleLogin) .andRoute(POST("/upload"), formHandler::handleUpload)
.andRoute(POST("/upload"), formHandler::handleUpload) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .andNest(path("/actor"), restfulRouter)
.andNest(path("/actor"), restfulRouter) .filter((request, next) -> {
.filter((request, next) -> { System.out.println("Before handler invocation: " + request.path());
System.out.println("Before handler invocation: " + request.path()); return next.handle(request);
return next.handle(request); });
});
} }
@Bean @Bean
public ServletRegistrationBean servletRegistrationBean() throws Exception { public ServletRegistrationBean servletRegistrationBean() throws Exception {
HttpHandler httpHandler = WebHttpHandlerBuilder HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
.webHandler((WebHandler) toHttpHandler(routingFunction())) .prependFilter(new IndexRewriteFilter())
.prependFilter(new IndexRewriteFilter()) .build();
.build();
ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/"); ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/");
registrationBean.setLoadOnStartup(1); registrationBean.setLoadOnStartup(1);
registrationBean.setAsyncSupported(true); registrationBean.setAsyncSupported(true);
@ -74,10 +71,9 @@ public class FunctionalSpringBootApplication {
static class SecurityConfig extends WebSecurityConfigurerAdapter { static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(final HttpSecurity http) throws Exception { protected void configure(final HttpSecurity http) throws Exception {
http http.authorizeRequests()
.authorizeRequests() .anyRequest()
.anyRequest() .permitAll();
.permitAll();
} }
} }

View File

@ -33,28 +33,25 @@ public class FunctionalWebApplication {
private RouterFunction<ServerResponse> routingFunction() { private RouterFunction<ServerResponse> routingFunction() {
FormHandler formHandler = new FormHandler(); FormHandler formHandler = new FormHandler();
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
.bodyToMono(Actor.class) .doOnNext(actors::add)
.doOnNext(actors::add) .then(ok().build()));
.then(ok().build()));
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/login"), formHandler::handleLogin) .andRoute(POST("/upload"), formHandler::handleUpload)
.andRoute(POST("/upload"), formHandler::handleUpload) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .andNest(path("/actor"), restfulRouter)
.andNest(path("/actor"), restfulRouter) .filter((request, next) -> {
.filter((request, next) -> { System.out.println("Before handler invocation: " + request.path());
System.out.println("Before handler invocation: " + request.path()); return next.handle(request);
return next.handle(request); });
});
} }
WebServer start() throws Exception { WebServer start() throws Exception {
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
HttpHandler httpHandler = WebHttpHandlerBuilder HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
.webHandler(webHandler) .prependFilter(new IndexRewriteFilter())
.prependFilter(new IndexRewriteFilter()) .build();
.build();
Tomcat tomcat = new Tomcat(); Tomcat tomcat = new Tomcat();
tomcat.setHostname("localhost"); tomcat.setHostname("localhost");

View File

@ -11,17 +11,15 @@ class IndexRewriteFilter implements WebFilter {
@Override @Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) { public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
ServerHttpRequest request = serverWebExchange.getRequest(); ServerHttpRequest request = serverWebExchange.getRequest();
if (request if (request.getURI()
.getURI() .getPath()
.getPath() .equals("/")) {
.equals("/")) { return webFilterChain.filter(serverWebExchange.mutate()
return webFilterChain.filter(serverWebExchange .request(builder -> builder.method(request.getMethod())
.mutate() .contextPath(request.getPath()
.request(builder -> builder .toString())
.method(request.getMethod()) .path("/test"))
.contextPath(request.getPath().toString()) .build());
.path("/test"))
.build());
} }
return webFilterChain.filter(serverWebExchange); return webFilterChain.filter(serverWebExchange);
} }

View File

@ -2,12 +2,10 @@ package com.baeldung.functional;
import java.util.Random; import java.util.Random;
import org.springframework.stereotype.Component;
public class MyService { public class MyService {
public int getRandomNumber(){ public int getRandomNumber() {
return (new Random().nextInt(10)); return (new Random().nextInt(10));
} }
} }

View File

@ -28,10 +28,9 @@ import org.springframework.web.server.WebHandler;
public class RootServlet extends ServletHttpHandlerAdapter { public class RootServlet extends ServletHttpHandlerAdapter {
public RootServlet() { public RootServlet() {
this(WebHttpHandlerBuilder this(WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
.webHandler((WebHandler) toHttpHandler(routingFunction())) .prependFilter(new IndexRewriteFilter())
.prependFilter(new IndexRewriteFilter()) .build());
.build());
} }
RootServlet(HttpHandler httpHandler) { RootServlet(HttpHandler httpHandler) {
@ -44,44 +43,36 @@ public class RootServlet extends ServletHttpHandlerAdapter {
private static RouterFunction<?> routingFunction() { private static RouterFunction<?> routingFunction() {
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), serverRequest -> serverRequest.body(toFormData())
.andRoute(POST("/login"), serverRequest -> serverRequest
.body(toFormData())
.map(MultiValueMap::toSingleValueMap) .map(MultiValueMap::toSingleValueMap)
.map(formData -> { .map(formData -> {
System.out.println("form data: " + formData.toString()); System.out.println("form data: " + formData.toString());
if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) { if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) {
return ok() return ok().body(Mono.just("welcome back!"), String.class)
.body(Mono.just("welcome back!"), String.class) .block();
.block();
} }
return ServerResponse return ServerResponse.badRequest()
.badRequest() .build()
.build() .block();
.block();
})) }))
.andRoute(POST("/upload"), serverRequest -> serverRequest .andRoute(POST("/upload"), serverRequest -> serverRequest.body(toDataBuffers())
.body(toDataBuffers()) .collectList()
.collectList() .map(dataBuffers -> {
.map(dataBuffers -> { AtomicLong atomicLong = new AtomicLong(0);
AtomicLong atomicLong = new AtomicLong(0); dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
dataBuffers.forEach(d -> atomicLong.addAndGet(d .array().length));
.asByteBuffer() System.out.println("data length:" + atomicLong.get());
.array().length)); return ok().body(fromObject(atomicLong.toString()))
System.out.println("data length:" + atomicLong.get()); .block();
return ok() }))
.body(fromObject(atomicLong.toString())) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.block(); .andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
})) .doOnNext(actors::add)
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .then(ok().build())))
.andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest .filter((request, next) -> {
.bodyToMono(Actor.class) System.out.println("Before handler invocation: " + request.path());
.doOnNext(actors::add) return next.handle(request);
.then(ok().build()))) });
.filter((request, next) -> {
System.out.println("Before handler invocation: " + request.path());
return next.handle(request);
});
} }

View File

@ -0,0 +1,139 @@
package com.baeldung.jsonb;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.json.bind.annotation.JsonbNumberFormat;
import javax.json.bind.annotation.JsonbProperty;
import javax.json.bind.annotation.JsonbTransient;
public class Person {
@JsonbProperty("person-name")
private String name;
@JsonbProperty(nillable = true)
private String email;
@JsonbTransient
private int age;
@JsonbDateFormat("dd-MM-yyyy")
private LocalDate registeredDate;
private BigDecimal salary;
public Person() {
}
public Person(String name, String email, int age, LocalDate registeredDate, BigDecimal salary) {
super();
this.name = name;
this.email = email;
this.age = age;
this.registeredDate = registeredDate;
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonbNumberFormat(locale = "en_US", value = "#0.0")
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public LocalDate getRegisteredDate() {
return registeredDate;
}
public void setRegisteredDate(LocalDate registeredDate) {
this.registeredDate = registeredDate;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [name=");
builder.append(name);
builder.append(", email=");
builder.append(email);
builder.append(", age=");
builder.append(age);
builder.append(", registeredDate=");
builder.append(registeredDate);
builder.append(", salary=");
builder.append(salary);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((registeredDate == null) ? 0 : registeredDate.hashCode());
result = prime * result + ((salary == null) ? 0 : salary.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (registeredDate == null) {
if (other.registeredDate != null)
return false;
} else if (!registeredDate.equals(other.registeredDate))
return false;
if (salary == null) {
if (other.salary != null)
return false;
} else if (!salary.equals(other.salary))
return false;
return true;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.jsonb;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController("/person")
public class PersonController {
List<Person> personRepository;
@PostConstruct
public void init() {
// @formatter:off
personRepository = new ArrayList<>(Arrays.asList(
new Person("Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person("Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person("Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person("Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person("Mark", "mark@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1200)),
new Person("Julia", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000))));
// @formatter:on
}
@GetMapping("/person/{id}")
@ResponseBody
public Person findById(@PathVariable final int id) {
return personRepository.get(id);
}
@PostMapping("/person")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public boolean insertPerson(@RequestBody final Person person) {
return personRepository.add(person);
}
@GetMapping("/person")
@ResponseBody
public List<Person> findAll() {
return personRepository;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.jsonb;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.JsonbHttpMessageConverter;
@SpringBootApplication
@ComponentScan(basePackages = { "com.baeldung.jsonb" })
public class Spring5Application {
public static void main(String[] args) {
SpringApplication.run(Spring5Application.class, args);
}
@Bean
public HttpMessageConverters customConverters() {
Collection<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
JsonbHttpMessageConverter jsonbHttpMessageConverter = new JsonbHttpMessageConverter();
messageConverters.add(jsonbHttpMessageConverter);
return new HttpMessageConverters(true, messageConverters);
}
}

View File

@ -27,16 +27,14 @@ abstract class ParameterAutowireUtils {
public static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) { public static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) {
boolean required = findMergedAnnotation(parameter, Autowired.class) boolean required = findMergedAnnotation(parameter, Autowired.class).map(Autowired::required)
.map(Autowired::required) .orElse(true);
.orElse(true);
MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter)); MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter));
DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required); DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required);
descriptor.setContainingClass(containingClass); descriptor.setContainingClass(containingClass);
return applicationContext return applicationContext.getAutowireCapableBeanFactory()
.getAutowireCapableBeanFactory() .resolveDependency(descriptor, null);
.resolveDependency(descriptor, null);
} }
private static <A extends Annotation> Optional<A> findMergedAnnotation(AnnotatedElement element, Class<A> annotationType) { private static <A extends Annotation> Optional<A> findMergedAnnotation(AnnotatedElement element, Class<A> annotationType) {

View File

@ -26,11 +26,9 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
try { try {
getTestContextManager(context).afterTestClass(); getTestContextManager(context).afterTestClass();
} finally { } finally {
context context.getStore(namespace)
.getStore(namespace) .remove(context.getTestClass()
.remove(context .get());
.getTestClass()
.get());
} }
} }
@ -42,21 +40,18 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
@Override @Override
public void beforeEach(TestExtensionContext context) throws Exception { public void beforeEach(TestExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance(); Object testInstance = context.getTestInstance();
Method testMethod = context Method testMethod = context.getTestMethod()
.getTestMethod() .get();
.get();
getTestContextManager(context).beforeTestMethod(testInstance, testMethod); getTestContextManager(context).beforeTestMethod(testInstance, testMethod);
} }
@Override @Override
public void afterEach(TestExtensionContext context) throws Exception { public void afterEach(TestExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance(); Object testInstance = context.getTestInstance();
Method testMethod = context Method testMethod = context.getTestMethod()
.getTestMethod() .get();
.get(); Throwable testException = context.getTestException()
Throwable testException = context .orElse(null);
.getTestException()
.orElse(null);
getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException); getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException);
} }
@ -70,24 +65,21 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
@Override @Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) { public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) {
Parameter parameter = parameterContext.getParameter(); Parameter parameter = parameterContext.getParameter();
Class<?> testClass = extensionContext Class<?> testClass = extensionContext.getTestClass()
.getTestClass() .get();
.get();
ApplicationContext applicationContext = getApplicationContext(extensionContext); ApplicationContext applicationContext = getApplicationContext(extensionContext);
return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext); return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext);
} }
private ApplicationContext getApplicationContext(ExtensionContext context) { private ApplicationContext getApplicationContext(ExtensionContext context) {
return getTestContextManager(context) return getTestContextManager(context).getTestContext()
.getTestContext() .getApplicationContext();
.getApplicationContext();
} }
private TestContextManager getTestContextManager(ExtensionContext context) { private TestContextManager getTestContextManager(ExtensionContext context) {
Assert.notNull(context, "ExtensionContext must not be null"); Assert.notNull(context, "ExtensionContext must not be null");
Class<?> testClass = context Class<?> testClass = context.getTestClass()
.getTestClass() .get();
.get();
ExtensionContext.Store store = context.getStore(namespace); ExtensionContext.Store store = context.getStore(namespace);
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class); return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
} }

View File

@ -26,8 +26,7 @@ public @interface SpringJUnit5Config {
String[] locations() default {}; String[] locations() default {};
@AliasFor(annotation = ContextConfiguration.class) @AliasFor(annotation = ContextConfiguration.class)
Class<? extends ApplicationContextInitializer<? Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>[] initializers() default {};
extends ConfigurableApplicationContext>>[] initializers() default {};
@AliasFor(annotation = ContextConfiguration.class) @AliasFor(annotation = ContextConfiguration.class)
boolean inheritLocations() default true; boolean inheritLocations() default true;

View File

@ -20,7 +20,8 @@ public class DataSetupBean implements InitializingBean {
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
IntStream.range(1, 20).forEach(i -> repo.save(new Foo(randomAlphabetic(8)))); IntStream.range(1, 20)
.forEach(i -> repo.save(new Foo(randomAlphabetic(8))));
} }
} }

View File

@ -23,7 +23,8 @@ public class FooController {
@ResponseBody @ResponseBody
@Validated @Validated
public Foo findById(@PathVariable @Min(0) final long id) { public Foo findById(@PathVariable @Min(0) final long id) {
return repo.findById(id).orElse(null); return repo.findById(id)
.orElse(null);
} }
@GetMapping @GetMapping
@ -36,7 +37,8 @@ public class FooController {
@ResponseBody @ResponseBody
@Validated @Validated
public List<Foo> findPaginated(@RequestParam("page") @Min(0) final int page, @Max(100) @RequestParam("size") final int size) { public List<Foo> findPaginated(@RequestParam("page") @Min(0) final int page, @Max(100) @RequestParam("size") final int size) {
return repo.findAll(PageRequest.of(page, size)).getContent(); return repo.findAll(PageRequest.of(page, size))
.getContent();
} }
// API - write // API - write

View File

@ -23,9 +23,6 @@ public class Task {
@Override @Override
public String toString() { public String toString() {
return "Task{" + return "Task{" + "name='" + name + '\'' + ", id=" + id + '}';
"name='" + name + '\'' +
", id=" + id +
'}';
} }
} }

View File

@ -33,17 +33,17 @@ public class WebClientController {
WebClient.UriSpec<WebClient.RequestBodySpec> request2 = createWebClientWithServerURLAndDefaultValues().post(); WebClient.UriSpec<WebClient.RequestBodySpec> request2 = createWebClientWithServerURLAndDefaultValues().post();
// request body specifications // request body specifications
WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST).uri("/resource"); WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST)
WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post().uri(URI.create("/resource")); .uri("/resource");
WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post()
.uri(URI.create("/resource"));
// request header specification // request header specification
WebClient.RequestHeadersSpec<?> requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class)); WebClient.RequestHeadersSpec<?> requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class));
WebClient.RequestHeadersSpec<?> requestSpec2 = uri2.body(BodyInserters.fromObject("data")); WebClient.RequestHeadersSpec<?> requestSpec2 = uri2.body(BodyInserters.fromObject("data"));
// inserters // inserters
BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class);
.fromPublisher(Subscriber::onComplete, String.class);
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>(); LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("key1", "value1"); map.add("key1", "value1");
@ -53,14 +53,13 @@ public class WebClientController {
BodyInserter<String, ReactiveHttpOutputMessage> inserter3 = BodyInserters.fromObject("body"); BodyInserter<String, ReactiveHttpOutputMessage> inserter3 = BodyInserters.fromObject("body");
// responses // responses
WebClient.ResponseSpec response1 = uri1 WebClient.ResponseSpec response1 = uri1.body(inserter3)
.body(inserter3) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .acceptCharset(Charset.forName("UTF-8"))
.acceptCharset(Charset.forName("UTF-8")) .ifNoneMatch("*")
.ifNoneMatch("*") .ifModifiedSince(ZonedDateTime.now())
.ifModifiedSince(ZonedDateTime.now()) .retrieve();
.retrieve();
WebClient.ResponseSpec response2 = requestSpec2.retrieve(); WebClient.ResponseSpec response2 = requestSpec2.retrieve();
} }
@ -74,13 +73,12 @@ public class WebClientController {
} }
private WebClient createWebClientWithServerURLAndDefaultValues() { private WebClient createWebClientWithServerURLAndDefaultValues() {
return WebClient return WebClient.builder()
.builder() .baseUrl("http://localhost:8081")
.baseUrl("http://localhost:8081") .defaultCookie("cookieKey", "cookieValue")
.defaultCookie("cookieKey", "cookieValue") .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080"))
.defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) .build();
.build();
} }
} }

View File

@ -9,14 +9,14 @@ public class ParallelIntegrationTest {
@Test @Test
public void runTests() { public void runTests() {
final Class<?>[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new Computer(), classes); JUnitCore.runClasses(new Computer(), classes);
} }
@Test @Test
public void runTestsInParallel() { public void runTestsInParallel() {
final Class<?>[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class}; final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new ParallelComputer(true, true), classes); JUnitCore.runClasses(new ParallelComputer(true, true), classes);
} }

View File

@ -50,5 +50,3 @@ public class Spring5JUnit4ConcurrentIntegrationTest implements ApplicationContex
} }
} }

View File

@ -23,10 +23,9 @@ public class FunctionalWebApplicationIntegrationTest {
@BeforeClass @BeforeClass
public static void setup() throws Exception { public static void setup() throws Exception {
server = new FunctionalWebApplication().start(); server = new FunctionalWebApplication().start();
client = WebTestClient client = WebTestClient.bindToServer()
.bindToServer() .baseUrl("http://localhost:" + server.getPort())
.baseUrl("http://localhost:" + server.getPort()) .build();
.build();
} }
@AfterClass @AfterClass
@ -36,26 +35,24 @@ public class FunctionalWebApplicationIntegrationTest {
@Test @Test
public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception { public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
client client.get()
.get() .uri("/test")
.uri("/test") .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBody(String.class)
.expectBody(String.class) .isEqualTo("helloworld");
.isEqualTo("helloworld");
} }
@Test @Test
public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception { public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
client client.get()
.get() .uri("/")
.uri("/") .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBody(String.class)
.expectBody(String.class) .isEqualTo("helloworld");
.isEqualTo("helloworld");
} }
@Test @Test
@ -64,16 +61,15 @@ public class FunctionalWebApplicationIntegrationTest {
formData.add("user", "baeldung"); formData.add("user", "baeldung");
formData.add("token", "you_know_what_to_do"); formData.add("token", "you_know_what_to_do");
client client.post()
.post() .uri("/login")
.uri("/login") .contentType(MediaType.APPLICATION_FORM_URLENCODED)
.contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(BodyInserters.fromFormData(formData))
.body(BodyInserters.fromFormData(formData)) .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBody(String.class)
.expectBody(String.class) .isEqualTo("welcome back!");
.isEqualTo("welcome back!");
} }
@Test @Test
@ -82,70 +78,64 @@ public class FunctionalWebApplicationIntegrationTest {
formData.add("user", "baeldung"); formData.add("user", "baeldung");
formData.add("token", "try_again"); formData.add("token", "try_again");
client client.post()
.post() .uri("/login")
.uri("/login") .contentType(MediaType.APPLICATION_FORM_URLENCODED)
.contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(BodyInserters.fromFormData(formData))
.body(BodyInserters.fromFormData(formData)) .exchange()
.exchange() .expectStatus()
.expectStatus() .isBadRequest();
.isBadRequest();
} }
@Test @Test
public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception { public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception {
Resource resource = new ClassPathResource("/baeldung-weekly.png"); Resource resource = new ClassPathResource("/baeldung-weekly.png");
client client.post()
.post() .uri("/upload")
.uri("/upload") .contentType(MediaType.MULTIPART_FORM_DATA)
.contentType(MediaType.MULTIPART_FORM_DATA) .body(fromResource(resource))
.body(fromResource(resource)) .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBody(String.class)
.expectBody(String.class) .isEqualTo(String.valueOf(resource.contentLength()));
.isEqualTo(String.valueOf(resource.contentLength()));
} }
@Test @Test
public void givenActors_whenAddActor_thenAdded() throws Exception { public void givenActors_whenAddActor_thenAdded() throws Exception {
client client.get()
.get() .uri("/actor")
.uri("/actor") .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBodyList(Actor.class)
.expectBodyList(Actor.class) .hasSize(2);
.hasSize(2);
client client.post()
.post() .uri("/actor")
.uri("/actor") .body(fromObject(new Actor("Clint", "Eastwood")))
.body(fromObject(new Actor("Clint", "Eastwood"))) .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk();
.isOk();
client client.get()
.get() .uri("/actor")
.uri("/actor") .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBodyList(Actor.class)
.expectBodyList(Actor.class) .hasSize(3);
.hasSize(3);
} }
@Test @Test
public void givenResources_whenAccess_thenGot() throws Exception { public void givenResources_whenAccess_thenGot() throws Exception {
client client.get()
.get() .uri("/files/hello.txt")
.uri("/files/hello.txt") .exchange()
.exchange() .expectStatus()
.expectStatus() .isOk()
.isOk() .expectBody(String.class)
.expectBody(String.class) .isEqualTo("hello");
.isEqualTo("hello");
} }
} }

View File

@ -0,0 +1,44 @@
package com.baeldung.jsonb;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.time.LocalDate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class JsonbIntegrationTest {
@Value("${security.user.name}")
private String username;
@Value("${security.user.password}")
private String password;
@Autowired
private TestRestTemplate template;
@Test
public void givenId_whenUriIsPerson_thenGetPerson() {
ResponseEntity<Person> response = template.withBasicAuth(username, password)
.getForEntity("/person/1", Person.class);
Person person = response.getBody();
assertTrue(person.equals(new Person("Jhon", "jhon1@test.com", 0, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500.0))));
}
@Test
public void whenSendPostAPerson_thenGetOkStatus() {
ResponseEntity<Boolean> response = template.withBasicAuth(username, password)
.postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\"}", Boolean.class);
boolean value = response.getBody();
assertTrue(true == value);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.jsonb;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import org.junit.Before;
import org.junit.Test;
public class JsonbTest {
private Jsonb jsonb;
@Before
public void setup() {
jsonb = JsonbBuilder.create();
}
@Test
public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() {
Person person = new Person("Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000));
String jsonPerson = jsonb.toJson(person);
assertTrue("{\"email\":\"jhon@test.com\",\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}".equals(jsonPerson));
}
@Test
public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() {
Person person = new Person("Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));
String jsonPerson = "{\"email\":\"jhon@test.com\",\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}";
assertTrue(jsonb.fromJson(jsonPerson, Person.class)
.equals(person));
}
}

View File

@ -11,18 +11,14 @@ class Spring5JUnit5ParallelIntegrationTest {
@Test @Test
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() { void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() {
final Class<?>[] classes = { final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
Example1IntegrationTest.class, Example2IntegrationTest.class
};
JUnitCore.runClasses(new ParallelComputer(true, true), classes); JUnitCore.runClasses(new ParallelComputer(true, true), classes);
} }
@Test @Test
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() { void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() {
final Class<?>[] classes = { final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
Example1IntegrationTest.class, Example2IntegrationTest.class
};
JUnitCore.runClasses(new Computer(), classes); JUnitCore.runClasses(new Computer(), classes);
} }

View File

@ -16,18 +16,16 @@ class Spring5Java8NewFeaturesIntegrationTest {
} }
public class StringUtils { public class StringUtils {
FunctionalInterfaceExample<String, String> FunctionalInterfaceExample<String, String> functionLambdaString = s -> Pattern.compile(" +")
functionLambdaString = s -> Pattern.compile(" +").splitAsStream(s) .splitAsStream(s)
.map(word -> new StringBuilder(word).reverse()) .map(word -> new StringBuilder(word).reverse())
.collect(Collectors.joining(" ")); .collect(Collectors.joining(" "));
} }
@Test @Test
void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() throws Exception {
throws Exception {
Supplier<StringUtils> stringUtilsSupplier = StringUtils::new; Supplier<StringUtils> stringUtilsSupplier = StringUtils::new;
assertEquals(stringUtilsSupplier.get().functionLambdaString assertEquals(stringUtilsSupplier.get().functionLambdaString.reverseString("hello"), "olleh");
.reverseString("hello"), "olleh");
} }
} }

View File

@ -25,20 +25,15 @@ public class Spring5ReactiveServerClientIntegrationTest {
@BeforeAll @BeforeAll
public static void setUp() throws Exception { public static void setUp() throws Exception {
HttpServer server = HttpServer.create("localhost", 8080); HttpServer server = HttpServer.create("localhost", 8080);
RouterFunction<?> route = RouterFunctions RouterFunction<?> route = RouterFunctions.route(POST("/task/process"), request -> ServerResponse.ok()
.route(POST("/task/process"), request -> ServerResponse .body(request.bodyToFlux(Task.class)
.ok() .map(ll -> new Task("TaskName", 1)), Task.class))
.body(request .and(RouterFunctions.route(GET("/task"), request -> ServerResponse.ok()
.bodyToFlux(Task.class) .body(Mono.just("server is alive"), String.class)));
.map(ll -> new Task("TaskName", 1)), Task.class))
.and(RouterFunctions.route(GET("/task"), request -> ServerResponse
.ok()
.body(Mono.just("server is alive"), String.class)));
HttpHandler httpHandler = RouterFunctions.toHttpHandler(route); HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
nettyContext = server nettyContext = server.newHandler(adapter)
.newHandler(adapter) .block();
.block();
} }
@AfterAll @AfterAll
@ -46,55 +41,54 @@ public class Spring5ReactiveServerClientIntegrationTest {
nettyContext.dispose(); nettyContext.dispose();
} }
// @Test // @Test
// public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception { // public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception {
// WebClient client = WebClient.create("http://localhost:8080"); // WebClient client = WebClient.create("http://localhost:8080");
// Mono<String> result = client // Mono<String> result = client
// .get() // .get()
// .uri("/task") // .uri("/task")
// .exchange() // .exchange()
// .then(response -> response.bodyToMono(String.class)); // .then(response -> response.bodyToMono(String.class));
// //
// assertThat(result.block()).isInstanceOf(String.class); // assertThat(result.block()).isInstanceOf(String.class);
// } // }
// @Test // @Test
// public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception { // public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception {
// URI uri = URI.create("http://localhost:8080/task/process"); // URI uri = URI.create("http://localhost:8080/task/process");
// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
// ClientRequest request = ClientRequest // ClientRequest request = ClientRequest
// .method(HttpMethod.POST, uri) // .method(HttpMethod.POST, uri)
// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
// .build(); // .build();
// //
// Flux<Task> taskResponse = exchange // Flux<Task> taskResponse = exchange
// .exchange(request) // .exchange(request)
// .flatMap(response -> response.bodyToFlux(Task.class)); // .flatMap(response -> response.bodyToFlux(Task.class));
// //
// assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class); // assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class);
// } // }
// @Test // @Test
// public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception { // public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception {
// URI uri = URI.create("http://localhost:8080/task"); // URI uri = URI.create("http://localhost:8080/task");
// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); // ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
// ClientRequest request = ClientRequest // ClientRequest request = ClientRequest
// .method(HttpMethod.GET, uri) // .method(HttpMethod.GET, uri)
// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class)) // .body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
// .build(); // .build();
// //
// Flux<String> taskResponse = exchange // Flux<String> taskResponse = exchange
// .exchange(request) // .exchange(request)
// .flatMap(response -> response.bodyToFlux(String.class)); // .flatMap(response -> response.bodyToFlux(String.class));
// //
// assertThat(taskResponse.blockFirst()).isInstanceOf(String.class); // assertThat(taskResponse.blockFirst()).isInstanceOf(String.class);
// } // }
private static Flux<Task> getLatLngs() { private static Flux<Task> getLatLngs() {
return Flux return Flux.range(0, 3)
.range(0, 3) .zipWith(Flux.interval(Duration.ofSeconds(1)))
.zipWith(Flux.interval(Duration.ofSeconds(1))) .map(x -> new Task("taskname", 1))
.map(x -> new Task("taskname", 1)) .doOnNext(ll -> System.out.println("Produced: {}" + ll));
.doOnNext(ll -> System.out.println("Produced: {}" + ll));
} }
} }

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