Merge branch 'master' into akka

# Conflicts:
#	pom.xml
This commit is contained in:
Tom Hombergs 2018-12-16 20:43:48 +01:00
commit b29bdd5422
260 changed files with 4752 additions and 1862 deletions

View File

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

View File

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

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,22 @@
package com.baeldung.packages;
import java.time.LocalDate;
import com.baeldung.packages.domain.TodoItem;
public class TodoApp {
public static void main(String[] args) {
TodoList todoList = new TodoList();
for (int i = 0; i < 3; i++) {
TodoItem item = new TodoItem();
item.setId(Long.valueOf((long)i));
item.setDescription("Todo item " + (i + 1));
item.setDueDate(LocalDate.now().plusDays((long)(i + 1)));
todoList.addTodoItem(item);
}
todoList.getTodoItems().forEach((TodoItem todoItem) -> System.out.println(todoItem.toString()));
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.packages;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.packages.domain.TodoItem;
public class TodoList {
private List<TodoItem> todoItems;
public void addTodoItem(TodoItem todoItem) {
if (todoItems == null) {
todoItems = new ArrayList<TodoItem>();
}
todoItems.add(todoItem);
}
public List<TodoItem> getTodoItems() {
return todoItems;
}
public void setTodoItems(List<TodoItem> todoItems) {
this.todoItems = todoItems;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.packages.domain;
import java.time.LocalDate;
public class TodoItem {
private Long id;
private String description;
private LocalDate dueDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDueDate() {
return dueDate;
}
public void setDueDate(LocalDate dueDate) {
this.dueDate = dueDate;
}
@Override
public String toString() {
return "TodoItem [id=" + id + ", description=" + description + ", dueDate=" + dueDate + "]";
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.packages;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import org.junit.Test;
import com.baeldung.packages.domain.TodoItem;
public class PackagesUnitTest {
@Test
public void whenTodoItemAdded_ThenSizeIncreases() {
TodoItem todoItem = new TodoItem();
todoItem.setId(1L);
todoItem.setDescription("Test the Todo List");
todoItem.setDueDate(LocalDate.now());
TodoList todoList = new TodoList();
todoList.addTodoItem(todoItem);
assertEquals(1, todoList.getTodoItems().size());
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,14 @@
package com.baeldung.inline.classes
interface Drawable {
fun draw()
}
inline class CircleRadius(private val circleRadius : Double) : Drawable {
val diameterOfCircle get() = 2 * circleRadius
fun areaOfCircle() = 3.14 * circleRadius * circleRadius
override fun draw() {
println("Draw my circle")
}
}

View File

@ -0,0 +1,3 @@
package com.baeldung.inline.classes
inline class InlineDoubleWrapper(val doubleValue : Double)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,19 @@
package com.baeldung.inline.classes
import org.junit.Test
import kotlin.test.assertEquals
class CircleRadiusTest {
@Test
fun givenRadius_ThenDiameterIsCorrectlyCalculated() {
val radius = CircleRadius(5.0)
assertEquals(10.0, radius.diameterOfCircle)
}
@Test
fun givenRadius_ThenAreaIsCorrectlyCalculated() {
val radius = CircleRadius(5.0)
assertEquals(78.5, radius.areaOfCircle())
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.inline.classes
import org.junit.Test
import kotlin.test.assertEquals
class InlineDoubleWrapperTest {
@Test
fun whenInclineClassIsUsed_ThenPropertyIsReadCorrectly() {
val piDoubleValue = InlineDoubleWrapper(3.14)
assertEquals(3.14, piDoubleValue.doubleValue)
}
}

View File

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

View File

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

View File

@ -1,65 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>flips</groupId>
<artifactId>flips</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>flips</name>
<parent>
<artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot-starter-web.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot-starter-test.version}</version>
</dependency>
<dependency>
<groupId>com.github.feature-flip</groupId>
<artifactId>flips-web</artifactId>
<version>${flips-web.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<!-- Check for the most recent available version: https://projectlombok.org/changelog.html -->
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<spring-boot-starter-web.version>1.5.10.RELEASE</spring-boot-starter-web.version>
<spring-boot-starter-test.version>1.5.9.RELEASE</spring-boot-starter-test.version>
<flips-web.version>1.0.1</flips-web.version>
<lombok.version>1.16.18</lombok.version>
</properties>
</project>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -35,6 +35,7 @@
- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty)
- [String Performance Hints](https://www.baeldung.com/java-string-performance)
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences)
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
@ -42,4 +43,4 @@
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline)
- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)
- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)

View File

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

View File

@ -0,0 +1,90 @@
package com.baeldung.string.conversion;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
public class ByteArrayToStringUnitTest {
@Test
public void whenStringConstructorWithDefaultCharset_thenOK() {
final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114,
108, 100, 33 };
String string = new String(byteArrray);
System.out.println(string);
assertNotNull(string);
}
@Test
public void whenStringConstructorWithNamedCharset_thenOK()
throws UnsupportedEncodingException {
final String charsetName = "IBM01140";
final byte[] byteArrray = { -56, -123, -109, -109, -106, 64, -26, -106,
-103, -109, -124, 90 };
String string = new String(byteArrray, charsetName);
assertEquals("Hello World!", string);
}
@Test
public void whenStringConstructorWithCharSet_thenOK() {
final Charset charset = Charset.forName("UTF-8");
final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114,
108, 100, 33 };
String string = new String(byteArrray, charset);
assertEquals("Hello World!", string);
}
@Test
public void whenStringConstructorWithStandardCharSet_thenOK() {
final Charset charset = StandardCharsets.UTF_16;
final byte[] byteArrray = { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0,
111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 };
String string = new String(byteArrray, charset);
assertEquals("Hello World!", string);
}
@Test
public void whenDecodeWithCharset_thenOK() {
byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33 };
final Charset charset = StandardCharsets.US_ASCII;
String string = charset.decode(ByteBuffer.wrap(byteArrray)).toString();
System.out.println(string);
assertEquals("Hello <20>orl<72>!", string);
}
@Test
public void whenUsingCharsetDecoder_thenOK()
throws CharacterCodingException {
byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33};
CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.replaceWith("?");
String string = decoder.decode(ByteBuffer.wrap(byteArrray)).toString();
assertEquals("Hello ?orl?!", string);
}
}

View File

@ -0,0 +1,122 @@
package com.baeldung.string.conversion;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.UnsupportedEncodingException;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.junit.Test;
public class StringToByteArrayUnitTest {
@Test
public void whenGetBytesWithDefaultCharset_thenOK() {
final String inputString = "Hello World!";
final String defaultCharSet = Charset.defaultCharset()
.displayName();
byte[] byteArrray = inputString.getBytes();
System.out.printf(
"Using default charset:%s, Input String:%s, Output byte array:%s\n",
defaultCharSet, inputString, Arrays.toString(byteArrray));
assertNotNull(byteArrray);
assert (byteArrray.length >= inputString.length());
}
@Test
public void whenGetBytesWithNamedCharset_thenOK()
throws UnsupportedEncodingException {
final String inputString = "Hello World!";
final String charsetName = "IBM01140";
byte[] byteArrray = inputString.getBytes("IBM01140");
System.out.printf(
"Using named charset:%s, Input String:%s, Output byte array:%s\n",
charsetName, inputString, Arrays.toString(byteArrray));
assertArrayEquals(new byte[] { -56, -123, -109, -109, -106, 64, -26,
-106, -103, -109, -124, 90 },
byteArrray);
}
@Test
public void whenGetBytesWithCharset_thenOK() {
final String inputString = "Hello ਸੰਸਾਰ!";
final Charset charset = Charset.forName("ASCII");
byte[] byteArrray = inputString.getBytes(charset);
System.out.printf(
"Using Charset:%s, Input String:%s, Output byte array:%s\n",
charset, inputString, Arrays.toString(byteArrray));
assertArrayEquals(
new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 },
byteArrray);
}
@Test
public void whenGetBytesWithStandardCharset_thenOK() {
final String inputString = "Hello World!";
final Charset charset = StandardCharsets.UTF_16;
byte[] byteArrray = inputString.getBytes(charset);
System.out.printf(
"Using Standard Charset:%s, Input String:%s, Output byte array:%s\n",
charset, inputString, Arrays.toString(byteArrray));
assertArrayEquals(new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0,
111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 },
byteArrray);
}
@Test
public void whenEncodeWithCharset_thenOK() {
final String inputString = "Hello ਸੰਸਾਰ!";
final Charset charset = StandardCharsets.US_ASCII;
byte[] byteArrray = charset.encode(inputString)
.array();
System.out.printf(
"Using encode with Charset:%s, Input String:%s, Output byte array:%s\n",
charset, inputString, Arrays.toString(byteArrray));
assertArrayEquals(
new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 },
byteArrray);
}
@Test
public void whenUsingCharsetEncoder_thenOK()
throws CharacterCodingException {
final String inputString = "Hello ਸੰਸਾਰ!";
CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder();
encoder.onMalformedInput(CodingErrorAction.IGNORE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.replaceWith(new byte[] { 0 });
byte[] byteArrray = encoder.encode(CharBuffer.wrap(inputString))
.array();
System.out.printf(
"Using encode with CharsetEncoder:%s, Input String:%s, Output byte array:%s\n",
encoder, inputString, Arrays.toString(byteArrray));
assertArrayEquals(
new byte[] { 72, 101, 108, 108, 111, 32, 0, 0, 0, 0, 0, 33 },
byteArrray);
}
}

View File

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

9
libraries-apache-commons/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
*.class
# Folders #
/gensrc
/target
# Packaged files #
*.jar
/bin/

View File

@ -0,0 +1,20 @@
### Relevant articles
- [Array Processing with Apache Commons Lang 3](http://www.baeldung.com/array-processing-commons-lang)
- [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang)
- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math)
- [Apache Commons Collections SetUtils](http://www.baeldung.com/apache-commons-setutils)
- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map)
- [Introduction to Apache Commons Text](http://www.baeldung.com/java-apache-commons-text)
- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils)
- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue)
- [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain)
- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv)
- [Apache Commons IO](http://www.baeldung.com/apache-commons-io)
- [Apache Commons Collections Bag](http://www.baeldung.com/apache-commons-bag)
- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils)
- [Apache Commons BeanUtils](http://www.baeldung.com/apache-commons-beanutils)
- [Apache Commons Collections BidiMap](http://www.baeldung.com/commons-collections-bidi-map)
- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils)
- [Histograms with Apache Commons Frequency](http://www.baeldung.com/apache-commons-frequency)
- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3)

View File

@ -0,0 +1 @@
log4j.rootLogger=INFO, stdout

View File

@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries-apache-commons</artifactId>
<name>libraries-apache-commons</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons-beanutils.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<dependency>
<groupId>commons-chain</groupId>
<artifactId>commons-chain</artifactId>
<version>${commons-chain.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>${commons-csv.version}</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>${commons.dbutils.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${common-math3.version}</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>${commons-net.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.knowm.xchart</groupId>
<artifactId>xchart</artifactId>
<version>${xchart-version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons.collections.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>${org.hamcrest.java-hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<commons-lang.version>3.6</commons-lang.version>
<commons-text.version>1.1</commons-text.version>
<commons-beanutils.version>1.9.3</commons-beanutils.version>
<commons-chain.version>1.2</commons-chain.version>
<commons-csv.version>1.4</commons-csv.version>
<assertj.version>3.6.2</assertj.version>
<commons.io.version>2.5</commons.io.version>
<commons.dbutils.version>1.6</commons.dbutils.version>
<h2.version>1.4.196</h2.version>
<commons.collections.version>4.1</commons.collections.version>
<junit.version>4.12</junit.version>
<org.hamcrest.java-hamcrest.version>2.0.0.0</org.hamcrest.java-hamcrest.version>
<commons-codec-version>1.10.L001</commons-codec-version>
<xchart-version>3.5.2</xchart-version>
<commons-net.version>3.6</commons-net.version>
<hamcrest-all.version>1.3</hamcrest-all.version>
<common-math3.version>3.6.1</common-math3.version>
</properties>
</project>

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