Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2017-08-19 11:58:39 +02:00
commit 08eb127715
134 changed files with 3247 additions and 206 deletions

View File

@ -0,0 +1,26 @@
public class BinarySearch {
public int runBinarySearch() {
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6;
int low = 0;
int high = sortedArray.length - 1;
int index = Integer.MAX_VALUE;
while (low <= high) {
int mid = (low + high) / 2;
if (sortedArray[mid] < key) {
low = mid + 1;
} else if (sortedArray[mid] > key) {
high = mid - 1;
} else if (sortedArray[mid] == key) {
index = mid;
break;
}
}
return index;
}
}

View File

@ -0,0 +1,14 @@
import org.junit.Assert;
import org.junit.Test;
public class BinarySearchTest {
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
int expectedIndexForSearchKey = 7;
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearch());
}
}

4
apache-shiro/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/.idea/
/target/
/apache-shiro.iml

0
apache-shiro/README.md Normal file
View File

65
apache-shiro/pom.xml Normal file
View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-shiro</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
<log4j-version>1.2.17</log4j-version>
<slf4j-version>1.7.25</slf4j-version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${apache-shiro-core-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j-version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,85 @@
package com.baeldung;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final transient Logger log = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
Realm realm = new MyCustomRealm();
SecurityManager securityManager = new DefaultSecurityManager(realm);
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token
= new UsernamePasswordToken("user", "password");
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.error("Username Not Found!", uae);
} catch (IncorrectCredentialsException ice) {
log.error("Invalid Credentials!", ice);
} catch (LockedAccountException lae) {
log.error("Your Account is Locked!", lae);
} catch (AuthenticationException ae) {
log.error("Unexpected Error!", ae);
}
}
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
if (currentUser.hasRole("admin")) {
log.info("Welcome Admin");
} else if(currentUser.hasRole("editor")) {
log.info("Welcome, Editor!");
} else if(currentUser.hasRole("author")) {
log.info("Welcome, Author");
} else {
log.info("Welcome, Guest");
}
if(currentUser.isPermitted("articles:compose")) {
log.info("You can compose an article");
} else {
log.info("You are not permitted to compose an article!");
}
if(currentUser.isPermitted("articles:save")) {
log.info("You can save articles");
} else {
log.info("You can not save articles");
}
if(currentUser.isPermitted("articles:publish")) {
log.info("You can publish articles");
} else {
log.info("You can not publish articles");
}
Session session = currentUser.getSession();
session.setAttribute("key", "value");
String value = (String) session.getAttribute("key");
if (value.equals("value")) {
log.info("Retrieved the correct value! [" + value + "]");
}
currentUser.logout();
System.exit(0);
}
}

View File

@ -0,0 +1,102 @@
package com.baeldung;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
public class MyCustomRealm extends JdbcRealm {
private Map<String, String> credentials = new HashMap<>();
private Map<String, Set<String>> roles = new HashMap<>();
private Map<String, Set<String>> perm = new HashMap<>();
{
credentials.put("user", "password");
credentials.put("user2", "password2");
credentials.put("user3", "password3");
roles.put("user", new HashSet<>(Arrays.asList("admin")));
roles.put("user2", new HashSet<>(Arrays.asList("editor")));
roles.put("user3", new HashSet<>(Arrays.asList("author")));
perm.put("admin", new HashSet<>(Arrays.asList("*")));
perm.put("editor", new HashSet<>(Arrays.asList("articles:*")));
perm.put("author",
new HashSet<>(Arrays.asList("articles:compose",
"articles:save")));
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
UsernamePasswordToken uToken = (UsernamePasswordToken) token;
if(uToken.getUsername() == null
|| uToken.getUsername().isEmpty()
|| !credentials.containsKey(uToken.getUsername())
) {
throw new UnknownAccountException("username not found!");
}
return new SimpleAuthenticationInfo(
uToken.getUsername(), credentials.get(uToken.getUsername()),
getName());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Set<String> roleNames = new HashSet<>();
Set<String> permissions = new HashSet<>();
principals.forEach(p -> {
try {
Set<String> roles = getRoleNamesForUser(null, (String) p);
roleNames.addAll(roles);
permissions.addAll(getPermissions(null, null,roles));
} catch (SQLException e) {
e.printStackTrace();
}
});
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
info.setStringPermissions(permissions);
return info;
}
@Override
protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
if(!roles.containsKey(username)) {
throw new SQLException("username not found!");
}
return roles.get(username);
}
@Override
protected Set<String> getPermissions(Connection conn, String username, Collection<String> roleNames) throws SQLException {
for (String role : roleNames) {
if (!perm.containsKey(role)) {
throw new SQLException("role not found!");
}
}
Set<String> finalSet = new HashSet<>();
for (String role : roleNames) {
finalSet.addAll(perm.get(role));
}
return finalSet;
}
}

View File

@ -0,0 +1,12 @@
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
log4j.logger.org.apache=WARN
log4j.logger.org.apache.shiro=INFO
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

View File

@ -0,0 +1,9 @@
[users]
user = password,admin
user2 = password2,editor
user3 = password3,author
[roles]
admin = *
editor = articles:*
author = articles:compose,articles:save

View File

@ -1,3 +1,4 @@
### Relevant articles
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book)

View File

@ -10,17 +10,27 @@ import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class Java9ObjectsAPIUnitTest {
private List<String> aMethodReturningNullList(){
return null;
}
@Test
public void givenNullObject_whenRequireNonNullElse_thenElse(){
assertThat(Objects.<List>requireNonNullElse(null, Collections.EMPTY_LIST),
is(Collections.EMPTY_LIST));
List<String> aList = Objects.<List>requireNonNullElse(
aMethodReturningNullList(), Collections.EMPTY_LIST);
assertThat(aList, is(Collections.EMPTY_LIST));
}
private List<String> aMethodReturningNonNullList(){
return List.of("item1", "item2");
}
@Test
public void givenObject_whenRequireNonNullElse_thenObject(){
assertThat(Objects.<List>requireNonNullElse(List.of("item1", "item2"),
Collections.EMPTY_LIST), is(List.of("item1", "item2")));
List<String> aList = Objects.<List>requireNonNullElse(
aMethodReturningNonNullList(), Collections.EMPTY_LIST);
assertThat(aList, is(List.of("item1", "item2")));
}
@Test(expected = NullPointerException.class)
@ -30,8 +40,8 @@ public class Java9ObjectsAPIUnitTest {
@Test
public void givenObject_whenRequireNonNullElseGet_thenObject(){
assertThat(Objects.<List>requireNonNullElseGet(null, List::of),
is(List.of()));
List<String> aList = Objects.<List>requireNonNullElseGet(null, List::of);
assertThat(aList, is(List.of()));
}
@Test

View File

@ -0,0 +1,13 @@
package com.baeldung.concurrent.volatilekeyword;
public class SharedObject {
private volatile int count=0;
void increamentCount(){
count++;
}
public int getCount(){
return count;
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.java.networking.cookies;
package com.baeldung.networking.cookies;
import java.net.*;
import java.util.List;

View File

@ -1,4 +1,4 @@
package com.baeldung.java.networking.cookies;
package com.baeldung.networking.cookies;
import java.net.*;

View File

@ -1,4 +1,4 @@
package com.baeldung.java.networking.udp;
package com.baeldung.networking.udp;
import java.io.IOException;
import java.net.DatagramPacket;

View File

@ -1,4 +1,4 @@
package com.baeldung.java.networking.udp;
package com.baeldung.networking.udp;
import java.io.IOException;
import java.net.DatagramPacket;

View File

@ -0,0 +1,85 @@
package com.baeldung.networking.udp.broadcast;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;
public class BroadcastingClient {
private DatagramSocket socket;
private InetAddress address;
private int expectedServerCount;
private byte[] buf;
public BroadcastingClient(int expectedServerCount) throws Exception {
this.expectedServerCount = expectedServerCount;
this.address = InetAddress.getByName("255.255.255.255");
}
public int discoverServers(String msg) throws IOException {
initializeSocketForBroadcasting();
copyMessageOnBuffer(msg);
// When we want to broadcast not just to local network, call listAllBroadcastAddresses() and execute broadcastPacket for each value.
broadcastPacket(address);
return receivePackets();
}
List<InetAddress> listAllBroadcastAddresses() throws SocketException {
List<InetAddress> broadcastList = new ArrayList<>();
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
continue;
}
broadcastList.addAll(networkInterface.getInterfaceAddresses()
.stream()
.filter(address -> address.getBroadcast() != null)
.map(address -> address.getBroadcast())
.collect(Collectors.toList()));
}
return broadcastList;
}
private void initializeSocketForBroadcasting() throws SocketException {
socket = new DatagramSocket();
socket.setBroadcast(true);
}
private void copyMessageOnBuffer(String msg) {
buf = msg.getBytes();
}
private void broadcastPacket(InetAddress address) throws IOException {
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
}
private int receivePackets() throws IOException {
int serversDiscovered = 0;
while (serversDiscovered != expectedServerCount) {
receivePacket();
serversDiscovered++;
}
return serversDiscovered;
}
private void receivePacket() throws IOException {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
}
public void close() {
socket.close();
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.networking.udp.broadcast;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
public class BroadcastingEchoServer extends Thread {
protected DatagramSocket socket = null;
protected boolean running;
protected byte[] buf = new byte[256];
public BroadcastingEchoServer() throws IOException {
socket = new DatagramSocket(null);
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(4445));
}
public void run() {
running = true;
while (running) {
try {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
String received = new String(packet.getData(), 0, packet.getLength());
if (received.equals("end")) {
running = false;
continue;
}
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
running = false;
}
}
socket.close();
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.networking.udp.multicast;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class MulticastEchoServer extends Thread {
protected MulticastSocket socket = null;
protected byte[] buf = new byte[256];
protected InetAddress group = null;
public MulticastEchoServer() throws IOException {
socket = new MulticastSocket(4446);
socket.setReuseAddress(true);
group = InetAddress.getByName("230.0.0.0");
socket.joinGroup(group);
}
public void run() {
try {
while (true) {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
String received = new String(packet.getData(), 0, packet.getLength());
if (received.equals("end")) {
break;
}
socket.send(packet);
}
socket.leaveGroup(group);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.networking.udp.multicast;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class MulticastingClient {
private DatagramSocket socket;
private InetAddress group;
private int expectedServerCount;
private byte[] buf;
public MulticastingClient(int expectedServerCount) throws Exception {
this.expectedServerCount = expectedServerCount;
this.socket = new DatagramSocket();
this.group = InetAddress.getByName("230.0.0.0");
}
public int discoverServers(String msg) throws IOException {
copyMessageOnBuffer(msg);
multicastPacket();
return receivePackets();
}
private void copyMessageOnBuffer(String msg) {
buf = msg.getBytes();
}
private void multicastPacket() throws IOException {
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);
socket.send(packet);
}
private int receivePackets() throws IOException {
int serversDiscovered = 0;
while (serversDiscovered != expectedServerCount) {
receivePacket();
serversDiscovered++;
}
return serversDiscovered;
}
private void receivePacket() throws IOException {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
}
public void close() {
socket.close();
}
}

View File

@ -0,0 +1,71 @@
package com.baeldung.concurrent.volatilekeyword;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class SharedObjectManualTest {
private SharedObject sharedObject;
private int valueReadByThread2;
private int valueReadByThread3;
@Before
public void setUp() {
sharedObject = new SharedObject();
}
@Test
public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
Thread writer = new Thread(() -> sharedObject.increamentCount());
writer.start();
Thread readerOne = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
valueReadByThread2 = sharedObject.getCount();
});
readerOne.start();
Thread readerTwo = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
valueReadByThread3 = sharedObject.getCount();
});
readerTwo.start();
assertEquals(1, valueReadByThread2);
assertEquals(1, valueReadByThread3);
}
@Test
public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
Thread writerOne = new Thread(() -> sharedObject.increamentCount());
writerOne.start();
Thread.sleep(100);
Thread writerTwo = new Thread(() -> sharedObject.increamentCount());
writerTwo.start();
Thread.sleep(100);
Thread readerOne = new Thread(() -> valueReadByThread2 = sharedObject.getCount());
readerOne.start();
Thread readerTwo = new Thread(() -> valueReadByThread3 = sharedObject.getCount());
readerTwo.start();
assertEquals(2, valueReadByThread2);
assertEquals(2, valueReadByThread3);
}
}

View File

@ -0,0 +1,78 @@
package com.baeldung.javanetworking.uriurl;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import static org.junit.Assert.*;
import org.junit.Test;
public class URIvsURLUnitTest {
@Test
public void whenCreatingURIs_thenSameInfo() throws URISyntaxException {
URI firstURI = new URI("somescheme://theuser:thepassword@someauthority:80/some/path?thequery#somefragment");
URI secondURI = new URI("somescheme", "theuser:thepassword", "someuthority", 80, "/some/path", "thequery", "somefragment");
assertEquals(firstURI.getScheme(), secondURI.getScheme());
assertEquals(firstURI.getPath(), secondURI.getPath());
}
@Test
public void whenCreatingURLs_thenSameInfo() throws MalformedURLException {
URL firstURL = new URL("http://theuser:thepassword@somehost:80/path/to/file?thequery#somefragment");
URL secondURL = new URL("http", "somehost", 80, "/path/to/file");
assertEquals(firstURL.getHost(), secondURL.getHost());
assertEquals(firstURL.getPath(), secondURL.getPath());
}
@Test
public void whenCreatingURI_thenCorrect() {
URI uri = URI.create("urn:isbn:1234567890");
assertNotNull(uri);
}
@Test(expected = MalformedURLException.class)
public void whenCreatingURLs_thenException() throws MalformedURLException {
URL theURL = new URL("otherprotocol://somehost/path/to/file");
assertNotNull(theURL);
}
@Test
public void givenObjects_whenConverting_thenCorrect() throws MalformedURLException, URISyntaxException {
String aURIString = "http://somehost:80/path?thequery";
URI uri = new URI(aURIString);
URL url = new URL(aURIString);
URL toURL = uri.toURL();
URI toURI = url.toURI();
assertNotNull(url);
assertNotNull(uri);
assertEquals(toURL.toString(), toURI.toString());
}
@Test(expected = MalformedURLException.class)
public void givenURI_whenConvertingToURL_thenException() throws MalformedURLException, URISyntaxException {
URI uri = new URI("somescheme://someauthority/path?thequery");
URL url = uri.toURL();
assertNotNull(url);
}
@Test
public void givenURL_whenGettingContents_thenCorrect() throws MalformedURLException, IOException {
URL url = new URL("http://courses.baeldung.com");
String contents = IOUtils.toString(url.openStream());
assertTrue(contents.contains("<!DOCTYPE html>"));
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.java.networking.udp;
package com.baeldung.networking.udp;
import org.junit.After;
import org.junit.Before;

View File

@ -0,0 +1,39 @@
package com.baeldung.networking.udp.broadcast;
import org.junit.After;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class BroadcastIntegrationTest {
private BroadcastingClient client;
@Test
public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception {
int expectedServers = 4;
initializeForExpectedServers(expectedServers);
int serversDiscovered = client.discoverServers("hello server");
assertEquals(expectedServers, serversDiscovered);
}
private void initializeForExpectedServers(int expectedServers) throws Exception {
for (int i = 0; i < expectedServers; i++) {
new BroadcastingEchoServer().start();
}
client = new BroadcastingClient(expectedServers);
}
@After
public void tearDown() throws IOException {
stopEchoServer();
client.close();
}
private void stopEchoServer() throws IOException {
client.discoverServers("end");
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.networking.udp.multicast;
import org.junit.After;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class MulticastIntegrationTest {
private MulticastingClient client;
@Test
public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception {
int expectedServers = 4;
initializeForExpectedServers(expectedServers);
int serversDiscovered = client.discoverServers("hello server");
assertEquals(expectedServers, serversDiscovered);
}
private void initializeForExpectedServers(int expectedServers) throws Exception {
for (int i = 0; i < expectedServers; i++) {
new MulticastEchoServer().start();
}
client = new MulticastingClient(expectedServers);
}
@After
public void tearDown() throws IOException {
stopEchoServer();
client.close();
}
private void stopEchoServer() throws IOException {
client.discoverServers("end");
}
}

15
easy-rules/pom.xml Normal file
View File

@ -0,0 +1,15 @@
<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.easyrules</groupId>
<artifactId>easy-rules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-core</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,20 @@
package com.baeldung.easyrules;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Rule;
@Rule(name = "Hello World rule", description = "Always say hello world")
public class HelloWorldRule {
@Condition
public boolean when() {
return true;
}
@Action
public void then() throws Exception {
System.out.println("hello world");
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.easyrules;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
public class Launcher {
public static void main(String... args) {
// create facts
Facts facts = new Facts();
// create rules
Rules rules = new Rules();
rules.register(new HelloWorldRule());
// create a rules engine and fire rules on known facts
RulesEngine rulesEngine = new DefaultRulesEngine();
rulesEngine.fire(rules, facts);
}
}

View File

@ -1,8 +1,8 @@
endpoint.name=client-endpoint
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=127.0.0.1
remote.connection.default.port=8080
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER}
remote.connection.default.username=testUser
remote.connection.default.password=admin1234!
remote.connection.default.username=myusername
remote.connection.default.password=mypassword

View File

@ -0,0 +1,42 @@
package com.baeldung.ejbclient.application;
import com.baeldung.ejbmodule.TextProcessorBean;
import com.baeldung.ejbmodule.TextProcessorRemote;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;
public class TextApplication {
public static void main(String[] args) throws NamingException {
TextProcessorRemote textProcessor = EJBFactory.createTextProcessorBeanFromJNDI("ejb:");
System.out.print(textProcessor.processText("sample text"));
}
private static class EJBFactory {
private static TextProcessorRemote createTextProcessorBeanFromJNDI(String namespace) throws NamingException {
return lookupTextProcessorBean(namespace);
}
private static TextProcessorRemote lookupTextProcessorBean(String namespace) throws NamingException {
Context ctx = createInitialContext();
final String appName = "";
final String moduleName = "EJBModule";
final String distinctName = "";
final String beanName = TextProcessorBean.class.getSimpleName();
final String viewClassName = TextProcessorRemote.class.getName();
return (TextProcessorRemote) ctx.lookup(namespace + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName);
}
private static Context createInitialContext() throws NamingException {
Properties jndiProperties = new Properties();
jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
jndiProperties.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
jndiProperties.put("jboss.naming.client.ejb.context", true);
return new InitialContext(jndiProperties);
}
}
}

View File

@ -0,0 +1,8 @@
endpoint.name=client-endpoint
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=127.0.0.1
remote.connection.default.port=8080
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.username=myusername
remote.connection.default.password=mypassword

View File

@ -0,0 +1,31 @@
package com.baeldung.ejbclient.application;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.naming.NamingException;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.*;
public class TextApplicationTest {
private static ByteArrayOutputStream outContent;
@BeforeClass
public static void setUpPrintStreamInstance() {
outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
}
@AfterClass
public static void tearDownByteArrayOutputStream() {
outContent = null;
}
@Test
public void givenInputString_whenCompareTtoStringPrintedToConsole_thenSuccessful() throws NamingException {
TextApplication.main(new String[]{});
assertEquals("SAMPLE TEXT", outContent.toString());
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.ejbmodule;
import javax.ejb.Stateless;
@Stateless
public class TextProcessorBean implements TextProcessorRemote {
public String processText(String text) {
return text.toUpperCase();
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.ejbmodule;
import javax.ejb.Remote;
@Remote
public interface TextProcessorRemote {
String processText(String text);
}

View File

@ -0,0 +1,12 @@
package com.baeldung.ejbmodule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TextProcessorBeanTest {
@Test
public void givenInputString_whenComparedToStringParsedByBean_thenSuccessful() {
TextProcessorBean textProcessor = new TextProcessorBean();
assertEquals("TEST", textProcessor.processText("test"));
}
}

View File

@ -1,19 +1,23 @@
package com.baeldung.jackson.test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;
import com.baeldung.jackson.deserialization.ItemDeserializer;
import com.baeldung.jackson.dtos.Item;
import com.baeldung.jackson.dtos.ItemWithSerializer;
import com.baeldung.jackson.dtos.MyDto;
import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreUnknown;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
@ -21,6 +25,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.fasterxml.jackson.databind.module.SimpleModule;
@ -165,4 +170,35 @@ public class JacksonDeserializationUnitTest {
assertThat(readValue, notNullValue());
}
@Test
public void whenDeserialisingZonedDateTimeWithDefaults_thenTimeZoneIsNotPreserved() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// construct a new instance of ZonedDateTime
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
String converted = objectMapper.writeValueAsString(now);
// restore an instance of ZonedDateTime from String
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
System.out.println("serialized: " + now);
System.out.println("restored: " + restored);
assertThat(now, is(not(restored)));
}
@Test
public void whenDeserialisingZonedDateTimeWithFeaturesDisabled_thenTimeZoneIsPreserved() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
// construct a new instance of ZonedDateTime
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
String converted = objectMapper.writeValueAsString(now);
// restore an instance of ZonedDateTime from String
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
System.out.println("serialized: " + now);
System.out.println("restored: " + restored);
assertThat(now, is(restored));
}
}

View File

@ -7,3 +7,10 @@
- [Difference Between “==” and “===” in Kotlin](http://www.baeldung.com/kotlin-equality-operators)
- [Generics in Kotlin](http://www.baeldung.com/kotlin-generics)
- [Introduction to Kotlin Coroutines](http://www.baeldung.com/kotlin-coroutines)
- [Destructuring Declarations in Kotlin](http://www.baeldung.com/kotlin-destructuring-declarations)
- [Kotlin with Mockito](http://www.baeldung.com/kotlin-mockito)
- [Lazy Initialization in Kotlin](http://www.baeldung.com/kotlin-lazy-initialization)
- [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)

View File

@ -23,6 +23,7 @@
- [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave)
- [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing)
- [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)
- [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing)
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)

View File

@ -186,11 +186,11 @@
<artifactId>rome</artifactId>
<version>${rome.version}</version>
</dependency>
<dependency>
<groupId>io.specto</groupId>
<artifactId>hoverfly-java</artifactId>
<version>0.8.0</version>
</dependency>
<dependency>
<groupId>io.specto</groupId>
<artifactId>hoverfly-java</artifactId>
<version>0.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
@ -212,6 +212,11 @@
<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>
@ -380,7 +385,7 @@
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>0.6.5</version>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
@ -467,11 +472,16 @@
<artifactId>noexception</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse-collections.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
</dependencies>
<properties>
<multiverse.version>0.7.0</multiverse.version>
@ -480,6 +490,7 @@
<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>
<jasypt.version>1.9.2</jasypt.version>
<javatuples.version>1.2</javatuples.version>
<javaassist.version>3.21.0-GA</javaassist.version>
@ -513,6 +524,8 @@
<bytebuddy.version>1.7.1</bytebuddy.version>
<pcollections.version>2.1.2</pcollections.version>
<rome.version>1.0</rome.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
</properties>
</project>

View File

@ -0,0 +1,15 @@
package com.baeldung.distinct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
public class DistinctWithJavaFunction {
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.distinct;
public class Person {
int age;
String name;
String email;
public Person(int age, String name, String email) {
super();
this.age = age;
this.name = name;
this.email = email;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [age=");
builder.append(age);
builder.append(", name=");
builder.append(name);
builder.append(", email=");
builder.append(email);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.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 (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
return true;
}
}

View File

@ -1,15 +1,25 @@
package com.baeldung.eclipsecollections;
import java.util.List;
public class Student {
private String firstName;
private String lastName;
private List<String> addresses;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Student(String firstName, String lastName, List<String> addresses) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.addresses = addresses;
}
public String getFirstName() {
return this.firstName;
}
@ -17,4 +27,20 @@ public class Student {
public String getLastName() {
return this.lastName;
}
public List<String> getAddresses() {
return addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

View File

@ -0,0 +1,85 @@
package com.baeldung.commons.collections4;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.CollectionBag;
import org.apache.commons.collections4.bag.HashBag;
import org.apache.commons.collections4.bag.TreeBag;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class BagTests {
Bag<String> baseBag;
TreeBag<String> treeBag;
@Before
public void before() {
baseBag = new HashBag<String>();
treeBag = new TreeBag<String>();
treeBag = new TreeBag<String>();
}
@Test
public void whenAdd_thenRemoveFromBaseBag_thenContainsCorrect() {
baseBag.add("apple", 2);
baseBag.add("lemon", 6);
baseBag.add("lime");
baseBag.remove("lemon");
Assert.assertEquals(3, baseBag.size());
Assert.assertFalse(baseBag.contains("lemon"));
Assert.assertTrue(baseBag.uniqueSet().contains("apple"));
Assert.assertFalse(baseBag.uniqueSet().contains("lemon"));
Assert.assertTrue(baseBag.uniqueSet().contains("lime"));
List<String> containList = new ArrayList<String>();
containList.add("apple");
containList.add("lemon");
containList.add("lime");
Assert.assertFalse(baseBag.containsAll(containList));
}
@Test
public void whenAdd_thenRemoveFromBaseCollectionBag_thenContainsCorrect() {
baseBag.add("apple", 2);
baseBag.add("lemon", 6);
baseBag.add("lime");
CollectionBag<String> baseCollectionBag = new CollectionBag<String>(
baseBag);
baseCollectionBag.remove("lemon");
Assert.assertEquals(8, baseCollectionBag.size());
Assert.assertTrue(baseCollectionBag.contains("lemon"));
Assert.assertTrue(baseBag.uniqueSet().contains("apple"));
Assert.assertTrue(baseBag.uniqueSet().contains("lemon"));
Assert.assertTrue(baseBag.uniqueSet().contains("lime"));
List<String> containList = new ArrayList<String>();
containList.add("apple");
containList.add("lemon");
containList.add("lime");
Assert.assertTrue(baseBag.containsAll(containList));
}
@Test
public void whenAddtoTreeBag_thenRemove_thenContainsCorrect() {
treeBag.add("banana", 8);
treeBag.add("apple", 2);
treeBag.add("lime");
Assert.assertEquals(11, treeBag.size());
Assert.assertEquals("apple", treeBag.first());
Assert.assertEquals("lime", treeBag.last());
treeBag.remove("apple");
Assert.assertEquals(9, treeBag.size());
Assert.assertEquals("banana", treeBag.first());
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.commons.csv;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.junit.Test;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class CSVReaderWriterTest {
public static final Map<String, String> AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap<String, String>() {
{
put("Dan Simmons", "Hyperion");
put("Douglas Adams", "The Hitchhiker's Guide to the Galaxy");
}
});
public static final String[] HEADERS = { "author", "title" };
public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy";
@Test
public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException {
Reader in = new FileReader("src/test/resources/book.csv");
Iterable<CSVRecord> records = CSVFormat.DEFAULT
.withHeader(HEADERS)
.withFirstRecordAsHeader()
.parse(in);
for (CSVRecord record : records) {
String author = record.get("author");
String title = record.get("title");
assertEquals(AUTHOR_BOOK_MAP.get(author), title);
}
}
@Test
public void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException {
StringWriter sw = new StringWriter();
try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) {
AUTHOR_BOOK_MAP.forEach((author, title) -> {
try {
printer.printRecord(author, title);
} catch (IOException e) {
e.printStackTrace();
}
});
}
assertEquals(EXPECTED_FILESTREAM, sw
.toString()
.trim());
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.eclipse.collections.impl.block.factory.HashingStrategies;
import org.eclipse.collections.impl.utility.ListIterate;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithEclipseCollectionsUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromFunction(Person::getName));
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromIntFunction(Person::getAge));
assertTrue(personListFiltered.size() == 2);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import static com.baeldung.distinct.DistinctWithJavaFunction.distinctByKey;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithJavaFunctionUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = personList.stream()
.filter(distinctByKey(p -> p.getName()))
.collect(Collectors.toList());
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = personList.stream()
.filter(distinctByKey(p -> p.getAge()))
.collect(Collectors.toList());
assertTrue(personListFiltered.size() == 2);
}
@Test
public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() {
List<Person> personListFiltered = personList.stream()
.distinct()
.collect(Collectors.toList());
assertTrue(personListFiltered.size() == 5);
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import one.util.streamex.StreamEx;
public class DistinctWithStreamexUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = StreamEx.of(personList)
.distinct(Person::getName)
.toList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = StreamEx.of(personList)
.distinct(Person::getAge)
.toList();
assertTrue(personListFiltered.size() == 2);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithVavrUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList)
.distinctBy(Person::getName)
.toJavaList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList)
.distinctBy(Person::getAge)
.toJavaList();
assertTrue(personListFiltered.size() == 2);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.distinct;
import java.util.Arrays;
import java.util.List;
public class PersonDataGenerator {
public static List<Person> getPersonListWithFakeValues() {
// @formatter:off
return Arrays.asList(
new Person(20, "Jhon", "jhon@test.com"),
new Person(20, "Jhon", "jhon1@test.com"),
new Person(20, "Jhon", "jhon2@test.com"),
new Person(21, "Tom", "Tom@test.com"),
new Person(21, "Mark", "Mark@test.com"),
new Person(20, "Julia", "jhon@test.com"));
// @formatter:on
}
}

View File

@ -14,15 +14,7 @@ public class AllSatisfyPatternTest {
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
}
@Test

View File

@ -14,15 +14,7 @@ public class AnySatisfyPatternTest {
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
}
@Test

View File

@ -2,7 +2,8 @@ package com.baeldung.eclipsecollections;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.list.mutable.FastList;
import static org.junit.Assert.assertEquals;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class CollectPatternTest {
@ -16,7 +17,7 @@ public class CollectPatternTest {
MutableList<String> lastNames = students.collect(Student::getLastName);
assertEquals(lastNames.get(0), "Hopkins");
assertEquals(lastNames.get(1), "Adams");
Assertions.assertThat(lastNames)
.containsExactly("Hopkins", "Adams");
}
}

View File

@ -1,9 +1,8 @@
package com.baeldung.eclipsecollections;
import static org.junit.Assert.assertTrue;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Test;
public class ConvertContainerToAnotherTest {
@ -12,9 +11,8 @@ public class ConvertContainerToAnotherTest {
@Test
public void whenConvertContainerToAnother_thenCorrect() {
MutableList<String> cars = (MutableList) ConvertContainerToAnother.convertToList();
assertTrue(cars.anySatisfy(Predicates.equal("Toyota")));
assertTrue(cars.anySatisfy(Predicates.equal("Mercedes")));
assertTrue(cars.anySatisfy(Predicates.equal("Volkswagen")));
Assertions.assertThat(cars)
.containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes"));
}
}

View File

@ -1,10 +1,9 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
@ -14,21 +13,14 @@ public class DetectPatternTest {
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
}
@Test
public void whenDetect_thenCorrect() {
Integer result = list.detect(Predicates.greaterThan(30));
assertEquals((int) result, 41);
Assertions.assertThat(result)
.isEqualTo(41);
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.list.mutable.FastList;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class FlatCollectTest {
MutableList<String> addresses1;
MutableList<String> addresses2;
MutableList<String> addresses3;
MutableList<String> addresses4;
List<String> expectedAddresses;
MutableList<Student> students;
@Before
public void setup() {
String address1 = "73 Pacific St., Forest Hills, NY 11375";
String address2 = "93 Bayport Ave., South Richmond Hill, NY 11419";
String address3 = "548 Market St, San Francisco, CA 94104";
String address4 = "8605 Santa Monica Blvd, West Hollywood, CA 90069";
this.addresses1 = FastList.newListWith(address1, address2);
this.addresses2 = FastList.newListWith(address3, address4);
Student student1 = new Student("John", "Hopkins", addresses1);
Student student2 = new Student("George", "Adams", addresses2);
this.addresses2 = FastList.newListWith(address3, address4);
this.students = FastList.newListWith(student1, student2);
this.expectedAddresses = new ArrayList<>();
this.expectedAddresses.add("73 Pacific St., Forest Hills, NY 11375");
this.expectedAddresses.add("93 Bayport Ave., South Richmond Hill, NY 11419");
this.expectedAddresses.add("548 Market St, San Francisco, CA 94104");
this.expectedAddresses.add("8605 Santa Monica Blvd, West Hollywood, CA 90069");
}
@Test
public void whenFlatCollect_thenCorrect() {
MutableList<String> addresses = students.flatCollect(Student::getAddresses);
Assertions.assertThat(addresses)
.containsExactlyElementsOf(this.expectedAddresses);
}
}

View File

@ -1,13 +1,10 @@
package com.baeldung.eclipsecollections;
import org.eclipse.collections.api.block.procedure.Procedure;
import static org.junit.Assert.assertEquals;
import org.eclipse.collections.api.tuple.Pair;
import org.eclipse.collections.impl.map.mutable.UnifiedMap;
import org.eclipse.collections.impl.tuple.Tuples;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Test;
public class ForEachPatternTest {

View File

@ -1,10 +1,9 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.LazyIterable;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.factory.Lists;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class LazyIterationTest {
@ -19,8 +18,7 @@ public class LazyIterationTest {
LazyIterable<Student> lazyStudents = students.asLazy();
LazyIterable<String> lastNames = lazyStudents.collect(Student::getLastName);
assertTrue(lastNames.anySatisfy(Predicates.equal("Hopkins")));
assertTrue(lastNames.anySatisfy(Predicates.equal("Adams")));
assertTrue(lastNames.anySatisfy(Predicates.equal("Rodriguez")));
Assertions.assertThat(lastNames)
.containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez"));
}
}

View File

@ -1,12 +1,9 @@
package com.baeldung.eclipsecollections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.block.predicate.Predicate;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.partition.list.PartitionMutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Before;
import org.junit.Test;
@ -17,18 +14,9 @@ public class PartitionPatternTest {
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
}
@SuppressWarnings({ "unused" })
@Test
public void whenAnySatisfiesCondition_thenCorrect() {
MutableList<Integer> numbers = list;
@ -48,14 +36,9 @@ public class PartitionPatternTest {
MutableList<Integer> smallerThanThirty = partitionedFolks.getRejected()
.sortThis();
assertEquals(1, (int) smallerThanThirty.getFirst());
assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(5)));
assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(8)));
assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(17)));
assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(23)));
assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(31)));
assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(38)));
assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(41)));
Assertions.assertThat(smallerThanThirty)
.containsExactly(1, 5, 8, 17, 23);
Assertions.assertThat(greaterThanThirty)
.containsExactly(31, 38, 41);
}
}

View File

@ -1,27 +1,21 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class RejectPatternTest {
MutableList<Integer> list;
MutableList<Integer> expectedList;
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
public void setup() {
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
this.expectedList = FastList.newListWith(1, 5, 8, 17, 23);
}
@Test
@ -29,10 +23,7 @@ public class RejectPatternTest {
MutableList<Integer> notGreaterThanThirty = list.reject(Predicates.greaterThan(30))
.sortThis();
assertEquals(1, (int) notGreaterThanThirty.getFirst());
assertEquals(5, (int) notGreaterThanThirty.get(1));
assertEquals(8, (int) notGreaterThanThirty.get(2));
assertEquals(17, (int) notGreaterThanThirty.get(3));
assertEquals(23, (int) notGreaterThanThirty.getLast());
Assertions.assertThat(notGreaterThanThirty)
.containsExactlyElementsOf(this.expectedList);
}
}

View File

@ -1,9 +1,9 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
@ -13,15 +13,7 @@ public class SelectPatternTest {
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38);
}
@Test
@ -29,9 +21,8 @@ public class SelectPatternTest {
MutableList<Integer> greaterThanThirty = list.select(Predicates.greaterThan(30))
.sortThis();
assertEquals(31, (int) greaterThanThirty.getFirst());
assertEquals(38, (int) greaterThanThirty.get(1));
assertEquals(41, (int) greaterThanThirty.getLast());
Assertions.assertThat(greaterThanThirty)
.containsExactly(31, 38, 41);
}
@SuppressWarnings("rawtypes")
@ -45,8 +36,7 @@ public class SelectPatternTest {
public void givenListwhenSelectUsingLambda_thenCorrect() {
MutableList<Integer> greaterThanThirty = selectUsingLambda();
assertEquals(31, (int) greaterThanThirty.getFirst());
assertEquals(38, (int) greaterThanThirty.get(1));
assertEquals(41, (int) greaterThanThirty.getLast());
Assertions.assertThat(greaterThanThirty)
.containsExactly(31, 38, 41);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.eclipsecollections;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.tuple.Pair;
import org.eclipse.collections.impl.factory.Lists;
import org.eclipse.collections.impl.tuple.Tuples;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
public class ZipTest {
MutableList<Pair<String, String>> expectedPairs;
@SuppressWarnings("unchecked")
@Before
public void setup() {
Pair<String, String> pair1 = Tuples.pair("1", "Porsche");
Pair<String, String> pair2 = Tuples.pair("2", "Volvo");
Pair<String, String> pair3 = Tuples.pair("3", "Toyota");
expectedPairs = Lists.mutable.of(pair1, pair2, pair3);
}
@Test
public void whenZip_thenCorrect() {
MutableList<String> numbers = Lists.mutable.with("1", "2", "3", "Ignored");
MutableList<String> cars = Lists.mutable.with("Porsche", "Volvo", "Toyota");
MutableList<Pair<String, String>> pairs = numbers.zip(cars);
Assertions.assertThat(pairs)
.containsExactlyElementsOf(this.expectedPairs);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.eclipsecollections;
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.tuple.Pair;
import org.eclipse.collections.impl.factory.Lists;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.eclipse.collections.impl.tuple.Tuples;
import org.junit.Before;
import org.junit.Test;
public class ZipWithIndexTest {
MutableList<Pair<String, Integer>> expectedPairs;
@SuppressWarnings("unchecked")
@Before
public void setup() {
Pair<String, Integer> pair1 = Tuples.pair("Porsche", 0);
Pair<String, Integer> pair2 = Tuples.pair("Volvo", 1);
Pair<String, Integer> pair3 = Tuples.pair("Toyota", 2);
expectedPairs = Lists.mutable.of(pair1, pair2, pair3);
}
@Test
public void whenZip_thenCorrect() {
MutableList<String> cars = FastList.newListWith("Porsche", "Volvo", "Toyota");
MutableList<Pair<String, Integer>> pairs = cars.zipWithIndex();
Assertions.assertThat(pairs)
.containsExactlyElementsOf(this.expectedPairs);
}
}

View File

@ -0,0 +1,3 @@
author,title
Dan Simmons,Hyperion
Douglas Adams,The Hitchhiker's Guide to the Galaxy
1 author title
2 Dan Simmons Hyperion
3 Douglas Adams The Hitchhiker's Guide to the Galaxy

23
openl-tablets/pom.xml Normal file
View File

@ -0,0 +1,23 @@
<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.openltablets</groupId>
<artifactId>openl-tablets</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openl</groupId>
<artifactId>org.openl.core</artifactId>
<version>5.19.4</version>
</dependency>
<dependency>
<groupId>org.openl.rules</groupId>
<artifactId>org.openl.rules</artifactId>
<version>5.19.4</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,23 @@
package com.baeldung.openltablets.model;
public class Case {
private User user;
private int hourOfDay;
public User getUser() {
return user;
}
public void setUser(final User user) {
this.user = user;
}
public int getHourOfDay() {
return hourOfDay;
}
public void setHourOfDay(final int hourOfDay) {
this.hourOfDay = hourOfDay;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.openltablets.model;
public enum Greeting {
GOOD_MORNING("Good Morning"),
GOOD_AFTERNOON("Good Afternoon"),
GOOD_EVENING("Good Evening"),
GOOD_NIGHT("Good Night");
private final String literal;
private Greeting(final String literal) {
this.literal = literal;
}
public String getLiteral() {
return literal;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.openltablets.model;
public class User {
private String name;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.openltablets.rules;
import com.baeldung.openltablets.model.Case;
public interface IRule {
void helloUser(final Case aCase, final Response response);
}

View File

@ -0,0 +1,31 @@
package com.baeldung.openltablets.rules;
import java.time.LocalDateTime;
import org.openl.rules.runtime.RulesEngineFactory;
import org.openl.runtime.EngineFactory;
import com.baeldung.openltablets.model.Case;
import com.baeldung.openltablets.model.User;
public class Main {
private IRule instance;
public static void main(String[] args) {
Main rules = new Main();
User user = new User();
user.setName("Donald Duck");
Case aCase = new Case();
aCase.setUser(user);
aCase.setHourOfDay(23);
rules.process(aCase);
}
public void process(Case aCase) {
final EngineFactory<IRule> engineFactory = new RulesEngineFactory<IRule>(getClass().getClassLoader()
.getResource("openltablets/HelloUser.xls"), IRule.class);
instance = engineFactory.newEngineInstance();
instance.helloUser(aCase, new Response());
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.openltablets.rules;
import java.util.HashMap;
import java.util.Map;
public class Response {
private String result;
private Map<String, String> map = new HashMap<>();
public Response() { }
public String getResult() {
return result;
}
public void setResult(final String s) {
result = s;
}
public Map<String, String> getMap() {
return map;
}
}

View File

@ -175,6 +175,7 @@
<module>spring-mvc-webflow</module>
<module>spring-mvc-xml</module>
<module>spring-mvc-simple</module>
<module>spring-mvc-kotlin</module>
<module>spring-security-openid</module>
<module>spring-protobuf</module>
<module>spring-quartz</module>
@ -237,6 +238,7 @@
<module>liquibase</module>
<module>spring-boot-property-exp</module>
<module>mockserver</module>
<module>undertow</module>
</modules>
<dependencies>

View File

@ -2,3 +2,4 @@
- [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)

15
rulebook/pom.xml Normal file
View File

@ -0,0 +1,15 @@
<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.rulebook</groupId>
<artifactId>rulebook</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.deliveredtechnologies</groupId>
<artifactId>rulebook-core</artifactId>
<version>0.6.2</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.rulebook;
import com.deliveredtechnologies.rulebook.lang.RuleBookBuilder;
import com.deliveredtechnologies.rulebook.model.RuleBook;
public class HelloWorldRule {
public RuleBook<Object> defineHelloWorldRules() {
return RuleBookBuilder.create()
.addRule(rule -> rule.withNoSpecifiedFactType()
.then(f -> System.out.print("Hello ")))
.addRule(rule -> rule.withNoSpecifiedFactType()
.then(f -> System.out.println("World")))
.build();
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.rulebook;
import com.deliveredtechnologies.rulebook.FactMap;
public class Launcher {
public static void main(String[] args) {
HelloWorldRule ruleBook = new HelloWorldRule();
ruleBook.defineHelloWorldRules()
.run(new FactMap<>());
}
}

View File

@ -8,5 +8,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests)
- [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)

View File

@ -0,0 +1,3 @@
### Relevant articles
- [A Guide to Activiti with Java](http://www.baeldung.com/java-activiti)

View File

@ -1,4 +1,4 @@
package org.baeldung.spring_batch_intro;
package org.baeldung.batch;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;

View File

@ -1,11 +1,8 @@
package org.baeldung.spring_batch_intro;
package org.baeldung.batch;
import java.net.MalformedURLException;
import java.text.ParseException;
import org.baeldung.spring_batch_intro.model.Transaction;
import org.baeldung.spring_batch_intro.service.CustomItemProcessor;
import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper;
import org.baeldung.batch.model.Transaction;
import org.baeldung.batch.service.CustomItemProcessor;
import org.baeldung.batch.service.RecordFieldSetMapper;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
@ -26,6 +23,9 @@ import org.springframework.core.io.Resource;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import java.net.MalformedURLException;
import java.text.ParseException;
public class SpringBatchConfig {
@Autowired
private JobBuilderFactory jobs;
@ -43,7 +43,7 @@ public class SpringBatchConfig {
public ItemReader<Transaction> itemReader() throws UnexpectedInputException, ParseException {
FlatFileItemReader<Transaction> reader = new FlatFileItemReader<Transaction>();
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
String[] tokens = { "username", "userid", "transactiondate", "amount" };
String[] tokens = {"username", "userid", "transactiondate", "amount"};
tokenizer.setNames(tokens);
reader.setResource(inputCsv);
DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<Transaction>();
@ -71,13 +71,13 @@ public class SpringBatchConfig {
@Bean
public Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(new Class[] { Transaction.class });
marshaller.setClassesToBeBound(Transaction.class);
return marshaller;
}
@Bean
protected Step step1(ItemReader<Transaction> reader, ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> writer) {
return steps.get("step1").<Transaction, Transaction> chunk(10).reader(reader).processor(processor).writer(writer).build();
return steps.get("step1").<Transaction, Transaction>chunk(10).reader(reader).processor(processor).writer(writer).build();
}
@Bean(name = "firstBatchJob")

View File

@ -1,4 +1,4 @@
package org.baeldung.spring_batch_intro;
package org.baeldung.batch;
import java.net.MalformedURLException;

View File

@ -1,4 +1,4 @@
package org.baeldung.spring_batch_intro.model;
package org.baeldung.batch.model;
import java.util.Date;

View File

@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.baeldung.spring_batch_intro.partitioner;
package org.baeldung.batch.partitioner;
import java.util.HashMap;
import java.util.Map;

View File

@ -1,13 +1,7 @@
package org.baeldung.spring_batch_intro.partitioner;
package org.baeldung.batch.partitioner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.ParseException;
import javax.sql.DataSource;
import org.baeldung.spring_batch_intro.model.Transaction;
import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper;
import org.baeldung.batch.model.Transaction;
import org.baeldung.batch.service.RecordFieldSetMapper;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
@ -33,7 +27,6 @@ import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.task.TaskExecutor;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.oxm.Marshaller;
@ -41,6 +34,11 @@ import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.ParseException;
@Configuration
@EnableBatchProcessing
public class SpringbatchPartitionConfig {
@ -57,26 +55,26 @@ public class SpringbatchPartitionConfig {
@Bean(name = "partitionerJob")
public Job partitionerJob() throws UnexpectedInputException, MalformedURLException, ParseException {
return jobs.get("partitionerJob")
.start(partitionStep())
.build();
.start(partitionStep())
.build();
}
@Bean
public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException {
return steps.get("partitionStep")
.partitioner("slaveStep", partitioner())
.step(slaveStep())
.taskExecutor(taskExecutor())
.build();
.partitioner("slaveStep", partitioner())
.step(slaveStep())
.taskExecutor(taskExecutor())
.build();
}
@Bean
public Step slaveStep() throws UnexpectedInputException, MalformedURLException, ParseException {
return steps.get("slaveStep")
.<Transaction, Transaction> chunk(1)
.reader(itemReader(null))
.writer(itemWriter(marshaller(), null))
.build();
.<Transaction, Transaction>chunk(1)
.reader(itemReader(null))
.writer(itemWriter(marshaller(), null))
.build();
}
@Bean
@ -95,12 +93,12 @@ public class SpringbatchPartitionConfig {
@Bean
@StepScope
public FlatFileItemReader<Transaction> itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException {
FlatFileItemReader<Transaction> reader = new FlatFileItemReader<Transaction>();
FlatFileItemReader<Transaction> reader = new FlatFileItemReader<>();
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
String[] tokens = { "username", "userid", "transactiondate", "amount" };
String[] tokens = {"username", "userid", "transactiondate", "amount"};
tokenizer.setNames(tokens);
reader.setResource(new ClassPathResource("input/partitioner/" + filename));
DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<Transaction>();
DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<>();
lineMapper.setLineTokenizer(tokenizer);
lineMapper.setFieldSetMapper(new RecordFieldSetMapper());
reader.setLinesToSkip(1);
@ -121,7 +119,7 @@ public class SpringbatchPartitionConfig {
@Bean
public Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(new Class[] { Transaction.class });
marshaller.setClassesToBeBound(Transaction.class);
return marshaller;
}
@ -142,16 +140,15 @@ public class SpringbatchPartitionConfig {
// JobRepositoryFactoryBean's methods Throws Generic Exception,
// it would have been better to have a specific one
factory.afterPropertiesSet();
return (JobRepository) factory.getObject();
return factory.getObject();
}
private DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql")
.addScript("classpath:org/springframework/batch/core/schema-h2.sql")
.build();
return db;
return builder.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql")
.addScript("classpath:org/springframework/batch/core/schema-h2.sql")
.build();
}
private PlatformTransactionManager getTransactionManager() {

View File

@ -1,4 +1,4 @@
package org.baeldung.spring_batch_intro.partitioner;
package org.baeldung.batch.partitioner;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;

View File

@ -1,6 +1,6 @@
package org.baeldung.spring_batch_intro.service;
package org.baeldung.batch.service;
import org.baeldung.spring_batch_intro.model.Transaction;
import org.baeldung.batch.model.Transaction;
import org.springframework.batch.item.ItemProcessor;
public class CustomItemProcessor implements ItemProcessor<Transaction, Transaction> {

View File

@ -1,9 +1,9 @@
package org.baeldung.spring_batch_intro.service;
package org.baeldung.batch.service;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.baeldung.spring_batch_intro.model.Transaction;
import org.baeldung.batch.model.Transaction;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;

View File

@ -22,14 +22,14 @@
</property>
<property name="fieldSetMapper">
<bean
class="org.baeldung.spring_batch_intro.service.RecordFieldSetMapper" />
class="org.baeldung.batch.service.RecordFieldSetMapper" />
</property>
</bean>
</property>
<property name="linesToSkip" value="1" />
</bean>
<bean id="itemProcessor" class="org.baeldung.spring_batch_intro.service.CustomItemProcessor" />
<bean id="itemProcessor" class="org.baeldung.batch.service.CustomItemProcessor" />
<bean id="itemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="file:xml/output.xml" />
@ -40,7 +40,7 @@
<bean id="recordMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>org.baeldung.spring_batch_intro.model.Transaction</value>
<value>org.baeldung.batch.model.Transaction</value>
</list>
</property>
</bean>

View File

@ -17,6 +17,25 @@
<version>1.5.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<!-- add dependency management if you have a different parent pom
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.5.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -1,2 +1,18 @@
## The Module Holds Sources for the Following Articles
- [Automatic Property Expansion with Spring Boot] (http://www.baeldung.com/property-expansion-spring-boot)
- [Automatic Property Expansion with Spring Boot](http://www.baeldung.com/property-expansion-spring-boot)
### Module property-exp-default-config
This module contains both a standard Maven Spring Boot build and the Gradle build which is Maven compatible.
In order to execute the Maven example, run the following command:
`mvn spring-boot:run`
To execute the Gradle example:
`gradle bootRun`
### Module property-exp-custom-config
This project is not using the standard Spring Boot parent and is configured manually. Run the following command:
`mvn exec:java`

View File

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>property-exp-custom</artifactId>
<artifactId>property-exp-custom-config</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

View File

@ -11,7 +11,7 @@
</parent>
<groupId>com.baeldung</groupId>
<artifactId>property-exp-default</artifactId>
<artifactId>property-exp-default-config</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

View File

@ -0,0 +1,3 @@
### Relevant articles
- [Spring Cloud Bus](http://www.baeldung.com/spring-cloud-bus)

View File

@ -6,4 +6,6 @@
- [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok)
- [A Quick Guide to Spring @Value](http://www.baeldung.com/spring-value-annotation)
- [Spring YAML Configuration](http://www.baeldung.com/spring-yaml)
- [Introduction to Springs StreamUtils](http://www.baeldung.com/spring-stream-utils)
- [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults)

View File

@ -0,0 +1,70 @@
package com.baeldung.autowired;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
@SpringBootApplication
public class TypesOfBeanInjectionSpring {
private final UserService userService;
@Autowired // the @Autowired can even be omitted, in case there's only one explicit constructor
public TypesOfBeanInjectionSpring(UserService userService) {
this.userService = userService;
}
public static void main(String[] args) {
SpringApplication.run(TypesOfBeanInjectionSpring.class, args);
}
@Bean
CommandLineRunner runIt() {
return args -> {
userService.listUsers()
.stream()
.forEach(System.out::println);
};
}
}
class User {
private String name;
public User(String name) {
this.name = name;
}
// getters and setters ...
public String getName() {
return this.name;
}
public String toString() {
return name;
}
}
interface UserService {
List<User> listUsers();
}
@Service
class UserServiceImpl implements UserService {
@Override
public List<User> listUsers() {
ArrayList<User> users = new ArrayList<>(3);
users.add(new User("Snoopy"));
users.add(new User("Woodstock"));
users.add(new User("Charlie Brown"));
return users;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.autowired;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TypesOfBeanInjectionSpringIntegrationTest {
@Autowired
UserService userService;
private static final String[] expected = new String[] { "Snoopy", "Woodstock", "Charlie Brown" };
@Test
public void givenDI_whenInjectObject_thenUserNamesAreListed() {
Assert.assertArrayEquals(expected, userService.listUsers()
.stream()
.map(User::getName)
.toArray());
}
}

View File

@ -120,6 +120,12 @@
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
@ -167,7 +173,7 @@
<properties>
<!-- Spring -->
<org.springframework.version>4.3.5.RELEASE</org.springframework.version>
<org.springframework.version>4.3.10.RELEASE</org.springframework.version>
<org.springframework.data.version>1.10.6.RELEASE</org.springframework.data.version>
@ -177,7 +183,8 @@
<!-- persistence -->
<hibernate.version>5.2.10.Final</hibernate.version>
<tomcat-dbcp.version>8.5.15</tomcat-dbcp.version>
<mysql-connector-java.version>8.0.7-dmr</mysql-connector-java.version>
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<jta.version>1.1</jta.version>
<hsqldb.version>2.3.4</hsqldb.version>
<h2.version>1.4.195</h2.version>

View File

@ -0,0 +1,86 @@
package com.baeldung.hibernate.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "Employee")
public class Employee implements Serializable {
@Id
@Column(name = "employee_id")
@GeneratedValue
private Long employeeId;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "Employee_Project",
joinColumns = { @JoinColumn(name = "employee_id") },
inverseJoinColumns = { @JoinColumn(name = "project_id") }
)
Set<Project> projects = new HashSet<Project>();
public Employee() {
super();
}
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Employee(String firstName, String lastName, Set<Project> projects) {
this.firstName = firstName;
this.lastName = lastName;
this.projects = projects;
}
public Long getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Long employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Set<Project> getProjects() {
return projects;
}
public void setProjects(Set<Project> projects) {
this.projects = projects;
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.hibernate.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "Project")
public class Project implements Serializable {
@Id
@Column(name = "project_id")
@GeneratedValue
private Long projectId;
@Column(name = "title")
private String title;
@ManyToMany(mappedBy = "projects")
private Set<Employee> employees = new HashSet<Employee>();
public Project() {
super();
}
public Project(String title) {
this.title = title;
}
public Long getProjectId() {
return projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
}

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