Merge branch 'master' into master
This commit is contained in:
commit
0bc5f8df30
|
@ -8,3 +8,4 @@
|
|||
- [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)
|
||||
- [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)
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant articles
|
||||
- [Introduction to Apache Shiro](http://www.baeldung.com/apache-shiro)
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Introduction to Bootique](http://www.baeldung.com/bootique)
|
|
@ -16,3 +16,4 @@
|
|||
- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
|
||||
- [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)
|
||||
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
||||
|
|
|
@ -18,7 +18,7 @@ public class BaeldungSychronizedBlockTest {
|
|||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
service.awaitTermination(500, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, synchronizedBlocks.getCount());
|
||||
}
|
||||
|
@ -29,7 +29,7 @@ public class BaeldungSychronizedBlockTest {
|
|||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
service.awaitTermination(500, TimeUnit.MILLISECONDS);
|
||||
|
||||
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
|
||||
}
|
||||
|
|
|
@ -99,4 +99,10 @@
|
|||
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
|
||||
- [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 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)
|
||||
|
|
|
@ -211,6 +211,11 @@
|
|||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -239,6 +244,7 @@
|
|||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
|
@ -373,30 +379,7 @@
|
|||
</configuration>
|
||||
</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>
|
||||
|
||||
</build>
|
||||
|
@ -431,6 +414,31 @@
|
|||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</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>
|
||||
</build>
|
||||
</profile>
|
||||
|
@ -461,7 +469,7 @@
|
|||
<protonpack.version>1.13</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
|
|
|
@ -1,20 +1,23 @@
|
|||
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.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
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.*;
|
||||
import org.springframework.web.util.UriUtils;
|
||||
|
||||
public class EncoderDecoderUnitTest {
|
||||
|
||||
|
@ -76,19 +79,20 @@ public class EncoderDecoderUnitTest {
|
|||
|
||||
private String encodePath(String path) {
|
||||
try {
|
||||
path = new URI(null, null, path, null).getPath();
|
||||
} catch (URISyntaxException e) {
|
||||
path = UriUtils.encodePath(path, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_thenEncodeDecodePath() throws URISyntaxException {
|
||||
URI uri = new URI(null, null, "/Path 1/Path+2", null);
|
||||
|
||||
Assert.assertEquals("/Path 1/Path+2", uri.getPath());
|
||||
Assert.assertEquals("/Path%201/Path+2", uri.getRawPath());
|
||||
public void givenPathSegment_thenEncodeDecode() throws UnsupportedEncodingException {
|
||||
String pathSegment = "/Path 1/Path+2";
|
||||
String encodedPathSegment = encodePath(pathSegment);
|
||||
String decodedPathSegment = UriUtils.decode(encodedPathSegment, "UTF-8");
|
||||
Assert.assertEquals("/Path%201/Path+2", encodedPathSegment);
|
||||
Assert.assertEquals("/Path 1/Path+2", decodedPathSegment);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -8,10 +8,10 @@ import org.junit.After;
|
|||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NioEchoIntegrationTest {
|
||||
public class NioEchoLiveTest {
|
||||
|
||||
Process server;
|
||||
EchoClient client;
|
||||
private Process server;
|
||||
private EchoClient client;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException, InterruptedException {
|
|
@ -21,9 +21,9 @@ import org.junit.After;
|
|||
import org.junit.Before;
|
||||
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;
|
||||
|
|
@ -9,7 +9,7 @@ import java.io.IOException;
|
|||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class UDPIntegrationTest {
|
||||
public class UDPLiveTest {
|
||||
private EchoClient client;
|
||||
|
||||
@Before
|
|
@ -7,7 +7,7 @@ import java.io.IOException;
|
|||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class BroadcastIntegrationTest {
|
||||
public class BroadcastLiveTest {
|
||||
private BroadcastingClient client;
|
||||
|
||||
@Test
|
|
@ -7,7 +7,7 @@ import java.io.IOException;
|
|||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MulticastIntegrationTest {
|
||||
public class MulticastLiveTest {
|
||||
private MulticastingClient client;
|
||||
|
||||
@Test
|
|
@ -7,7 +7,7 @@ import java.io.File;
|
|||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ScreenshotIntegrationTest {
|
||||
public class ScreenshotLiveTest {
|
||||
|
||||
private Screenshot screenshot = new Screenshot("Screenshot.jpg");
|
||||
private File file = new File("Screenshot.jpg");
|
|
@ -0,0 +1,5 @@
|
|||
package org.baeldung.java.diamond;
|
||||
|
||||
public class Car<T extends Engine> implements Vehicle<T> {
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package org.baeldung.java.diamond;
|
||||
|
||||
public class Diesel implements Engine {
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
System.out.println("Started Diesel...");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package org.baeldung.java.diamond;
|
||||
|
||||
public interface Engine {
|
||||
|
||||
void start();
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package org.baeldung.java.diamond;
|
||||
|
||||
public interface Vehicle<T extends Engine> {
|
||||
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -1,12 +1,8 @@
|
|||
package com.baeldung.geotools;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.vividsolutions.jts.geom.Coordinate;
|
||||
import com.vividsolutions.jts.geom.GeometryFactory;
|
||||
import com.vividsolutions.jts.geom.Point;
|
||||
import org.geotools.data.DataUtilities;
|
||||
import org.geotools.data.DefaultTransaction;
|
||||
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.SimpleFeatureType;
|
||||
|
||||
import com.vividsolutions.jts.geom.Coordinate;
|
||||
import com.vividsolutions.jts.geom.GeometryFactory;
|
||||
import com.vividsolutions.jts.geom.Point;
|
||||
import java.io.File;
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ShapeFile {
|
||||
|
||||
|
@ -41,22 +41,117 @@ public class ShapeFile {
|
|||
|
||||
SimpleFeatureType CITY = createFeatureType();
|
||||
|
||||
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY);
|
||||
|
||||
addLocations(featureBuilder, collection);
|
||||
addLocations(CITY, collection);
|
||||
|
||||
File shapeFile = getNewShapeFile();
|
||||
|
||||
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
|
||||
|
||||
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()
|
||||
.toURL());
|
||||
.toURL());
|
||||
params.put("create spatial index", Boolean.TRUE);
|
||||
|
||||
ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
|
||||
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,
|
||||
// You will need to uncomment this line to set the Coordinate Reference System
|
||||
// newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
|
||||
|
@ -73,11 +168,9 @@ public class ShapeFile {
|
|||
try {
|
||||
featureStore.addFeatures(collection);
|
||||
transaction.commit();
|
||||
|
||||
} catch (Exception problem) {
|
||||
problem.printStackTrace();
|
||||
transaction.rollback();
|
||||
|
||||
} finally {
|
||||
transaction.close();
|
||||
}
|
||||
|
@ -86,102 +179,5 @@ public class ShapeFile {
|
|||
System.out.println(typeName + " does not support read/write access");
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
|
@ -7,21 +7,16 @@ import org.geotools.feature.simple.SimpleFeatureBuilder;
|
|||
import org.junit.Test;
|
||||
import org.opengis.feature.simple.SimpleFeatureType;
|
||||
|
||||
public class GeoToolsUnitTestTest {
|
||||
public class GeoToolsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenFeatureType_whenAddLocations_returnFeatureCollection() {
|
||||
|
||||
DefaultFeatureCollection collection = new DefaultFeatureCollection();
|
||||
|
||||
SimpleFeatureType CITY = ShapeFile.createFeatureType();
|
||||
|
||||
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY);
|
||||
|
||||
ShapeFile.addLocations(featureBuilder, collection);
|
||||
ShapeFile.addLocations(CITY, collection);
|
||||
|
||||
assertNotNull(collection);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Introduction to gRPC](http://www.baeldung.com/grpc-introduction)
|
|
@ -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>
|
|
@ -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()));
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.beanvalidation.service;
|
||||
|
||||
public interface EntityService {
|
||||
|
||||
public String toString();
|
||||
|
||||
public void processEntity();
|
||||
}
|
|
@ -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 + "]";
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -5,3 +5,4 @@
|
|||
- [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)
|
||||
- [Introduction to Testing with Arquillian](http://www.baeldung.com/arquillian)
|
||||
- [Securing Java EE with Spring Security](http://www.baeldung.com/java-ee-spring-security)
|
||||
|
|
|
@ -22,7 +22,7 @@ import com.baeldung.arquillian.Component;
|
|||
import com.baeldung.arquillian.ConvertToLowerCase;
|
||||
|
||||
@RunWith(Arquillian.class)
|
||||
public class ArquillianTest {
|
||||
public class ArquillianLiveTest {
|
||||
|
||||
@Deployment
|
||||
public static JavaArchive createDeployment() {
|
|
@ -5,3 +5,5 @@
|
|||
- [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)
|
||||
- [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)
|
||||
|
||||
|
|
|
@ -13,4 +13,7 @@
|
|||
- [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)
|
||||
- [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)
|
||||
|
||||
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant articles
|
||||
- [Introduction to Reladomo](http://www.baeldung.com/reladomo)
|
|
@ -30,8 +30,17 @@
|
|||
- [Introduction to Neuroph](http://www.baeldung.com/neuroph)
|
||||
- [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)
|
||||
- [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 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.
|
||||
|
||||
|
|
|
@ -140,7 +140,7 @@
|
|||
<artifactId>unit-ri</artifactId>
|
||||
<version>1.0.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons.collections.version}</version>
|
||||
|
@ -487,21 +487,7 @@
|
|||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</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 -->
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
|
@ -517,6 +503,11 @@
|
|||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>adapter-rxjava</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>logging-interceptor</artifactId>
|
||||
<version>3.9.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.darwinsys</groupId>
|
||||
|
@ -591,19 +582,6 @@
|
|||
<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>
|
||||
<repository>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
|
@ -657,11 +635,12 @@
|
|||
<eclipse-collections.version>8.2.0</eclipse-collections.version>
|
||||
<streamex.version>0.6.5</streamex.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>
|
||||
<joda-time.version>2.9.9</joda-time.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>
|
||||
<cache.version>1.0.0</cache.version>
|
||||
<hazelcast.version>3.8.4</hazelcast.version>
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.commons.lang3;
|
||||
|
||||
public class SampleObject {
|
||||
|
||||
//Ignored
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
}
|
|
@ -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 + '}';
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
package com.baeldung.commons.lang3;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotSame;
|
||||
import static org.junit.Assert.assertSame;
|
||||
|
@ -12,12 +13,14 @@ import java.beans.PropertyChangeListener;
|
|||
import java.io.File;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.apache.commons.lang3.ArchUtils;
|
||||
import org.apache.commons.lang3.BooleanUtils;
|
||||
import org.apache.commons.lang3.SystemUtils;
|
||||
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.ConcurrentUtils;
|
||||
import org.apache.commons.lang3.event.EventUtils;
|
||||
|
@ -97,22 +100,37 @@ public class Lang3UtilsTest {
|
|||
public void testAddEventListenerThrowsException() {
|
||||
final ExceptionEventSource src = new ExceptionEventSource();
|
||||
try {
|
||||
EventUtils.addEventListener(src, PropertyChangeListener.class, new PropertyChangeListener() {
|
||||
@Override
|
||||
public void propertyChange(final PropertyChangeEvent e) {
|
||||
// Do nothing!
|
||||
}
|
||||
});
|
||||
EventUtils.addEventListener(src, PropertyChangeListener.class, (PropertyChangeEvent e) -> {
|
||||
/* Change event*/});
|
||||
fail("Add method should have thrown an exception, so method should fail.");
|
||||
} 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 void addPropertyChangeListener(final PropertyChangeListener listener) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLazyInitializer() throws Exception {
|
||||
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
|
||||
SampleObject sampleObjectOne = sampleLazyInitializer.get();
|
||||
SampleObject sampleObjectTwo = sampleLazyInitializer.get();
|
||||
assertEquals(sampleObjectOne, sampleObjectTwo);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -9,11 +9,14 @@ import javax.cache.configuration.FactoryBuilder;
|
|||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CacheLoaderTest {
|
||||
|
||||
private static final String CACHE_NAME = "SimpleCache";
|
||||
|
||||
private Cache<Integer, String> cache;
|
||||
|
||||
@Before
|
||||
|
@ -25,6 +28,12 @@ public class CacheLoaderTest {
|
|||
this.cache = cacheManager.createCache("SimpleCache", config);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
Caching.getCachingProvider()
|
||||
.getCacheManager().destroyCache(CACHE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadingFromStorage_thenCorrect() {
|
||||
for (int i = 1; i < 4; i++) {
|
||||
|
@ -32,4 +41,4 @@ public class CacheLoaderTest {
|
|||
assertEquals("fromCache" + i, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,6 +1,8 @@
|
|||
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.CacheManager;
|
||||
|
@ -8,25 +10,32 @@ import javax.cache.Caching;
|
|||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class EntryProcessorTest {
|
||||
|
||||
private static final String CACHE_NAME = "MyCache";
|
||||
|
||||
private Cache<String, String> cache;
|
||||
|
||||
@Before
|
||||
public void instantiateCache() {
|
||||
CachingProvider cachingProvider = Caching.getCachingProvider();
|
||||
CacheManager cacheManager = cachingProvider.getCacheManager();
|
||||
MutableConfiguration<String, String> config = new MutableConfiguration<String, String>();
|
||||
this.cache = cacheManager.createCache("MyCache", config);
|
||||
MutableConfiguration<String, String> config = new MutableConfiguration<>();
|
||||
this.cache = cacheManager.createCache(CACHE_NAME, config);
|
||||
this.cache.put("key", "value");
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
Caching.getCachingProvider()
|
||||
.getCacheManager().destroyCache(CACHE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyValue_thenCorrect() {
|
||||
this.cache.invoke("key", new SimpleEntryProcessor());
|
||||
assertEquals("value - modified", cache.get("key"));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,6 +1,8 @@
|
|||
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.CacheManager;
|
||||
|
@ -10,14 +12,15 @@ import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
|
|||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class EventListenerTest {
|
||||
|
||||
private static final String CACHE_NAME = "MyCache";
|
||||
|
||||
private Cache<String, String> cache;
|
||||
private SimpleCacheEntryListener listener;
|
||||
MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration;
|
||||
private MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
|
@ -28,9 +31,16 @@ public class EventListenerTest {
|
|||
this.listener = new SimpleCacheEntryListener();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
Caching.getCachingProvider()
|
||||
.getCacheManager().destroyCache(CACHE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
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);
|
||||
|
||||
assertEquals(false, this.listener.getCreated());
|
||||
|
@ -42,4 +52,5 @@ public class EventListenerTest {
|
|||
this.cache.put("key", "newValue");
|
||||
assertEquals(true, this.listener.getUpdated());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.jcache;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.cache.Cache;
|
||||
import javax.cache.CacheManager;
|
||||
|
@ -8,7 +8,7 @@ import javax.cache.Caching;
|
|||
import javax.cache.configuration.MutableConfiguration;
|
||||
import javax.cache.spi.CachingProvider;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class JCacheTest {
|
||||
|
||||
|
@ -24,4 +24,4 @@ public class JCacheTest {
|
|||
assertEquals("value2", cache.get("key2"));
|
||||
cacheManager.close();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -16,7 +16,7 @@ import com.baeldung.retrofit.models.Repository;
|
|||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
public class GitHubBasicApiTest {
|
||||
public class GitHubBasicApiLiveTest {
|
||||
|
||||
GitHubBasicApi gitHub;
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
### Relevant articles
|
||||
|
||||
- [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)
|
||||
|
|
|
@ -22,10 +22,9 @@ public class ArticleController {
|
|||
.mapToObj(i -> generateArticle("Article Title " + i))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Map<String, Object> modelMap = new HashMap<>();
|
||||
modelMap.put("articles", articles);
|
||||
model.put("articles", articles);
|
||||
|
||||
return new ModelAndView("index", modelMap);
|
||||
return new ModelAndView("index", model);
|
||||
}
|
||||
|
||||
private Article generateArticle(String title) {
|
||||
|
|
2
pom.xml
2
pom.xml
|
@ -57,7 +57,7 @@
|
|||
|
||||
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
|
||||
|
||||
|
||||
<module>geotools</module>
|
||||
<module>groovy-spock</module>
|
||||
<module>gson</module>
|
||||
<module>guava</module>
|
||||
|
|
|
@ -3,3 +3,5 @@
|
|||
- [Introduction to Ratpack](http://www.baeldung.com/ratpack)
|
||||
- [Ratpack Google Guice Integration](http://www.baeldung.com/ratpack-google-guice)
|
||||
- [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot)
|
||||
- [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix)
|
||||
|
||||
|
|
|
@ -2,3 +2,4 @@
|
|||
|
||||
- [Dealing with Backpressure with RxJava](http://www.baeldung.com/rxjava-backpressure)
|
||||
- [How to Test RxJava?](http://www.baeldung.com/rxjava-testing)
|
||||
- [Implementing Custom Operators in RxJava](http://www.baeldung.com/rxjava-custom-operators)
|
||||
|
|
|
@ -19,6 +19,18 @@
|
|||
<artifactId>rxjava</artifactId>
|
||||
<version>${rx.java.version}</version>
|
||||
</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>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -9,7 +9,8 @@ public class ConnectableObservableImpl {
|
|||
|
||||
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);
|
||||
|
||||
System.out.println("Connect");
|
||||
|
|
|
@ -3,12 +3,22 @@ package com.baelding.rxjava;
|
|||
import rx.Observable;
|
||||
import rx.observables.BlockingObservable;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
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};
|
||||
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
|
||||
static String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
|
||||
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-----------");
|
||||
Observable<String> observable = Observable.just("Hello");
|
||||
|
@ -28,14 +38,9 @@ public class ObservableImpl {
|
|||
|
||||
System.out.println();
|
||||
System.out.println("-------FlatMap-----------");
|
||||
Observable.from(letters)
|
||||
.flatMap((letter) -> {
|
||||
String[] returnStrings = {letter.toUpperCase(), letter.toLowerCase()};
|
||||
return Observable.from(returnStrings);
|
||||
})
|
||||
.subscribe(
|
||||
System.out::print
|
||||
);
|
||||
Observable.just("book1", "book2")
|
||||
.flatMap(s -> getTitle())
|
||||
.subscribe(System.out::print);
|
||||
|
||||
System.out.println();
|
||||
System.out.println("--------Scan----------");
|
||||
|
@ -55,16 +60,12 @@ public class ObservableImpl {
|
|||
System.out.println("-------Filter-----------");
|
||||
Observable.from(numbers)
|
||||
.filter(i -> (i % 2 == 1))
|
||||
.subscribe(
|
||||
System.out::println
|
||||
);
|
||||
.subscribe(System.out::println);
|
||||
|
||||
System.out.println("------DefaultIfEmpty------------");
|
||||
Observable.empty()
|
||||
.defaultIfEmpty("Observable is empty")
|
||||
.subscribe(
|
||||
System.out::println
|
||||
);
|
||||
.subscribe(System.out::println);
|
||||
|
||||
System.out.println("------DefaultIfEmpty-2-----------");
|
||||
Observable.from(letters)
|
||||
|
|
|
@ -13,8 +13,9 @@ public class ResourceManagement {
|
|||
return resource;
|
||||
},
|
||||
r -> Observable.create(o -> {
|
||||
for (Character c : r.toCharArray())
|
||||
for (Character c : r.toCharArray()) {
|
||||
o.onNext(c);
|
||||
}
|
||||
o.onCompleted();
|
||||
}),
|
||||
r -> System.out.println("Disposed: " + r)
|
||||
|
|
|
@ -1,69 +1,73 @@
|
|||
package com.baelding.rxjava;
|
||||
|
||||
import rx.Observable;
|
||||
import rx.schedulers.Schedulers;
|
||||
import rx.Observer;
|
||||
import rx.subjects.PublishSubject;
|
||||
|
||||
public class SubjectImpl {
|
||||
|
||||
public static final String[] subscriber1 = {""};
|
||||
public static final String[] subscriber2 = {""};
|
||||
public static Integer subscriber1 = 0;
|
||||
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"};
|
||||
Long signal = 500L;
|
||||
PublishSubject<String> subject;
|
||||
subject.subscribe(getFirstObserver());
|
||||
|
||||
synchronized (signal) {
|
||||
subject = PublishSubject.create();
|
||||
subject.subscribe(
|
||||
(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();
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
subject.onNext(1);
|
||||
subject.onNext(2);
|
||||
subject.onNext(3);
|
||||
|
||||
Observable.from(letters)
|
||||
.subscribeOn(Schedulers.computation())
|
||||
.subscribe(
|
||||
subject::onNext,
|
||||
subject::onError,
|
||||
() -> {
|
||||
System.out.println("Subscriber 1 completed ");
|
||||
subject.onCompleted();
|
||||
synchronized (signal) {
|
||||
signal.notify();
|
||||
}
|
||||
subject.subscribe(getSecondObserver());
|
||||
|
||||
subject.onNext(4);
|
||||
subject.onCompleted();
|
||||
return subscriber1 + subscriber2;
|
||||
}
|
||||
|
||||
|
||||
public static Observer<Integer> getFirstObserver() {
|
||||
return new Observer<Integer>() {
|
||||
|
||||
@Override
|
||||
public void onNext(Integer value) {
|
||||
subscriber1 += value;
|
||||
System.out.println("Subscriber1: " + value);
|
||||
}
|
||||
);
|
||||
|
||||
synchronized (signal) {
|
||||
signal.wait();
|
||||
subject.subscribe(
|
||||
(letter) -> {
|
||||
subscriber2[0] += letter;
|
||||
System.out.println("Subscriber 2: " + subscriber2[0]);
|
||||
},
|
||||
subject::onError,
|
||||
() -> System.out.println("Subscriber 2 completed ")
|
||||
);
|
||||
}
|
||||
@Override
|
||||
public void onError(Throwable e) {
|
||||
System.out.println("error");
|
||||
}
|
||||
|
||||
synchronized (signal) {
|
||||
signal.wait();
|
||||
return subscriber1[0] + subscriber2[0];
|
||||
}
|
||||
@Override
|
||||
public void onCompleted() {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,6 +6,7 @@ import rx.observables.ConnectableObservable;
|
|||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.jayway.awaitility.Awaitility.await;
|
||||
import static junit.framework.Assert.assertFalse;
|
||||
import static junit.framework.Assert.assertTrue;
|
||||
|
||||
|
@ -13,15 +14,14 @@ public class ConnectableObservableTest {
|
|||
|
||||
@Test
|
||||
public void givenConnectableObservable_whenConnect_thenGetMessage() throws InterruptedException {
|
||||
final String[] result = {""};
|
||||
ConnectableObservable<Long> connectable = Observable.interval(200, TimeUnit.MILLISECONDS).publish();
|
||||
String[] result = {""};
|
||||
ConnectableObservable<Long> connectable
|
||||
= Observable.interval(500, TimeUnit.MILLISECONDS).publish();
|
||||
connectable.subscribe(i -> result[0] += i);
|
||||
|
||||
assertFalse(result[0].equals("01"));
|
||||
|
||||
connectable.connect();
|
||||
Thread.currentThread().sleep(500);
|
||||
|
||||
assertTrue(result[0].equals("01"));
|
||||
await()
|
||||
.until(() -> assertTrue(result[0].equals("01")));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,10 +2,8 @@ package com.baeldung.rxjava;
|
|||
|
||||
import org.junit.Test;
|
||||
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;
|
||||
|
||||
public class ObservableTest {
|
||||
|
@ -24,41 +22,23 @@ public class ObservableTest {
|
|||
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
|
||||
Observable<String> observable = Observable.from(letters);
|
||||
observable.subscribe(
|
||||
//onNext
|
||||
(i) -> {
|
||||
result += i;
|
||||
},
|
||||
//onError
|
||||
(t) -> {
|
||||
t.printStackTrace();
|
||||
},
|
||||
//onCompleted
|
||||
() -> {
|
||||
result += "Complete";
|
||||
}
|
||||
i -> result += i,
|
||||
Throwable::printStackTrace,
|
||||
() -> result += "_Complete"
|
||||
);
|
||||
assertTrue(result.equals("abcdefgComplete"));
|
||||
assertTrue(result.equals("abcdefg_Complete"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test
|
||||
public void givenArray_whenConvertsObservabletoBlockingObservable_thenReturnFirstElement() {
|
||||
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
|
||||
Observable<String> observable = Observable.from(letters);
|
||||
String blockingObservable = observable.toBlocking().first();
|
||||
|
||||
observable.subscribe(
|
||||
//onNext
|
||||
(i) -> {
|
||||
result += i;
|
||||
},
|
||||
//onError
|
||||
(t) -> {
|
||||
t.printStackTrace();
|
||||
},
|
||||
//onCompleted
|
||||
() -> {
|
||||
result += "Complete";
|
||||
}
|
||||
i -> result += i,
|
||||
Throwable::printStackTrace,
|
||||
() -> result += "_Completed"
|
||||
);
|
||||
assertTrue(String.valueOf(result.charAt(0)).equals(blockingObservable));
|
||||
}
|
||||
|
@ -68,45 +48,31 @@ public class ObservableTest {
|
|||
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
|
||||
|
||||
Observable.from(letters)
|
||||
.map((letter) -> {
|
||||
return letter.toUpperCase();
|
||||
})
|
||||
.subscribe((letter) -> {
|
||||
result += letter;
|
||||
});
|
||||
.map(String::toUpperCase)
|
||||
.subscribe(letter -> result += letter);
|
||||
|
||||
assertTrue(result.equals("ABCDEFG"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenFlatMapAndSubscribe_thenReturnUpperAndLowerCaseLetters() {
|
||||
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
|
||||
|
||||
Observable.from(letters)
|
||||
.flatMap((letter) -> {
|
||||
String[] returnStrings = {letter.toUpperCase(), letter.toLowerCase()};
|
||||
return Observable.from(returnStrings);
|
||||
})
|
||||
.subscribe((letter) -> {
|
||||
result += letter;
|
||||
});
|
||||
Observable.just("book1", "book2")
|
||||
.flatMap(s -> getTitle())
|
||||
.subscribe(l -> result += l);
|
||||
|
||||
assertTrue(result.equals("AaBbCcDdEeFfGg"));
|
||||
assertTrue(result.equals("titletitle"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenScanAndSubscribe_thenReturnTheSumOfAllLetters() {
|
||||
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
|
||||
String[] letters = {"a", "b", "c"};
|
||||
|
||||
Observable.from(letters)
|
||||
.scan(new StringBuilder(), (buffer, nextLetter) -> {
|
||||
return buffer.append(nextLetter);
|
||||
})
|
||||
.subscribe((total) -> {
|
||||
result = total.toString();
|
||||
});
|
||||
.scan(new StringBuilder(), StringBuilder::append)
|
||||
.subscribe(total -> result += total.toString());
|
||||
|
||||
assertTrue(result.equals("abcdefg"));
|
||||
assertTrue(result.equals("aababc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -116,18 +82,16 @@ public class ObservableTest {
|
|||
String[] ODD = {""};
|
||||
|
||||
Observable.from(numbers)
|
||||
.groupBy((i) -> {
|
||||
return 0 == (i % 2) ? "EVEN" : "ODD";
|
||||
})
|
||||
.subscribe((group) -> {
|
||||
group.subscribe((number) -> {
|
||||
if (group.getKey().toString().equals("EVEN")) {
|
||||
EVEN[0] += number;
|
||||
} else {
|
||||
ODD[0] += number;
|
||||
}
|
||||
});
|
||||
});
|
||||
.groupBy(i -> 0 == (i % 2) ? "EVEN" : "ODD")
|
||||
.subscribe(group ->
|
||||
group.subscribe((number) -> {
|
||||
if (group.getKey().toString().equals("EVEN")) {
|
||||
EVEN[0] += number;
|
||||
} else {
|
||||
ODD[0] += number;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
assertTrue(EVEN[0].equals("0246810"));
|
||||
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};
|
||||
|
||||
Observable.from(numbers)
|
||||
.filter((i) -> {
|
||||
return (i % 2 == 1);
|
||||
})
|
||||
.subscribe((i) -> {
|
||||
result += i;
|
||||
});
|
||||
.filter(i -> (i % 2 == 1))
|
||||
.subscribe(i -> result += i);
|
||||
|
||||
assertTrue(result.equals("13579"));
|
||||
}
|
||||
|
@ -152,10 +112,8 @@ public class ObservableTest {
|
|||
public void givenEmptyObservable_whenDefaultIfEmpty_thenGetDefaultMessage() {
|
||||
|
||||
Observable.empty()
|
||||
.defaultIfEmpty("Observable is empty")
|
||||
.subscribe((s) -> {
|
||||
result += s;
|
||||
});
|
||||
.defaultIfEmpty("Observable is empty")
|
||||
.subscribe(s -> result += s);
|
||||
|
||||
assertTrue(result.equals("Observable is empty"));
|
||||
}
|
||||
|
@ -165,11 +123,9 @@ public class ObservableTest {
|
|||
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
|
||||
|
||||
Observable.from(letters)
|
||||
.defaultIfEmpty("Observable is empty")
|
||||
.first()
|
||||
.subscribe((s) -> {
|
||||
result += s;
|
||||
});
|
||||
.defaultIfEmpty("Observable is empty")
|
||||
.first()
|
||||
.subscribe(s -> result += s);
|
||||
|
||||
assertTrue(result.equals("a"));
|
||||
}
|
||||
|
@ -180,12 +136,8 @@ public class ObservableTest {
|
|||
final Integer[] sum = {0};
|
||||
|
||||
Observable.from(numbers)
|
||||
.takeWhile((i) -> {
|
||||
return i < 5;
|
||||
})
|
||||
.subscribe((s) -> {
|
||||
sum[0] += s;
|
||||
});
|
||||
.takeWhile(i -> i < 5)
|
||||
.subscribe(s -> sum[0] += s);
|
||||
|
||||
assertTrue(sum[0] == 10);
|
||||
}
|
||||
|
|
|
@ -10,32 +10,25 @@ public class ResourceManagementTest {
|
|||
@Test
|
||||
public void givenResource_whenUsingOberservable_thenCreatePrintDisposeResource() throws InterruptedException {
|
||||
|
||||
final String[] result = {""};
|
||||
|
||||
String[] result = {""};
|
||||
Observable<Character> values = Observable.using(
|
||||
//a factory function that creates a disposable resource
|
||||
() -> {
|
||||
String resource = "MyResource";
|
||||
return resource;
|
||||
},
|
||||
//a factory function that creates an Observable
|
||||
(resource) -> {
|
||||
return Observable.create(o -> {
|
||||
for (Character c : resource.toCharArray())
|
||||
o.onNext(c);
|
||||
o.onCompleted();
|
||||
});
|
||||
},
|
||||
//a function that disposes of the resource
|
||||
(resource) -> System.out.println("Disposed: " + resource)
|
||||
() -> {
|
||||
return "MyResource";
|
||||
},
|
||||
r -> {
|
||||
return Observable.create(o -> {
|
||||
for (Character c : r.toCharArray())
|
||||
o.onNext(c);
|
||||
o.onCompleted();
|
||||
});
|
||||
},
|
||||
r -> System.out.println("Disposed: " + r)
|
||||
);
|
||||
|
||||
values.subscribe(
|
||||
v -> result[0] += v,
|
||||
e -> result[0] += e
|
||||
v -> result[0] += v,
|
||||
e -> result[0] += e
|
||||
);
|
||||
|
||||
assertTrue(result[0].equals("MyResource"));
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,19 +10,15 @@ public class SingleTest {
|
|||
|
||||
@Test
|
||||
public void givenSingleObservable_whenSuccess_thenGetMessage() throws InterruptedException {
|
||||
final String[] result = {""};
|
||||
Single<String> single = Observable.just("Hello").toSingle()
|
||||
.doOnSuccess(
|
||||
(i) -> {
|
||||
result[0] += i;
|
||||
})
|
||||
.doOnError(
|
||||
(error) -> {
|
||||
throw new RuntimeException(error.getMessage());
|
||||
});
|
||||
String[] result = {""};
|
||||
Single<String> single = Observable.just("Hello")
|
||||
.toSingle()
|
||||
.doOnSuccess(i -> result[0] += i)
|
||||
.doOnError(error -> {
|
||||
throw new RuntimeException(error.getMessage());
|
||||
});
|
||||
single.subscribe();
|
||||
|
||||
assertTrue(result[0].equals("Hello"));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,16 +2,25 @@ package com.baeldung.rxjava;
|
|||
|
||||
import com.baelding.rxjava.SubjectImpl;
|
||||
import org.junit.Test;
|
||||
import rx.subjects.PublishSubject;
|
||||
|
||||
import static junit.framework.Assert.assertTrue;
|
||||
|
||||
public class SubjectTest {
|
||||
|
||||
@Test
|
||||
public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubjectAfterLetterC_thenSecondSubscriberBeginsToPrint() throws InterruptedException {
|
||||
String result = SubjectImpl.subjectMethod();
|
||||
String subscribers = SubjectImpl.subscriber1[0] + SubjectImpl.subscriber2[0];
|
||||
public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd(){
|
||||
PublishSubject<Integer> subject = PublishSubject.create();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -66,7 +66,6 @@
|
|||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.module</groupId>
|
||||
<artifactId>jackson-module-kotlin</artifactId>
|
||||
<version>2.8.7</version>
|
||||
</dependency>
|
||||
|
||||
<!-- runtime and test scoped -->
|
||||
|
|
|
@ -14,16 +14,19 @@ public class LiveTest {
|
|||
|
||||
private static String APP_ROOT = "http://localhost:8081";
|
||||
|
||||
|
||||
@Test
|
||||
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());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
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());
|
||||
}
|
||||
|
||||
|
@ -32,21 +35,22 @@ public class LiveTest {
|
|||
final Response response = givenAuth("user", "pass").get(APP_ROOT + "/foos");
|
||||
assertEquals(200, response.getStatusCode());
|
||||
}*/
|
||||
|
||||
|
||||
|
||||
//
|
||||
|
||||
private final String resourceWithNullName() {
|
||||
return "{\"name\":null}";
|
||||
}
|
||||
|
||||
|
||||
private final String resourceString() {
|
||||
return "{\"name\":\"" + randomAlphabetic(8) + "\"}";
|
||||
}
|
||||
}
|
||||
|
||||
private final RequestSpecification givenAuth(String username, String password) {
|
||||
return RestAssured.given().auth().preemptive().basic(username, password);
|
||||
return RestAssured.given()
|
||||
.auth()
|
||||
.preemptive()
|
||||
.basic(username, password);
|
||||
}
|
||||
|
||||
}
|
|
@ -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)
|
||||
- [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 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans)
|
||||
|
||||
|
|
350
spring-5/pom.xml
350
spring-5/pom.xml
|
@ -1,188 +1,196 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
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>spring-5</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-5</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>spring-5</name>
|
||||
<description>spring 5 sample project about new features</description>
|
||||
<name>spring-5</name>
|
||||
<description>spring 5 sample project about new features</description>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.M1</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.M1</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectreactor</groupId>
|
||||
<artifactId>reactor-spring</artifactId>
|
||||
<version>1.0.1.RELEASE</version>
|
||||
</dependency>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectreactor</groupId>
|
||||
<artifactId>reactor-spring</artifactId>
|
||||
<version>${reactor-spring.version}</version>
|
||||
</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 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
</dependency>
|
||||
<!-- runtime and test scoped -->
|
||||
|
||||
<!-- 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>
|
||||
<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>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<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>
|
||||
|
||||
<dependency>
|
||||
<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>
|
||||
|
||||
</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>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.Spring5Application</mainClass>
|
||||
<layout>JAR</layout>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<forkCount>3</forkCount>
|
||||
<reuseForks>true</reuseForks>
|
||||
<parallel>methods</parallel>
|
||||
<useUnlimitedThreads>true</useUnlimitedThreads>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<forkCount>3</forkCount>
|
||||
<reuseForks>true</reuseForks>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<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>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<parallel>methods</parallel>
|
||||
<useUnlimitedThreads>true</useUnlimitedThreads>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
<reactor-spring.version>1.0.1.RELEASE</reactor-spring.version>
|
||||
<johnzon.version>1.1.3</johnzon.version>
|
||||
<jsonb-api.version>1.0</jsonb-api.version>
|
||||
<geronimo-json_1.1_spec.version>1.0</geronimo-json_1.1_spec.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages = {"com.baeldung.web"})
|
||||
@ComponentScan(basePackages = { "com.baeldung.web" })
|
||||
public class Spring5Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
|
|
@ -17,28 +17,25 @@ import static org.springframework.web.reactive.function.server.ServerResponse.ok
|
|||
public class FormHandler {
|
||||
|
||||
Mono<ServerResponse> handleLogin(ServerRequest request) {
|
||||
return request
|
||||
.body(toFormData())
|
||||
.map(MultiValueMap::toSingleValueMap)
|
||||
.filter(formData -> "baeldung".equals(formData.get("user")))
|
||||
.filter(formData -> "you_know_what_to_do".equals(formData.get("token")))
|
||||
.flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class))
|
||||
.switchIfEmpty(ServerResponse.badRequest().build());
|
||||
return request.body(toFormData())
|
||||
.map(MultiValueMap::toSingleValueMap)
|
||||
.filter(formData -> "baeldung".equals(formData.get("user")))
|
||||
.filter(formData -> "you_know_what_to_do".equals(formData.get("token")))
|
||||
.flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class))
|
||||
.switchIfEmpty(ServerResponse.badRequest()
|
||||
.build());
|
||||
}
|
||||
|
||||
Mono<ServerResponse> handleUpload(ServerRequest request) {
|
||||
return request
|
||||
.body(toDataBuffers())
|
||||
.collectList()
|
||||
.flatMap(dataBuffers -> ok()
|
||||
.body(fromObject(extractData(dataBuffers).toString())));
|
||||
return request.body(toDataBuffers())
|
||||
.collectList()
|
||||
.flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString())));
|
||||
}
|
||||
|
||||
private AtomicLong extractData(List<DataBuffer> dataBuffers) {
|
||||
AtomicLong atomicLong = new AtomicLong(0);
|
||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d
|
||||
.asByteBuffer()
|
||||
.array().length));
|
||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
|
||||
.array().length));
|
||||
return atomicLong;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -40,28 +40,25 @@ public class FunctionalSpringBootApplication {
|
|||
private RouterFunction<ServerResponse> routingFunction() {
|
||||
FormHandler formHandler = new FormHandler();
|
||||
|
||||
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest
|
||||
.bodyToMono(Actor.class)
|
||||
.doOnNext(actors::add)
|
||||
.then(ok().build()));
|
||||
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
|
||||
.doOnNext(actors::add)
|
||||
.then(ok().build()));
|
||||
|
||||
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld")))
|
||||
.andRoute(POST("/login"), formHandler::handleLogin)
|
||||
.andRoute(POST("/upload"), formHandler::handleUpload)
|
||||
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
|
||||
.andNest(path("/actor"), restfulRouter)
|
||||
.filter((request, next) -> {
|
||||
System.out.println("Before handler invocation: " + request.path());
|
||||
return next.handle(request);
|
||||
});
|
||||
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
|
||||
.andRoute(POST("/upload"), formHandler::handleUpload)
|
||||
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
|
||||
.andNest(path("/actor"), restfulRouter)
|
||||
.filter((request, next) -> {
|
||||
System.out.println("Before handler invocation: " + request.path());
|
||||
return next.handle(request);
|
||||
});
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ServletRegistrationBean servletRegistrationBean() throws Exception {
|
||||
HttpHandler httpHandler = WebHttpHandlerBuilder
|
||||
.webHandler((WebHandler) toHttpHandler(routingFunction()))
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.build();
|
||||
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.build();
|
||||
ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/");
|
||||
registrationBean.setLoadOnStartup(1);
|
||||
registrationBean.setAsyncSupported(true);
|
||||
|
@ -74,10 +71,9 @@ public class FunctionalSpringBootApplication {
|
|||
static class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Override
|
||||
protected void configure(final HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.anyRequest()
|
||||
.permitAll();
|
||||
http.authorizeRequests()
|
||||
.anyRequest()
|
||||
.permitAll();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -33,28 +33,25 @@ public class FunctionalWebApplication {
|
|||
private RouterFunction<ServerResponse> routingFunction() {
|
||||
FormHandler formHandler = new FormHandler();
|
||||
|
||||
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest
|
||||
.bodyToMono(Actor.class)
|
||||
.doOnNext(actors::add)
|
||||
.then(ok().build()));
|
||||
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
|
||||
.doOnNext(actors::add)
|
||||
.then(ok().build()));
|
||||
|
||||
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld")))
|
||||
.andRoute(POST("/login"), formHandler::handleLogin)
|
||||
.andRoute(POST("/upload"), formHandler::handleUpload)
|
||||
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
|
||||
.andNest(path("/actor"), restfulRouter)
|
||||
.filter((request, next) -> {
|
||||
System.out.println("Before handler invocation: " + request.path());
|
||||
return next.handle(request);
|
||||
});
|
||||
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
|
||||
.andRoute(POST("/upload"), formHandler::handleUpload)
|
||||
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
|
||||
.andNest(path("/actor"), restfulRouter)
|
||||
.filter((request, next) -> {
|
||||
System.out.println("Before handler invocation: " + request.path());
|
||||
return next.handle(request);
|
||||
});
|
||||
}
|
||||
|
||||
WebServer start() throws Exception {
|
||||
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
|
||||
HttpHandler httpHandler = WebHttpHandlerBuilder
|
||||
.webHandler(webHandler)
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.build();
|
||||
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.build();
|
||||
|
||||
Tomcat tomcat = new Tomcat();
|
||||
tomcat.setHostname("localhost");
|
||||
|
|
|
@ -11,17 +11,15 @@ class IndexRewriteFilter implements WebFilter {
|
|||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
|
||||
ServerHttpRequest request = serverWebExchange.getRequest();
|
||||
if (request
|
||||
.getURI()
|
||||
.getPath()
|
||||
.equals("/")) {
|
||||
return webFilterChain.filter(serverWebExchange
|
||||
.mutate()
|
||||
.request(builder -> builder
|
||||
.method(request.getMethod())
|
||||
.contextPath(request.getPath().toString())
|
||||
.path("/test"))
|
||||
.build());
|
||||
if (request.getURI()
|
||||
.getPath()
|
||||
.equals("/")) {
|
||||
return webFilterChain.filter(serverWebExchange.mutate()
|
||||
.request(builder -> builder.method(request.getMethod())
|
||||
.contextPath(request.getPath()
|
||||
.toString())
|
||||
.path("/test"))
|
||||
.build());
|
||||
}
|
||||
return webFilterChain.filter(serverWebExchange);
|
||||
}
|
||||
|
|
|
@ -2,12 +2,10 @@ package com.baeldung.functional;
|
|||
|
||||
import java.util.Random;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
public class MyService {
|
||||
|
||||
public int getRandomNumber(){
|
||||
public int getRandomNumber() {
|
||||
return (new Random().nextInt(10));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -28,10 +28,9 @@ import org.springframework.web.server.WebHandler;
|
|||
public class RootServlet extends ServletHttpHandlerAdapter {
|
||||
|
||||
public RootServlet() {
|
||||
this(WebHttpHandlerBuilder
|
||||
.webHandler((WebHandler) toHttpHandler(routingFunction()))
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.build());
|
||||
this(WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction()))
|
||||
.prependFilter(new IndexRewriteFilter())
|
||||
.build());
|
||||
}
|
||||
|
||||
RootServlet(HttpHandler httpHandler) {
|
||||
|
@ -44,44 +43,36 @@ public class RootServlet extends ServletHttpHandlerAdapter {
|
|||
|
||||
private static RouterFunction<?> routingFunction() {
|
||||
|
||||
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld")))
|
||||
.andRoute(POST("/login"), serverRequest -> serverRequest
|
||||
.body(toFormData())
|
||||
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), serverRequest -> serverRequest.body(toFormData())
|
||||
.map(MultiValueMap::toSingleValueMap)
|
||||
.map(formData -> {
|
||||
System.out.println("form data: " + formData.toString());
|
||||
if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) {
|
||||
return ok()
|
||||
.body(Mono.just("welcome back!"), String.class)
|
||||
.block();
|
||||
return ok().body(Mono.just("welcome back!"), String.class)
|
||||
.block();
|
||||
}
|
||||
return ServerResponse
|
||||
.badRequest()
|
||||
.build()
|
||||
.block();
|
||||
return ServerResponse.badRequest()
|
||||
.build()
|
||||
.block();
|
||||
}))
|
||||
.andRoute(POST("/upload"), serverRequest -> serverRequest
|
||||
.body(toDataBuffers())
|
||||
.collectList()
|
||||
.map(dataBuffers -> {
|
||||
AtomicLong atomicLong = new AtomicLong(0);
|
||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d
|
||||
.asByteBuffer()
|
||||
.array().length));
|
||||
System.out.println("data length:" + atomicLong.get());
|
||||
return ok()
|
||||
.body(fromObject(atomicLong.toString()))
|
||||
.block();
|
||||
}))
|
||||
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
|
||||
.andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest
|
||||
.bodyToMono(Actor.class)
|
||||
.doOnNext(actors::add)
|
||||
.then(ok().build())))
|
||||
.filter((request, next) -> {
|
||||
System.out.println("Before handler invocation: " + request.path());
|
||||
return next.handle(request);
|
||||
});
|
||||
.andRoute(POST("/upload"), serverRequest -> serverRequest.body(toDataBuffers())
|
||||
.collectList()
|
||||
.map(dataBuffers -> {
|
||||
AtomicLong atomicLong = new AtomicLong(0);
|
||||
dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
|
||||
.array().length));
|
||||
System.out.println("data length:" + atomicLong.get());
|
||||
return ok().body(fromObject(atomicLong.toString()))
|
||||
.block();
|
||||
}))
|
||||
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
|
||||
.andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
|
||||
.doOnNext(actors::add)
|
||||
.then(ok().build())))
|
||||
.filter((request, next) -> {
|
||||
System.out.println("Before handler invocation: " + request.path());
|
||||
return next.handle(request);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -27,16 +27,14 @@ abstract class ParameterAutowireUtils {
|
|||
|
||||
public static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) {
|
||||
|
||||
boolean required = findMergedAnnotation(parameter, Autowired.class)
|
||||
.map(Autowired::required)
|
||||
.orElse(true);
|
||||
boolean required = findMergedAnnotation(parameter, Autowired.class).map(Autowired::required)
|
||||
.orElse(true);
|
||||
MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter));
|
||||
DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required);
|
||||
descriptor.setContainingClass(containingClass);
|
||||
|
||||
return applicationContext
|
||||
.getAutowireCapableBeanFactory()
|
||||
.resolveDependency(descriptor, null);
|
||||
return applicationContext.getAutowireCapableBeanFactory()
|
||||
.resolveDependency(descriptor, null);
|
||||
}
|
||||
|
||||
private static <A extends Annotation> Optional<A> findMergedAnnotation(AnnotatedElement element, Class<A> annotationType) {
|
||||
|
|
|
@ -26,11 +26,9 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
|
|||
try {
|
||||
getTestContextManager(context).afterTestClass();
|
||||
} finally {
|
||||
context
|
||||
.getStore(namespace)
|
||||
.remove(context
|
||||
.getTestClass()
|
||||
.get());
|
||||
context.getStore(namespace)
|
||||
.remove(context.getTestClass()
|
||||
.get());
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -42,21 +40,18 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
|
|||
@Override
|
||||
public void beforeEach(TestExtensionContext context) throws Exception {
|
||||
Object testInstance = context.getTestInstance();
|
||||
Method testMethod = context
|
||||
.getTestMethod()
|
||||
.get();
|
||||
Method testMethod = context.getTestMethod()
|
||||
.get();
|
||||
getTestContextManager(context).beforeTestMethod(testInstance, testMethod);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterEach(TestExtensionContext context) throws Exception {
|
||||
Object testInstance = context.getTestInstance();
|
||||
Method testMethod = context
|
||||
.getTestMethod()
|
||||
.get();
|
||||
Throwable testException = context
|
||||
.getTestException()
|
||||
.orElse(null);
|
||||
Method testMethod = context.getTestMethod()
|
||||
.get();
|
||||
Throwable testException = context.getTestException()
|
||||
.orElse(null);
|
||||
getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException);
|
||||
}
|
||||
|
||||
|
@ -70,24 +65,21 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
|
|||
@Override
|
||||
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) {
|
||||
Parameter parameter = parameterContext.getParameter();
|
||||
Class<?> testClass = extensionContext
|
||||
.getTestClass()
|
||||
.get();
|
||||
Class<?> testClass = extensionContext.getTestClass()
|
||||
.get();
|
||||
ApplicationContext applicationContext = getApplicationContext(extensionContext);
|
||||
return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext);
|
||||
}
|
||||
|
||||
private ApplicationContext getApplicationContext(ExtensionContext context) {
|
||||
return getTestContextManager(context)
|
||||
.getTestContext()
|
||||
.getApplicationContext();
|
||||
return getTestContextManager(context).getTestContext()
|
||||
.getApplicationContext();
|
||||
}
|
||||
|
||||
private TestContextManager getTestContextManager(ExtensionContext context) {
|
||||
Assert.notNull(context, "ExtensionContext must not be null");
|
||||
Class<?> testClass = context
|
||||
.getTestClass()
|
||||
.get();
|
||||
Class<?> testClass = context.getTestClass()
|
||||
.get();
|
||||
ExtensionContext.Store store = context.getStore(namespace);
|
||||
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
|
||||
}
|
||||
|
|
|
@ -26,8 +26,7 @@ public @interface SpringJUnit5Config {
|
|||
String[] locations() default {};
|
||||
|
||||
@AliasFor(annotation = ContextConfiguration.class)
|
||||
Class<? extends ApplicationContextInitializer<?
|
||||
extends ConfigurableApplicationContext>>[] initializers() default {};
|
||||
Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>[] initializers() default {};
|
||||
|
||||
@AliasFor(annotation = ContextConfiguration.class)
|
||||
boolean inheritLocations() default true;
|
||||
|
|
|
@ -20,7 +20,8 @@ public class DataSetupBean implements InitializingBean {
|
|||
|
||||
@Override
|
||||
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))));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -23,7 +23,8 @@ public class FooController {
|
|||
@ResponseBody
|
||||
@Validated
|
||||
public Foo findById(@PathVariable @Min(0) final long id) {
|
||||
return repo.findById(id).orElse(null);
|
||||
return repo.findById(id)
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
|
@ -36,7 +37,8 @@ public class FooController {
|
|||
@ResponseBody
|
||||
@Validated
|
||||
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
|
||||
|
|
|
@ -23,9 +23,6 @@ public class Task {
|
|||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Task{" +
|
||||
"name='" + name + '\'' +
|
||||
", id=" + id +
|
||||
'}';
|
||||
return "Task{" + "name='" + name + '\'' + ", id=" + id + '}';
|
||||
}
|
||||
}
|
||||
|
|
|
@ -33,17 +33,17 @@ public class WebClientController {
|
|||
WebClient.UriSpec<WebClient.RequestBodySpec> request2 = createWebClientWithServerURLAndDefaultValues().post();
|
||||
|
||||
// request body specifications
|
||||
WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST).uri("/resource");
|
||||
WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post().uri(URI.create("/resource"));
|
||||
WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST)
|
||||
.uri("/resource");
|
||||
WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post()
|
||||
.uri(URI.create("/resource"));
|
||||
|
||||
// request header specification
|
||||
WebClient.RequestHeadersSpec<?> requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class));
|
||||
WebClient.RequestHeadersSpec<?> requestSpec2 = uri2.body(BodyInserters.fromObject("data"));
|
||||
|
||||
// inserters
|
||||
BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters
|
||||
.fromPublisher(Subscriber::onComplete, String.class);
|
||||
|
||||
BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class);
|
||||
|
||||
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
|
||||
map.add("key1", "value1");
|
||||
|
@ -53,14 +53,13 @@ public class WebClientController {
|
|||
BodyInserter<String, ReactiveHttpOutputMessage> inserter3 = BodyInserters.fromObject("body");
|
||||
|
||||
// responses
|
||||
WebClient.ResponseSpec response1 = uri1
|
||||
.body(inserter3)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
|
||||
.acceptCharset(Charset.forName("UTF-8"))
|
||||
.ifNoneMatch("*")
|
||||
.ifModifiedSince(ZonedDateTime.now())
|
||||
.retrieve();
|
||||
WebClient.ResponseSpec response1 = uri1.body(inserter3)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
|
||||
.acceptCharset(Charset.forName("UTF-8"))
|
||||
.ifNoneMatch("*")
|
||||
.ifModifiedSince(ZonedDateTime.now())
|
||||
.retrieve();
|
||||
WebClient.ResponseSpec response2 = requestSpec2.retrieve();
|
||||
|
||||
}
|
||||
|
@ -74,13 +73,12 @@ public class WebClientController {
|
|||
}
|
||||
|
||||
private WebClient createWebClientWithServerURLAndDefaultValues() {
|
||||
return WebClient
|
||||
.builder()
|
||||
.baseUrl("http://localhost:8081")
|
||||
.defaultCookie("cookieKey", "cookieValue")
|
||||
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080"))
|
||||
.build();
|
||||
return WebClient.builder()
|
||||
.baseUrl("http://localhost:8081")
|
||||
.defaultCookie("cookieKey", "cookieValue")
|
||||
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080"))
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -9,14 +9,14 @@ public class ParallelIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void runTests() {
|
||||
final Class<?>[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class};
|
||||
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
|
||||
|
||||
JUnitCore.runClasses(new Computer(), classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runTestsInParallel() {
|
||||
final Class<?>[] classes = {Example1IntegrationTest.class, Example2IntegrationTest.class};
|
||||
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
|
||||
|
||||
JUnitCore.runClasses(new ParallelComputer(true, true), classes);
|
||||
}
|
||||
|
|
|
@ -50,5 +50,3 @@ public class Spring5JUnit4ConcurrentIntegrationTest implements ApplicationContex
|
|||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -23,10 +23,9 @@ public class FunctionalWebApplicationIntegrationTest {
|
|||
@BeforeClass
|
||||
public static void setup() throws Exception {
|
||||
server = new FunctionalWebApplication().start();
|
||||
client = WebTestClient
|
||||
.bindToServer()
|
||||
.baseUrl("http://localhost:" + server.getPort())
|
||||
.build();
|
||||
client = WebTestClient.bindToServer()
|
||||
.baseUrl("http://localhost:" + server.getPort())
|
||||
.build();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
|
@ -36,26 +35,24 @@ public class FunctionalWebApplicationIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
|
||||
client
|
||||
.get()
|
||||
.uri("/test")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("helloworld");
|
||||
client.get()
|
||||
.uri("/test")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("helloworld");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
|
||||
client
|
||||
.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("helloworld");
|
||||
client.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("helloworld");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -64,16 +61,15 @@ public class FunctionalWebApplicationIntegrationTest {
|
|||
formData.add("user", "baeldung");
|
||||
formData.add("token", "you_know_what_to_do");
|
||||
|
||||
client
|
||||
.post()
|
||||
.uri("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.body(BodyInserters.fromFormData(formData))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("welcome back!");
|
||||
client.post()
|
||||
.uri("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.body(BodyInserters.fromFormData(formData))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("welcome back!");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -82,70 +78,64 @@ public class FunctionalWebApplicationIntegrationTest {
|
|||
formData.add("user", "baeldung");
|
||||
formData.add("token", "try_again");
|
||||
|
||||
client
|
||||
.post()
|
||||
.uri("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.body(BodyInserters.fromFormData(formData))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isBadRequest();
|
||||
client.post()
|
||||
.uri("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.body(BodyInserters.fromFormData(formData))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isBadRequest();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception {
|
||||
Resource resource = new ClassPathResource("/baeldung-weekly.png");
|
||||
client
|
||||
.post()
|
||||
.uri("/upload")
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.body(fromResource(resource))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo(String.valueOf(resource.contentLength()));
|
||||
client.post()
|
||||
.uri("/upload")
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.body(fromResource(resource))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo(String.valueOf(resource.contentLength()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenActors_whenAddActor_thenAdded() throws Exception {
|
||||
client
|
||||
.get()
|
||||
.uri("/actor")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBodyList(Actor.class)
|
||||
.hasSize(2);
|
||||
client.get()
|
||||
.uri("/actor")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBodyList(Actor.class)
|
||||
.hasSize(2);
|
||||
|
||||
client
|
||||
.post()
|
||||
.uri("/actor")
|
||||
.body(fromObject(new Actor("Clint", "Eastwood")))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
client.post()
|
||||
.uri("/actor")
|
||||
.body(fromObject(new Actor("Clint", "Eastwood")))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
|
||||
client
|
||||
.get()
|
||||
.uri("/actor")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBodyList(Actor.class)
|
||||
.hasSize(3);
|
||||
client.get()
|
||||
.uri("/actor")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBodyList(Actor.class)
|
||||
.hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResources_whenAccess_thenGot() throws Exception {
|
||||
client
|
||||
.get()
|
||||
.uri("/files/hello.txt")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("hello");
|
||||
client.get()
|
||||
.uri("/files/hello.txt")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("hello");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -11,18 +11,14 @@ class Spring5JUnit5ParallelIntegrationTest {
|
|||
|
||||
@Test
|
||||
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() {
|
||||
final Class<?>[] classes = {
|
||||
Example1IntegrationTest.class, Example2IntegrationTest.class
|
||||
};
|
||||
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
|
||||
|
||||
JUnitCore.runClasses(new ParallelComputer(true, true), classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() {
|
||||
final Class<?>[] classes = {
|
||||
Example1IntegrationTest.class, Example2IntegrationTest.class
|
||||
};
|
||||
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
|
||||
|
||||
JUnitCore.runClasses(new Computer(), classes);
|
||||
}
|
||||
|
|
|
@ -16,18 +16,16 @@ class Spring5Java8NewFeaturesIntegrationTest {
|
|||
}
|
||||
|
||||
public class StringUtils {
|
||||
FunctionalInterfaceExample<String, String>
|
||||
functionLambdaString = s -> Pattern.compile(" +").splitAsStream(s)
|
||||
.map(word -> new StringBuilder(word).reverse())
|
||||
.collect(Collectors.joining(" "));
|
||||
FunctionalInterfaceExample<String, String> functionLambdaString = s -> Pattern.compile(" +")
|
||||
.splitAsStream(s)
|
||||
.map(word -> new StringBuilder(word).reverse())
|
||||
.collect(Collectors.joining(" "));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString()
|
||||
throws Exception {
|
||||
void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() throws Exception {
|
||||
Supplier<StringUtils> stringUtilsSupplier = StringUtils::new;
|
||||
|
||||
assertEquals(stringUtilsSupplier.get().functionLambdaString
|
||||
.reverseString("hello"), "olleh");
|
||||
assertEquals(stringUtilsSupplier.get().functionLambdaString.reverseString("hello"), "olleh");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -25,20 +25,15 @@ public class Spring5ReactiveServerClientIntegrationTest {
|
|||
@BeforeAll
|
||||
public static void setUp() throws Exception {
|
||||
HttpServer server = HttpServer.create("localhost", 8080);
|
||||
RouterFunction<?> route = RouterFunctions
|
||||
.route(POST("/task/process"), request -> ServerResponse
|
||||
.ok()
|
||||
.body(request
|
||||
.bodyToFlux(Task.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)));
|
||||
RouterFunction<?> route = RouterFunctions.route(POST("/task/process"), request -> ServerResponse.ok()
|
||||
.body(request.bodyToFlux(Task.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);
|
||||
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
|
||||
nettyContext = server
|
||||
.newHandler(adapter)
|
||||
.block();
|
||||
nettyContext = server.newHandler(adapter)
|
||||
.block();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
|
@ -46,55 +41,54 @@ public class Spring5ReactiveServerClientIntegrationTest {
|
|||
nettyContext.dispose();
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception {
|
||||
// WebClient client = WebClient.create("http://localhost:8080");
|
||||
// Mono<String> result = client
|
||||
// .get()
|
||||
// .uri("/task")
|
||||
// .exchange()
|
||||
// .then(response -> response.bodyToMono(String.class));
|
||||
//
|
||||
// assertThat(result.block()).isInstanceOf(String.class);
|
||||
// }
|
||||
// @Test
|
||||
// public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception {
|
||||
// WebClient client = WebClient.create("http://localhost:8080");
|
||||
// Mono<String> result = client
|
||||
// .get()
|
||||
// .uri("/task")
|
||||
// .exchange()
|
||||
// .then(response -> response.bodyToMono(String.class));
|
||||
//
|
||||
// assertThat(result.block()).isInstanceOf(String.class);
|
||||
// }
|
||||
|
||||
// @Test
|
||||
// public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception {
|
||||
// URI uri = URI.create("http://localhost:8080/task/process");
|
||||
// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
|
||||
// ClientRequest request = ClientRequest
|
||||
// .method(HttpMethod.POST, uri)
|
||||
// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
|
||||
// .build();
|
||||
//
|
||||
// Flux<Task> taskResponse = exchange
|
||||
// .exchange(request)
|
||||
// .flatMap(response -> response.bodyToFlux(Task.class));
|
||||
//
|
||||
// assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class);
|
||||
// }
|
||||
// @Test
|
||||
// public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception {
|
||||
// URI uri = URI.create("http://localhost:8080/task/process");
|
||||
// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
|
||||
// ClientRequest request = ClientRequest
|
||||
// .method(HttpMethod.POST, uri)
|
||||
// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
|
||||
// .build();
|
||||
//
|
||||
// Flux<Task> taskResponse = exchange
|
||||
// .exchange(request)
|
||||
// .flatMap(response -> response.bodyToFlux(Task.class));
|
||||
//
|
||||
// assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class);
|
||||
// }
|
||||
|
||||
// @Test
|
||||
// public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception {
|
||||
// URI uri = URI.create("http://localhost:8080/task");
|
||||
// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
|
||||
// ClientRequest request = ClientRequest
|
||||
// .method(HttpMethod.GET, uri)
|
||||
// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
|
||||
// .build();
|
||||
//
|
||||
// Flux<String> taskResponse = exchange
|
||||
// .exchange(request)
|
||||
// .flatMap(response -> response.bodyToFlux(String.class));
|
||||
//
|
||||
// assertThat(taskResponse.blockFirst()).isInstanceOf(String.class);
|
||||
// }
|
||||
// @Test
|
||||
// public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception {
|
||||
// URI uri = URI.create("http://localhost:8080/task");
|
||||
// ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
|
||||
// ClientRequest request = ClientRequest
|
||||
// .method(HttpMethod.GET, uri)
|
||||
// .body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
|
||||
// .build();
|
||||
//
|
||||
// Flux<String> taskResponse = exchange
|
||||
// .exchange(request)
|
||||
// .flatMap(response -> response.bodyToFlux(String.class));
|
||||
//
|
||||
// assertThat(taskResponse.blockFirst()).isInstanceOf(String.class);
|
||||
// }
|
||||
|
||||
private static Flux<Task> getLatLngs() {
|
||||
return Flux
|
||||
.range(0, 3)
|
||||
.zipWith(Flux.interval(Duration.ofSeconds(1)))
|
||||
.map(x -> new Task("taskname", 1))
|
||||
.doOnNext(ll -> System.out.println("Produced: {}" + ll));
|
||||
return Flux.range(0, 3)
|
||||
.zipWith(Flux.interval(Duration.ofSeconds(1)))
|
||||
.map(x -> new Task("taskname", 1))
|
||||
.doOnNext(ll -> System.out.println("Produced: {}" + ll));
|
||||
}
|
||||
}
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue