Merge remote-tracking branch 'eugenp/master'
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
|
||||
/.idea/
|
||||
/target/
|
||||
/apache-shiro.iml
|
||||
@@ -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>
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,9 @@
|
||||
[users]
|
||||
user = password,admin
|
||||
user2 = password2,editor
|
||||
user3 = password3,author
|
||||
|
||||
[roles]
|
||||
admin = *
|
||||
editor = articles:*
|
||||
author = articles:compose,articles:save
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.networking.cookies;
|
||||
package com.baeldung.networking.cookies;
|
||||
|
||||
import java.net.*;
|
||||
import java.util.List;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.networking.cookies;
|
||||
package com.baeldung.networking.cookies;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.networking.udp;
|
||||
package com.baeldung.networking.udp;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.networking.udp;
|
||||
package com.baeldung.networking.udp;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
+44
@@ -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();
|
||||
}
|
||||
}
|
||||
+41
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
+71
@@ -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);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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>"));
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.networking.udp;
|
||||
package com.baeldung.networking.udp;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
+39
@@ -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");
|
||||
}
|
||||
}
|
||||
+39
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user