commit
e5cff86190
@ -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;
|
||||||
|
}
|
||||||
|
}
|
14
algorithms/src/test/java/algorithms/BinarySearchTest.java
Normal file
14
algorithms/src/test/java/algorithms/BinarySearchTest.java
Normal 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
4
apache-shiro/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
|
||||||
|
/.idea/
|
||||||
|
/target/
|
||||||
|
/apache-shiro.iml
|
0
apache-shiro/README.md
Normal file
0
apache-shiro/README.md
Normal file
65
apache-shiro/pom.xml
Normal file
65
apache-shiro/pom.xml
Normal 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>
|
85
apache-shiro/src/main/java/com/baeldung/Main.java
Normal file
85
apache-shiro/src/main/java/com/baeldung/Main.java
Normal 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
102
apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java
Normal file
102
apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java
Normal 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
12
apache-shiro/src/main/resources/log4j.properties
Normal file
12
apache-shiro/src/main/resources/log4j.properties
Normal 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
|
9
apache-shiro/src/main/resources/shiro.ini
Normal file
9
apache-shiro/src/main/resources/shiro.ini
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
[users]
|
||||||
|
user = password,admin
|
||||||
|
user2 = password2,editor
|
||||||
|
user3 = password3,author
|
||||||
|
|
||||||
|
[roles]
|
||||||
|
admin = *
|
||||||
|
editor = articles:*
|
||||||
|
author = articles:compose,articles:save
|
@ -1,4 +1,4 @@
|
|||||||
resource.loader=webapp
|
resource.loader=webapp
|
||||||
webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader
|
webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader
|
||||||
webapp.resource.loader.path = .
|
webapp.resource.loader.path =
|
||||||
webapp.resource.loader.cache = true
|
webapp.resource.loader.cache = true
|
@ -1,3 +1,4 @@
|
|||||||
### Relevant articles
|
### 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)
|
||||||
|
11
bootique/config.yml
Normal file
11
bootique/config.yml
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
log:
|
||||||
|
level: warn
|
||||||
|
appenders:
|
||||||
|
- type: file
|
||||||
|
logFormat: '%c{20}: %m%n'
|
||||||
|
file: /home/logger.log
|
||||||
|
|
||||||
|
jetty:
|
||||||
|
context: /hello
|
||||||
|
connector:
|
||||||
|
port: 10001
|
50
bootique/dependency-reduced-pom.xml
Normal file
50
bootique/dependency-reduced-pom.xml
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
<?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/maven-v4_0_0.xsd">
|
||||||
|
<parent>
|
||||||
|
<artifactId>bootique-parent</artifactId>
|
||||||
|
<groupId>io.bootique.parent</groupId>
|
||||||
|
<version>0.12</version>
|
||||||
|
</parent>
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung.bootique</groupId>
|
||||||
|
<artifactId>bootique</artifactId>
|
||||||
|
<name>bootique</name>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<url>http://maven.apache.org</url>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-shade-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.bootique</groupId>
|
||||||
|
<artifactId>bootique-test</artifactId>
|
||||||
|
<version>0.23</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>3.8.1</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<dependencyManagement>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.bootique.bom</groupId>
|
||||||
|
<artifactId>bootique-bom</artifactId>
|
||||||
|
<version>0.23</version>
|
||||||
|
<type>pom</type>
|
||||||
|
<scope>import</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</dependencyManagement>
|
||||||
|
<properties>
|
||||||
|
<main.class>com.baeldung.bootique.App</main.class>
|
||||||
|
</properties>
|
||||||
|
</project>
|
||||||
|
|
66
bootique/pom.xml
Normal file
66
bootique/pom.xml
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
<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/maven-v4_0_0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung.bootique</groupId>
|
||||||
|
<artifactId>bootique</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<name>bootique</name>
|
||||||
|
<url>http://maven.apache.org</url>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<main.class>com.baeldung.bootique.App</main.class>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>io.bootique.parent</groupId>
|
||||||
|
<artifactId>bootique-parent</artifactId>
|
||||||
|
<version>0.12</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencyManagement>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.bootique.bom</groupId>
|
||||||
|
<artifactId>bootique-bom</artifactId>
|
||||||
|
<version>0.23</version>
|
||||||
|
<type>pom</type>
|
||||||
|
<scope>import</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</dependencyManagement>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.bootique.jersey</groupId>
|
||||||
|
<artifactId>bootique-jersey</artifactId>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.bootique.logback</groupId>
|
||||||
|
<artifactId>bootique-logback</artifactId>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.bootique</groupId>
|
||||||
|
<artifactId>bootique-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.12</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-shade-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
41
bootique/src/main/java/com/baeldung/bootique/App.java
Normal file
41
bootique/src/main/java/com/baeldung/bootique/App.java
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.bootique;
|
||||||
|
|
||||||
|
import com.baeldung.bootique.module.ModuleBinder;
|
||||||
|
import com.baeldung.bootique.router.IndexController;
|
||||||
|
import com.baeldung.bootique.router.SaveController;
|
||||||
|
import com.google.inject.Module;
|
||||||
|
import io.bootique.Bootique;
|
||||||
|
import io.bootique.jersey.JerseyModule;
|
||||||
|
import io.bootique.log.BootLogger;
|
||||||
|
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
public class App {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Module module = binder -> JerseyModule.extend(binder).addResource(IndexController.class)
|
||||||
|
.addResource(SaveController.class);
|
||||||
|
Bootique.app(args).module(module).module(ModuleBinder.class).bootLogger(new BootLogger() {
|
||||||
|
@Override
|
||||||
|
public void trace(Supplier<String> arg0) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stdout(String arg0) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stderr(String arg0, Throwable arg1) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stderr(String arg0) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
}).autoLoadModules().exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.bootique.module;
|
||||||
|
|
||||||
|
import com.baeldung.bootique.service.HelloService;
|
||||||
|
import com.baeldung.bootique.service.impl.HelloServiceImpl;
|
||||||
|
import com.google.inject.Binder;
|
||||||
|
import com.google.inject.Module;
|
||||||
|
|
||||||
|
public class ModuleBinder implements Module {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configure(Binder binder) {
|
||||||
|
binder.bind(HelloService.class).to(HelloServiceImpl.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.bootique.module;
|
||||||
|
|
||||||
|
import com.google.inject.Module;
|
||||||
|
import io.bootique.BQModuleProvider;
|
||||||
|
|
||||||
|
public class ModuleProvider implements BQModuleProvider {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Module module() {
|
||||||
|
return new ModuleBinder();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.bootique.router;
|
||||||
|
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
|
||||||
|
@Path("/")
|
||||||
|
public class IndexController {
|
||||||
|
|
||||||
|
@GET
|
||||||
|
public String index() {
|
||||||
|
return "Hello, baeldung!";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.bootique.router;
|
||||||
|
|
||||||
|
import com.baeldung.bootique.service.HelloService;
|
||||||
|
import com.google.inject.Inject;
|
||||||
|
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
|
||||||
|
@Path("/save")
|
||||||
|
public class SaveController {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
HelloService helloService;
|
||||||
|
|
||||||
|
@POST
|
||||||
|
public String save() {
|
||||||
|
return "Data Saved!";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,7 @@
|
|||||||
|
package com.baeldung.bootique.service;
|
||||||
|
|
||||||
|
public interface HelloService {
|
||||||
|
|
||||||
|
boolean save();
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.bootique.service.impl;
|
||||||
|
|
||||||
|
import com.baeldung.bootique.service.HelloService;
|
||||||
|
|
||||||
|
public class HelloServiceImpl implements HelloService {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean save() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1 @@
|
|||||||
|
com.baeldung.bootique.module.ModuleProvider
|
27
bootique/src/test/java/com/baeldung/bootique/AppTest.java
Normal file
27
bootique/src/test/java/com/baeldung/bootique/AppTest.java
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.bootique;
|
||||||
|
|
||||||
|
import com.baeldung.bootique.service.HelloService;
|
||||||
|
import io.bootique.BQRuntime;
|
||||||
|
import io.bootique.test.junit.BQDaemonTestFactory;
|
||||||
|
import io.bootique.test.junit.BQTestFactory;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class AppTest {
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public BQTestFactory bqTestFactory = new BQTestFactory();
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenService_expectBoolen() {
|
||||||
|
BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime();
|
||||||
|
HelloService service = runtime.getInstance(HelloService.class);
|
||||||
|
assertEquals(true, service.save());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -6,7 +6,7 @@ public class ServiceMain {
|
|||||||
|
|
||||||
public static void main(String[] args) throws InterruptedException {
|
public static void main(String[] args) throws InterruptedException {
|
||||||
ProcessHandle thisProcess = ProcessHandle.current();
|
ProcessHandle thisProcess = ProcessHandle.current();
|
||||||
long pid = thisProcess.getPid();
|
long pid = thisProcess.pid();
|
||||||
|
|
||||||
Optional<String[]> opArgs = Optional.ofNullable(args);
|
Optional<String[]> opArgs = Optional.ofNullable(args);
|
||||||
String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));
|
String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));
|
||||||
|
@ -0,0 +1,86 @@
|
|||||||
|
package com.baeldung.java9.language;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
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(){
|
||||||
|
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(){
|
||||||
|
List<String> aList = Objects.<List>requireNonNullElse(
|
||||||
|
aMethodReturningNonNullList(), Collections.EMPTY_LIST);
|
||||||
|
assertThat(aList, is(List.of("item1", "item2")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenNull_whenRequireNonNullElse_thenException(){
|
||||||
|
Objects.<List>requireNonNullElse(null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenObject_whenRequireNonNullElseGet_thenObject(){
|
||||||
|
List<String> aList = Objects.<List>requireNonNullElseGet(null, List::of);
|
||||||
|
assertThat(aList, is(List.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNumber_whenInvokeCheckIndex_thenNumber(){
|
||||||
|
int length = 5;
|
||||||
|
assertThat(Objects.checkIndex(4, length), is(4));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IndexOutOfBoundsException.class)
|
||||||
|
public void givenOutOfRangeNumber_whenInvokeCheckIndex_thenException(){
|
||||||
|
int length = 5;
|
||||||
|
Objects.checkIndex(5, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSubRange_whenCheckFromToIndex_thenNumber(){
|
||||||
|
int length = 6;
|
||||||
|
assertThat(Objects.checkFromToIndex(2,length,length), is(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IndexOutOfBoundsException.class)
|
||||||
|
public void givenInvalidSubRange_whenCheckFromToIndex_thenException(){
|
||||||
|
int length = 6;
|
||||||
|
Objects.checkFromToIndex(2,7,length);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSubRange_whenCheckFromIndexSize_thenNumber(){
|
||||||
|
int length = 6;
|
||||||
|
assertThat(Objects.checkFromIndexSize(2,3,length), is(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IndexOutOfBoundsException.class)
|
||||||
|
public void givenInvalidSubRange_whenCheckFromIndexSize_thenException(){
|
||||||
|
int length = 6;
|
||||||
|
Objects.checkFromIndexSize(2, 6, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@ -1,39 +0,0 @@
|
|||||||
<?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.hashcode</groupId>
|
|
||||||
<artifactId>hashcode</artifactId>
|
|
||||||
<version>1.0</version>
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<configuration>
|
|
||||||
<source>1.8</source>
|
|
||||||
<target>1.8</target>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>junit</groupId>
|
|
||||||
<artifactId>junit</artifactId>
|
|
||||||
<version>4.12</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.slf4j</groupId>
|
|
||||||
<artifactId>slf4j-api</artifactId>
|
|
||||||
<version>1.7.25</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.slf4j</groupId>
|
|
||||||
<artifactId>slf4j-simple</artifactId>
|
|
||||||
<version>1.7.25</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
</project>
|
|
@ -1,23 +0,0 @@
|
|||||||
package com.baeldung.application;
|
|
||||||
|
|
||||||
import com.baeldung.entities.User;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
public class Application {
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
Map<User, User> users = new HashMap<>();
|
|
||||||
User user1 = new User(1L, "John", "john@domain.com");
|
|
||||||
User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
|
|
||||||
User user3 = new User(3L, "Mary", "mary@domain.com");
|
|
||||||
|
|
||||||
users.put(user1, user1);
|
|
||||||
users.put(user2, user2);
|
|
||||||
users.put(user3, user3);
|
|
||||||
|
|
||||||
if (users.containsKey(user1)) {
|
|
||||||
System.out.print("User found in the collection");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,38 +0,0 @@
|
|||||||
package com.baeldung.entities;
|
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
public class User {
|
|
||||||
|
|
||||||
private final Logger logger = LoggerFactory.getLogger(User.class);
|
|
||||||
private long id;
|
|
||||||
private String name;
|
|
||||||
private String email;
|
|
||||||
|
|
||||||
public User(long id, String name, String email) {
|
|
||||||
this.id = id;
|
|
||||||
this.name = name;
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean equals(Object o) {
|
|
||||||
if (this == o) return true;
|
|
||||||
if (o == null) return false;
|
|
||||||
if (this.getClass() != o.getClass()) return false;
|
|
||||||
User user = (User) o;
|
|
||||||
return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int hashCode() {
|
|
||||||
int hash = 7;
|
|
||||||
hash = 31 * hash + (int) id;
|
|
||||||
hash = 31 * hash + (name == null ? 0 : name.hashCode());
|
|
||||||
hash = 31 * hash + (email == null ? 0 : email.hashCode());
|
|
||||||
logger.info("hashCode() method called - Computed hash: " + hash);
|
|
||||||
return hash;
|
|
||||||
}
|
|
||||||
// getters and setters here
|
|
||||||
}
|
|
@ -1,30 +0,0 @@
|
|||||||
package com.baeldung.application;
|
|
||||||
|
|
||||||
import org.junit.After;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.PrintStream;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
public class ApplicationTest {
|
|
||||||
|
|
||||||
private ByteArrayOutputStream outContent;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void setUpPrintStreamInstance() throws Exception {
|
|
||||||
this.outContent = new ByteArrayOutputStream();
|
|
||||||
System.setOut(new PrintStream(outContent));
|
|
||||||
}
|
|
||||||
|
|
||||||
@After
|
|
||||||
public void tearDownByteArrayOutputStream() throws Exception {
|
|
||||||
outContent = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void main_NoInputState_TextPrintedToConsole() throws Exception {
|
|
||||||
Application.main(new String[]{});
|
|
||||||
assertEquals("User found in the collection", outContent.toString());
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,34 +0,0 @@
|
|||||||
package com.baeldung.entities;
|
|
||||||
|
|
||||||
import org.junit.After;
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class UserTest {
|
|
||||||
|
|
||||||
private User user;
|
|
||||||
private User comparisonUser;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void setUpUserInstances() {
|
|
||||||
this.user = new User(1L, "test", "test@domain.com");
|
|
||||||
this.comparisonUser = this.user;
|
|
||||||
}
|
|
||||||
|
|
||||||
@After
|
|
||||||
public void tearDownUserInstances() {
|
|
||||||
user = null;
|
|
||||||
comparisonUser = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void equals_EqualUserInstance_TrueAssertion(){
|
|
||||||
Assert.assertTrue(user.equals(comparisonUser));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void hashCode_UserHash_TrueAssertion() {
|
|
||||||
Assert.assertEquals(1792276941, user.hashCode());
|
|
||||||
}
|
|
||||||
}
|
|
@ -80,7 +80,11 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>log4j</groupId>
|
||||||
|
<artifactId>log4j</artifactId>
|
||||||
|
<version>1.2.17</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
|
@ -15,14 +15,12 @@ public class CyclicBarrierDemo {
|
|||||||
private int NUM_PARTIAL_RESULTS;
|
private int NUM_PARTIAL_RESULTS;
|
||||||
private int NUM_WORKERS;
|
private int NUM_WORKERS;
|
||||||
|
|
||||||
|
|
||||||
private void runSimulation(int numWorkers, int numberOfPartialResults) {
|
private void runSimulation(int numWorkers, int numberOfPartialResults) {
|
||||||
NUM_PARTIAL_RESULTS = numberOfPartialResults;
|
NUM_PARTIAL_RESULTS = numberOfPartialResults;
|
||||||
NUM_WORKERS = numWorkers;
|
NUM_WORKERS = numWorkers;
|
||||||
|
|
||||||
cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
|
cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
|
||||||
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute "
|
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " + NUM_PARTIAL_RESULTS + " partial results each");
|
||||||
+ NUM_PARTIAL_RESULTS + " partial results each");
|
|
||||||
for (int i = 0; i < NUM_WORKERS; i++) {
|
for (int i = 0; i < NUM_WORKERS; i++) {
|
||||||
Thread worker = new Thread(new NumberCruncherThread());
|
Thread worker = new Thread(new NumberCruncherThread());
|
||||||
worker.setName("Thread " + i);
|
worker.setName("Thread " + i);
|
||||||
@ -38,8 +36,7 @@ public class CyclicBarrierDemo {
|
|||||||
List<Integer> partialResult = new ArrayList<>();
|
List<Integer> partialResult = new ArrayList<>();
|
||||||
for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
|
for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
|
||||||
Integer num = random.nextInt(10);
|
Integer num = random.nextInt(10);
|
||||||
System.out.println(thisThreadName
|
System.out.println(thisThreadName + ": Crunching some numbers! Final result - " + num);
|
||||||
+ ": Crunching some numbers! Final result - " + num);
|
|
||||||
partialResult.add(num);
|
partialResult.add(num);
|
||||||
}
|
}
|
||||||
partialResults.add(partialResult);
|
partialResults.add(partialResult);
|
||||||
@ -57,13 +54,12 @@ public class CyclicBarrierDemo {
|
|||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
String thisThreadName = Thread.currentThread().getName();
|
String thisThreadName = Thread.currentThread().getName();
|
||||||
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS
|
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS + " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
|
||||||
+ " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
|
|
||||||
int sum = 0;
|
int sum = 0;
|
||||||
for (List<Integer> threadResult : partialResults) {
|
for (List<Integer> threadResult : partialResults) {
|
||||||
System.out.print("Adding ");
|
System.out.print("Adding ");
|
||||||
for (Integer partialResult : threadResult) {
|
for (Integer partialResult : threadResult) {
|
||||||
System.out.print(partialResult+" ");
|
System.out.print(partialResult + " ");
|
||||||
sum += partialResult;
|
sum += partialResult;
|
||||||
}
|
}
|
||||||
System.out.println();
|
System.out.println();
|
||||||
|
@ -15,7 +15,8 @@ public class Philosopher implements Runnable {
|
|||||||
Thread.sleep(((int) (Math.random() * 100)));
|
Thread.sleep(((int) (Math.random() * 100)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public void run() {
|
@Override
|
||||||
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while (true) {
|
while (true) {
|
||||||
doAction(System.nanoTime() + ": Thinking"); // thinking
|
doAction(System.nanoTime() + ": Thinking"); // thinking
|
||||||
|
@ -6,22 +6,22 @@ import java.util.concurrent.TimeUnit;
|
|||||||
|
|
||||||
public class ExecutorServiceDemo {
|
public class ExecutorServiceDemo {
|
||||||
|
|
||||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
public void execute() {
|
public void execute() {
|
||||||
|
|
||||||
executor.submit(() -> {
|
executor.submit(() -> {
|
||||||
new Task();
|
new Task();
|
||||||
});
|
});
|
||||||
|
|
||||||
executor.shutdown();
|
executor.shutdown();
|
||||||
executor.shutdownNow();
|
executor.shutdownNow();
|
||||||
try {
|
try {
|
||||||
executor.awaitTermination(20l, TimeUnit.NANOSECONDS);
|
executor.awaitTermination(20l, TimeUnit.NANOSECONDS);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -9,36 +9,36 @@ import java.util.concurrent.TimeoutException;
|
|||||||
|
|
||||||
public class FutureDemo {
|
public class FutureDemo {
|
||||||
|
|
||||||
public String invoke() {
|
public String invoke() {
|
||||||
|
|
||||||
String str = null;
|
String str = null;
|
||||||
|
|
||||||
ExecutorService executorService = Executors.newFixedThreadPool(10);
|
ExecutorService executorService = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
Future<String> future = executorService.submit(() -> {
|
Future<String> future = executorService.submit(() -> {
|
||||||
// Task
|
// Task
|
||||||
Thread.sleep(10000l);
|
Thread.sleep(10000l);
|
||||||
return "Hellow world";
|
return "Hellow world";
|
||||||
});
|
});
|
||||||
|
|
||||||
future.cancel(false);
|
future.cancel(false);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
future.get(20, TimeUnit.SECONDS);
|
future.get(20, TimeUnit.SECONDS);
|
||||||
} catch (InterruptedException | ExecutionException | TimeoutException e1) {
|
} catch (InterruptedException | ExecutionException | TimeoutException e1) {
|
||||||
e1.printStackTrace();
|
e1.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (future.isDone() && !future.isCancelled()) {
|
if (future.isDone() && !future.isCancelled()) {
|
||||||
try {
|
try {
|
||||||
str = future.get();
|
str = future.get();
|
||||||
} catch (InterruptedException | ExecutionException e) {
|
} catch (InterruptedException | ExecutionException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return str;
|
return str;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -4,20 +4,20 @@ import java.util.concurrent.ThreadFactory;
|
|||||||
|
|
||||||
public class BaeldungThreadFactory implements ThreadFactory {
|
public class BaeldungThreadFactory implements ThreadFactory {
|
||||||
|
|
||||||
private int threadId;
|
private int threadId;
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
public BaeldungThreadFactory(String name) {
|
public BaeldungThreadFactory(String name) {
|
||||||
threadId = 1;
|
threadId = 1;
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Thread newThread(Runnable r) {
|
public Thread newThread(Runnable r) {
|
||||||
Thread t = new Thread(r, name + "-Thread_" + threadId);
|
Thread t = new Thread(r, name + "-Thread_" + threadId);
|
||||||
System.out.println("created new thread with id : " + threadId + " and name : " + t.getName());
|
System.out.println("created new thread with id : " + threadId + " and name : " + t.getName());
|
||||||
threadId++;
|
threadId++;
|
||||||
return t;
|
return t;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -2,9 +2,9 @@ package com.baeldung.concurrent.threadfactory;
|
|||||||
|
|
||||||
public class Task implements Runnable {
|
public class Task implements Runnable {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// task details
|
// task details
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.designpatterns.adapter;
|
||||||
|
|
||||||
|
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||||
|
|
||||||
|
public class AdapterPatternDriver {
|
||||||
|
|
||||||
|
public static void main(String args[]) {
|
||||||
|
LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl();
|
||||||
|
LOG.info("Bugatti Veyron Super Sport's top speed is " + luxuryCars.bugattiVeyronInKMPH() + " Kmph.");
|
||||||
|
LOG.info("McLaren F1 top speed is " + luxuryCars.mcLarenInKMPH() + " Kmph.");
|
||||||
|
LOG.info("Aston Martin One-77 top speed is " + luxuryCars.astonMartinInKMPH() + " Kmph.");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.designpatterns.adapter;
|
||||||
|
|
||||||
|
public class LuxuryCarsSpeed {
|
||||||
|
public double bugattiVeyronInMPH() {
|
||||||
|
return 268;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double mcLarenInMPH() {
|
||||||
|
return 241;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double astonMartinInMPH() {
|
||||||
|
return 220;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,7 @@
|
|||||||
|
package com.baeldung.designpatterns.adapter;
|
||||||
|
|
||||||
|
public interface LuxuryCarsSpeedAdapter {
|
||||||
|
public double bugattiVeyronInKMPH();
|
||||||
|
public double mcLarenInKMPH();
|
||||||
|
public double astonMartinInKMPH();
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.designpatterns.adapter;
|
||||||
|
|
||||||
|
public class LuxuryCarsSpeedAdapterImpl extends LuxuryCarsSpeed implements LuxuryCarsSpeedAdapter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double bugattiVeyronInKMPH() {
|
||||||
|
double mph = super.bugattiVeyronInMPH();
|
||||||
|
return convertMPHtoKMPH(mph);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double mcLarenInKMPH() {
|
||||||
|
double mph = super.mcLarenInMPH();
|
||||||
|
return convertMPHtoKMPH(mph);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double astonMartinInKMPH() {
|
||||||
|
double mph = super.astonMartinInMPH();
|
||||||
|
return convertMPHtoKMPH(mph);
|
||||||
|
}
|
||||||
|
|
||||||
|
private double convertMPHtoKMPH(double mph) {
|
||||||
|
return mph * 1.60934;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.designpatterns.bridge;
|
||||||
|
|
||||||
|
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||||
|
|
||||||
|
public class Blue implements Color {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void fillColor() {
|
||||||
|
LOG.info("Color : Blue");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.designpatterns.bridge;
|
||||||
|
|
||||||
|
public class BridgePatternDriver {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//a square with red color
|
||||||
|
Shape square = new Square(new Red());
|
||||||
|
square.drawShape();
|
||||||
|
|
||||||
|
//a triangle with blue color
|
||||||
|
Shape triangle = new Triangle(new Blue());
|
||||||
|
triangle.drawShape();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.designpatterns.bridge;
|
||||||
|
|
||||||
|
public interface Color {
|
||||||
|
public void fillColor();
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.designpatterns.bridge;
|
||||||
|
|
||||||
|
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||||
|
|
||||||
|
public class Red implements Color {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void fillColor() {
|
||||||
|
LOG.info("Color : Red");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung.designpatterns.bridge;
|
||||||
|
|
||||||
|
public abstract class Shape {
|
||||||
|
protected Color color;
|
||||||
|
|
||||||
|
public Shape(Color color) {
|
||||||
|
this.color = color;
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract public void drawShape();
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.designpatterns.bridge;
|
||||||
|
|
||||||
|
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||||
|
|
||||||
|
public class Square extends Shape {
|
||||||
|
|
||||||
|
public Square(Color color) {
|
||||||
|
super(color);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawShape() {
|
||||||
|
LOG.info("Square drawn. ");
|
||||||
|
color.fillColor();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.designpatterns.bridge;
|
||||||
|
|
||||||
|
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||||
|
|
||||||
|
public class Triangle extends Shape {
|
||||||
|
|
||||||
|
public Triangle(Color color) {
|
||||||
|
super(color);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawShape() {
|
||||||
|
LOG.info("Triangle drawn. ");
|
||||||
|
color.fillColor();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.designpatterns.decorator;
|
||||||
|
|
||||||
|
public class BubbleLights extends TreeDecorator {
|
||||||
|
|
||||||
|
public BubbleLights(ChristmasTree tree) {
|
||||||
|
super(tree);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String decorate() {
|
||||||
|
return super.decorate() + decorateWithBubbleLights();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String decorateWithBubbleLights() {
|
||||||
|
return " with Bubble Lights";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.designpatterns.decorator;
|
||||||
|
|
||||||
|
public interface ChristmasTree {
|
||||||
|
public String decorate();
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.designpatterns.decorator;
|
||||||
|
|
||||||
|
public class ChristmasTreeImpl implements ChristmasTree {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String decorate() {
|
||||||
|
return "Christmas tree";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.designpatterns.decorator;
|
||||||
|
|
||||||
|
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||||
|
|
||||||
|
public class DecoratorPatternDriver {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//christmas tree with just one Garland
|
||||||
|
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
|
||||||
|
LOG.info(tree1.decorate());
|
||||||
|
|
||||||
|
//christmas tree with two Garlands and one Bubble lights
|
||||||
|
ChristmasTree tree2 = new BubbleLights(new Garland(
|
||||||
|
new Garland(new ChristmasTreeImpl()))
|
||||||
|
);
|
||||||
|
LOG.info(tree2.decorate());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.designpatterns.decorator;
|
||||||
|
|
||||||
|
public class Garland extends TreeDecorator {
|
||||||
|
|
||||||
|
public Garland(ChristmasTree tree) {
|
||||||
|
super(tree);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String decorate() {
|
||||||
|
return super.decorate() + decorateWithGarland();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String decorateWithGarland() {
|
||||||
|
return " with Garland";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.designpatterns.decorator;
|
||||||
|
|
||||||
|
public abstract class TreeDecorator implements ChristmasTree {
|
||||||
|
private ChristmasTree tree;
|
||||||
|
|
||||||
|
public TreeDecorator(ChristmasTree tree) {
|
||||||
|
this.tree = tree;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String decorate() {
|
||||||
|
return tree.decorate();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.designpatterns.proxy;
|
||||||
|
|
||||||
|
public interface ExpensiveObject {
|
||||||
|
public void process();
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.designpatterns.proxy;
|
||||||
|
|
||||||
|
import static com.baeldung.designpatterns.util.LogerUtil.LOG;;
|
||||||
|
|
||||||
|
public class ExpensiveObjectImpl implements ExpensiveObject {
|
||||||
|
|
||||||
|
public ExpensiveObjectImpl() {
|
||||||
|
heavyInitialConfiguration();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void process() {
|
||||||
|
LOG.info("processing complete.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void heavyInitialConfiguration() {
|
||||||
|
LOG.info("Loading initial configuration...");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.designpatterns.proxy;
|
||||||
|
|
||||||
|
public class ExpensiveObjectProxy implements ExpensiveObject{
|
||||||
|
private static ExpensiveObject object;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void process() {
|
||||||
|
if(object == null) {
|
||||||
|
object = new ExpensiveObjectImpl();
|
||||||
|
}
|
||||||
|
object.process();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
package com.baeldung.designpatterns.proxy;
|
||||||
|
|
||||||
|
public class ProxyPatternDriver {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
ExpensiveObject object = new ExpensiveObjectProxy();
|
||||||
|
object.process();
|
||||||
|
object.process();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.designpatterns.singleton;
|
||||||
|
|
||||||
|
public class ClassSingleton {
|
||||||
|
|
||||||
|
private static ClassSingleton INSTANCE;
|
||||||
|
private String info = "Initial class info";
|
||||||
|
|
||||||
|
private ClassSingleton(){
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ClassSingleton getInstance(){
|
||||||
|
if(INSTANCE == null){
|
||||||
|
INSTANCE = new ClassSingleton();
|
||||||
|
}
|
||||||
|
|
||||||
|
return INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public String getInfo() {
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setInfo(String info) {
|
||||||
|
this.info = info;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.designpatterns.singleton;
|
||||||
|
|
||||||
|
public enum EnumSingleton {
|
||||||
|
|
||||||
|
INSTANCE("Initial enum info"); //Name of the single instance
|
||||||
|
|
||||||
|
private String info;
|
||||||
|
|
||||||
|
private EnumSingleton(String info) {
|
||||||
|
this.info = info;
|
||||||
|
}
|
||||||
|
|
||||||
|
public EnumSingleton getInstance(){
|
||||||
|
return INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
//getters and setters
|
||||||
|
|
||||||
|
public String getInfo() {
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setInfo(String info) {
|
||||||
|
this.info = info;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.designpatterns.singleton;
|
||||||
|
|
||||||
|
public class Sandbox {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
//Class singleton
|
||||||
|
|
||||||
|
ClassSingleton classSingleton1 = ClassSingleton.getInstance();
|
||||||
|
//OurSingleton object1 = new OurSingleton(); // The constructor OurSingleton() is not visible
|
||||||
|
|
||||||
|
System.out.println(classSingleton1.getInfo()); //Initial class info
|
||||||
|
|
||||||
|
ClassSingleton classSingleton2 = ClassSingleton.getInstance();
|
||||||
|
classSingleton2.setInfo("New class info");
|
||||||
|
|
||||||
|
System.out.println(classSingleton1.getInfo()); //New class info
|
||||||
|
System.out.println(classSingleton2.getInfo()); //New class info
|
||||||
|
|
||||||
|
//Enum singleton
|
||||||
|
|
||||||
|
EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance();
|
||||||
|
|
||||||
|
System.out.println(enumSingleton1.getInfo()); //Initial enum info
|
||||||
|
|
||||||
|
EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance();
|
||||||
|
enumSingleton2.setInfo("New enum info");
|
||||||
|
|
||||||
|
System.out.println(enumSingleton1.getInfo()); //New enum info
|
||||||
|
System.out.println(enumSingleton2.getInfo()); //New enum info
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.designpatterns.util;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import org.apache.log4j.Logger;
|
||||||
|
import org.apache.log4j.PropertyConfigurator;
|
||||||
|
|
||||||
|
public class LogerUtil {
|
||||||
|
|
||||||
|
public final static Logger LOG = Logger.getLogger("GLOBAL");
|
||||||
|
|
||||||
|
static {
|
||||||
|
configuration();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void configuration() {
|
||||||
|
Properties props = new Properties();
|
||||||
|
try {
|
||||||
|
props.load(
|
||||||
|
new BufferedReader(
|
||||||
|
new InputStreamReader(
|
||||||
|
LogerUtil.class.getResourceAsStream("/log4jstructuraldp.properties")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("log4jstructuraldp.properties file not configured properly");
|
||||||
|
System.exit(0);
|
||||||
|
}
|
||||||
|
PropertyConfigurator.configure(props);
|
||||||
|
}
|
||||||
|
}
|
@ -14,26 +14,25 @@ public class LookupFSJNDI {
|
|||||||
super();
|
super();
|
||||||
init();
|
init();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void init() throws NamingException {
|
private void init() throws NamingException {
|
||||||
Hashtable<String, String> env = new Hashtable<String, String>();
|
Hashtable<String, String> env = new Hashtable<String, String>();
|
||||||
|
|
||||||
env.put (Context.INITIAL_CONTEXT_FACTORY,
|
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
|
||||||
"com.sun.jndi.fscontext.RefFSContextFactory");
|
|
||||||
// URI to namespace (actual directory)
|
// URI to namespace (actual directory)
|
||||||
env.put(Context.PROVIDER_URL, "file:./src/test/resources");
|
env.put(Context.PROVIDER_URL, "file:./src/test/resources");
|
||||||
|
|
||||||
ctx = new InitialContext(env);
|
ctx = new InitialContext(env);
|
||||||
}
|
}
|
||||||
|
|
||||||
public InitialContext getCtx() {
|
public InitialContext getCtx() {
|
||||||
return ctx;
|
return ctx;
|
||||||
}
|
}
|
||||||
|
|
||||||
public File getFile(String fileName) {
|
public File getFile(String fileName) {
|
||||||
File file;
|
File file;
|
||||||
try {
|
try {
|
||||||
file = (File)getCtx().lookup(fileName);
|
file = (File) getCtx().lookup(fileName);
|
||||||
} catch (NamingException e) {
|
} catch (NamingException e) {
|
||||||
file = null;
|
file = null;
|
||||||
}
|
}
|
||||||
|
@ -1,23 +0,0 @@
|
|||||||
package com.baeldung.application;
|
|
||||||
|
|
||||||
import com.baeldung.entities.User;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
public class Application {
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
Map<User, User> users = new HashMap<>();
|
|
||||||
User user1 = new User(1L, "John", "john@domain.com");
|
|
||||||
User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
|
|
||||||
User user3 = new User(3L, "Mary", "mary@domain.com");
|
|
||||||
|
|
||||||
users.put(user1, user1);
|
|
||||||
users.put(user2, user2);
|
|
||||||
users.put(user3, user3);
|
|
||||||
|
|
||||||
if (users.containsKey(user1)) {
|
|
||||||
System.out.print("User found in the collection");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.entities;
|
package com.baeldung.hashcode.entities;
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@ -18,13 +18,16 @@ public class User {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object o) {
|
public boolean equals(Object o) {
|
||||||
if (this == o) return true;
|
if (this == o)
|
||||||
if (o == null) return false;
|
return true;
|
||||||
if (this.getClass() != o.getClass()) return false;
|
if (o == null)
|
||||||
|
return false;
|
||||||
|
if (this.getClass() != o.getClass())
|
||||||
|
return false;
|
||||||
User user = (User) o;
|
User user = (User) o;
|
||||||
return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
|
return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
int hash = 7;
|
int hash = 7;
|
||||||
|
@ -10,7 +10,6 @@ public class JMXTutorialMainlauncher {
|
|||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class);
|
private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class);
|
||||||
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
// TODO Auto-generated method stub
|
// TODO Auto-generated method stub
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java.networking.cookies;
|
package com.baeldung.networking.cookies;
|
||||||
|
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
import java.util.List;
|
import java.util.List;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java.networking.cookies;
|
package com.baeldung.networking.cookies;
|
||||||
|
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java.networking.udp;
|
package com.baeldung.networking.udp;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.DatagramPacket;
|
import java.net.DatagramPacket;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java.networking.udp;
|
package com.baeldung.networking.udp;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.DatagramPacket;
|
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();
|
||||||
|
}
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
@ -8,9 +8,8 @@ import java.net.*;
|
|||||||
|
|
||||||
public class EchoClient {
|
public class EchoClient {
|
||||||
|
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
|
private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
|
||||||
|
|
||||||
private Socket clientSocket;
|
private Socket clientSocket;
|
||||||
private PrintWriter out;
|
private PrintWriter out;
|
||||||
private BufferedReader in;
|
private BufferedReader in;
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.stream;
|
package com.baeldung.stream;
|
||||||
|
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
@ -12,15 +12,10 @@ class StringHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static String removeLastCharOptional(String s) {
|
static String removeLastCharOptional(String s) {
|
||||||
return Optional.ofNullable(s)
|
return Optional.ofNullable(s).filter(str -> str.length() != 0).map(str -> str.substring(0, str.length() - 1)).orElse(s);
|
||||||
.filter(str -> str.length() != 0)
|
|
||||||
.map(str -> str.substring(0, str.length() - 1))
|
|
||||||
.orElse(s);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static String removeLastCharRegexOptional(String s) {
|
static String removeLastCharRegexOptional(String s) {
|
||||||
return Optional.ofNullable(s)
|
return Optional.ofNullable(s).map(str -> str.replaceAll(".$", "")).orElse(s);
|
||||||
.map(str -> str.replaceAll(".$", ""))
|
|
||||||
.orElse(s);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -25,11 +25,7 @@ public class MyTokenizer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getTokensWithCollection(String str) {
|
public List<String> getTokensWithCollection(String str) {
|
||||||
return Collections
|
return Collections.list(new StringTokenizer(str, ",")).stream().map(token -> (String) token).collect(Collectors.toList());
|
||||||
.list(new StringTokenizer(str, ","))
|
|
||||||
.stream()
|
|
||||||
.map(token -> (String) token)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> getTokensFromFile(String path, String delim) {
|
public List<String> getTokensFromFile(String path, String delim) {
|
||||||
|
@ -11,12 +11,12 @@ public class CustomTemporalAdjuster implements TemporalAdjuster {
|
|||||||
@Override
|
@Override
|
||||||
public Temporal adjustInto(Temporal temporal) {
|
public Temporal adjustInto(Temporal temporal) {
|
||||||
switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) {
|
switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) {
|
||||||
case FRIDAY:
|
case FRIDAY:
|
||||||
return temporal.plus(3, ChronoUnit.DAYS);
|
return temporal.plus(3, ChronoUnit.DAYS);
|
||||||
case SATURDAY:
|
case SATURDAY:
|
||||||
return temporal.plus(2, ChronoUnit.DAYS);
|
return temporal.plus(2, ChronoUnit.DAYS);
|
||||||
default:
|
default:
|
||||||
return temporal.plus(1, ChronoUnit.DAYS);
|
return temporal.plus(1, ChronoUnit.DAYS);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,6 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||||||
public class Consumer implements Runnable {
|
public class Consumer implements Runnable {
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
|
private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
|
||||||
|
|
||||||
|
|
||||||
private final TransferQueue<String> transferQueue;
|
private final TransferQueue<String> transferQueue;
|
||||||
private final String name;
|
private final String name;
|
||||||
private final int numberOfMessagesToConsume;
|
private final int numberOfMessagesToConsume;
|
||||||
|
@ -0,0 +1,9 @@
|
|||||||
|
|
||||||
|
# Root logger
|
||||||
|
log4j.rootLogger=INFO, file, stdout
|
||||||
|
|
||||||
|
# Write to console
|
||||||
|
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
|
||||||
|
log4j.appender.stdout.Target=System.out
|
||||||
|
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
|
||||||
|
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
|
@ -15,28 +15,24 @@ public class LongAccumulatorUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException {
|
public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException {
|
||||||
//given
|
// given
|
||||||
ExecutorService executorService = Executors.newFixedThreadPool(8);
|
ExecutorService executorService = Executors.newFixedThreadPool(8);
|
||||||
LongBinaryOperator sum = Long::sum;
|
LongBinaryOperator sum = Long::sum;
|
||||||
LongAccumulator accumulator = new LongAccumulator(sum, 0L);
|
LongAccumulator accumulator = new LongAccumulator(sum, 0L);
|
||||||
int numberOfThreads = 4;
|
int numberOfThreads = 4;
|
||||||
int numberOfIncrements = 100;
|
int numberOfIncrements = 100;
|
||||||
|
|
||||||
//when
|
// when
|
||||||
Runnable accumulateAction = () -> IntStream
|
Runnable accumulateAction = () -> IntStream.rangeClosed(0, numberOfIncrements).forEach(accumulator::accumulate);
|
||||||
.rangeClosed(0, numberOfIncrements)
|
|
||||||
.forEach(accumulator::accumulate);
|
|
||||||
|
|
||||||
for (int i = 0; i < numberOfThreads; i++) {
|
for (int i = 0; i < numberOfThreads; i++) {
|
||||||
executorService.execute(accumulateAction);
|
executorService.execute(accumulateAction);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// then
|
||||||
//then
|
|
||||||
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
|
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
|
||||||
executorService.shutdown();
|
executorService.shutdown();
|
||||||
assertEquals(accumulator.get(), 20200);
|
assertEquals(accumulator.get(), 20200);
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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,20 @@
|
|||||||
|
package com.baeldung.designpatterns;
|
||||||
|
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapter;
|
||||||
|
import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapterImpl;
|
||||||
|
|
||||||
|
public class AdapterPatternIntegrationTest {
|
||||||
|
@Test
|
||||||
|
public void givenLuxuryCarsAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() {
|
||||||
|
LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl();
|
||||||
|
assertEquals(luxuryCars.bugattiVeyronInKMPH(), 431.30312, 0.00001);
|
||||||
|
assertEquals(luxuryCars.mcLarenInKMPH(), 387.85094, 0.00001);
|
||||||
|
assertEquals(luxuryCars.astonMartinInKMPH(), 354.0548, 0.00001);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,52 @@
|
|||||||
|
package com.baeldung.designpatterns;
|
||||||
|
|
||||||
|
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.log4j.spi.LoggingEvent;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.designpatterns.bridge.Blue;
|
||||||
|
import com.baeldung.designpatterns.bridge.Red;
|
||||||
|
import com.baeldung.designpatterns.bridge.Shape;
|
||||||
|
import com.baeldung.designpatterns.bridge.Square;
|
||||||
|
import com.baeldung.designpatterns.bridge.Triangle;
|
||||||
|
|
||||||
|
public class BridgePatternIntegrationTest {
|
||||||
|
public static TestAppenderDP appender;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
appender = new TestAppenderDP();
|
||||||
|
LOG.addAppender(appender);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenBridgePatternInvoked_thenConfigSuccess() {
|
||||||
|
//a square with red color
|
||||||
|
Shape square = new Square(new Red());
|
||||||
|
square.drawShape();
|
||||||
|
|
||||||
|
//a triangle with blue color
|
||||||
|
Shape triangle = new Triangle(new Blue());
|
||||||
|
triangle.drawShape();
|
||||||
|
|
||||||
|
final List<LoggingEvent> log = appender.getLog();
|
||||||
|
|
||||||
|
assertThat((String) log.get(0).getMessage(), is("Square drawn. "));
|
||||||
|
assertThat((String) log.get(1).getMessage(), is("Color : Red"));
|
||||||
|
assertThat((String) log.get(2).getMessage(), is("Triangle drawn. "));
|
||||||
|
assertThat((String) log.get(3).getMessage(), is("Color : Blue"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() {
|
||||||
|
LOG.removeAppender(appender);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.designpatterns;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.designpatterns.decorator.BubbleLights;
|
||||||
|
import com.baeldung.designpatterns.decorator.ChristmasTree;
|
||||||
|
import com.baeldung.designpatterns.decorator.ChristmasTreeImpl;
|
||||||
|
import com.baeldung.designpatterns.decorator.Garland;
|
||||||
|
|
||||||
|
public class DecoratorPatternIntegrationTest {
|
||||||
|
private ChristmasTree tree;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDecoratorPattern_WhenDecoratorsInjectedAtRuntime_thenConfigSuccess() {
|
||||||
|
//christmas tree with just one Garland
|
||||||
|
tree = new Garland(new ChristmasTreeImpl());
|
||||||
|
assertEquals(tree.decorate(), "Christmas tree with Garland");
|
||||||
|
|
||||||
|
//christmas tree with two Garlands and one Bubble lights
|
||||||
|
tree = new BubbleLights(new Garland(
|
||||||
|
new Garland(new ChristmasTreeImpl()))
|
||||||
|
);
|
||||||
|
assertEquals(tree.decorate(), "Christmas tree with Garland with Garland with Bubble Lights");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.designpatterns;
|
||||||
|
|
||||||
|
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.log4j.spi.LoggingEvent;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.designpatterns.proxy.ExpensiveObject;
|
||||||
|
import com.baeldung.designpatterns.proxy.ExpensiveObjectProxy;
|
||||||
|
|
||||||
|
public class ProxyPatternIntegrationTest {
|
||||||
|
public static TestAppenderDP appender;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
appender = new TestAppenderDP();
|
||||||
|
LOG.addAppender(appender);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExpensiveObjectProxy_WhenObjectInitialized_thenInitializedOnlyOnce() {
|
||||||
|
ExpensiveObject object = new ExpensiveObjectProxy();
|
||||||
|
object.process();
|
||||||
|
object.process();
|
||||||
|
|
||||||
|
final List<LoggingEvent> log = appender.getLog();
|
||||||
|
|
||||||
|
assertThat((String) log.get(0).getMessage(), is("Loading initial configuration..."));
|
||||||
|
assertThat((String) log.get(1).getMessage(), is("processing complete."));
|
||||||
|
assertThat((String) log.get(2).getMessage(), is("processing complete."));
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() {
|
||||||
|
LOG.removeAppender(appender);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.designpatterns;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.log4j.AppenderSkeleton;
|
||||||
|
import org.apache.log4j.spi.LoggingEvent;
|
||||||
|
|
||||||
|
public class TestAppenderDP extends AppenderSkeleton {
|
||||||
|
private final List<LoggingEvent> log = new ArrayList<LoggingEvent>();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean requiresLayout() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void append(final LoggingEvent loggingEvent) {
|
||||||
|
log.add(loggingEvent);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<LoggingEvent> getLog() {
|
||||||
|
return new ArrayList<LoggingEvent>(log);
|
||||||
|
}
|
||||||
|
}
|
@ -1,30 +1,26 @@
|
|||||||
package com.baeldung.application;
|
package com.baeldung.hashcode.application;
|
||||||
|
|
||||||
import org.junit.After;
|
import com.baeldung.hashcode.entities.User;
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.PrintStream;
|
import java.util.HashMap;
|
||||||
import static org.junit.Assert.assertEquals;
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class ApplicationTest {
|
public class ApplicationTest {
|
||||||
|
|
||||||
private ByteArrayOutputStream outContent;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void setUpPrintStreamInstance() throws Exception {
|
|
||||||
this.outContent = new ByteArrayOutputStream();
|
|
||||||
System.setOut(new PrintStream(outContent));
|
|
||||||
}
|
|
||||||
|
|
||||||
@After
|
|
||||||
public void tearDownByteArrayOutputStream() throws Exception {
|
|
||||||
outContent = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void main_NoInputState_TextPrintedToConsole() throws Exception {
|
public void main_NoInputState_TextPrintedToConsole() throws Exception {
|
||||||
Application.main(new String[]{});
|
Map<User, User> users = new HashMap<>();
|
||||||
assertEquals("User found in the collection", outContent.toString());
|
User user1 = new User(1L, "John", "john@domain.com");
|
||||||
|
User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
|
||||||
|
User user3 = new User(3L, "Mary", "mary@domain.com");
|
||||||
|
|
||||||
|
users.put(user1, user1);
|
||||||
|
users.put(user2, user2);
|
||||||
|
users.put(user3, user3);
|
||||||
|
|
||||||
|
assertTrue(users.containsKey(user1));
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.entities;
|
package com.baeldung.hashcode.entities;
|
||||||
|
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
@ -23,7 +23,7 @@ public class UserTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void equals_EqualUserInstance_TrueAssertion(){
|
public void equals_EqualUserInstance_TrueAssertion() {
|
||||||
Assert.assertTrue(user.equals(comparisonUser));
|
Assert.assertTrue(user.equals(comparisonUser));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -15,7 +15,6 @@ public class LambdaExceptionWrappersUnitTest {
|
|||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class);
|
||||||
|
|
||||||
|
|
||||||
private List<Integer> integers;
|
private List<Integer> integers;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
|
@ -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>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -29,12 +29,9 @@ public class ListOfListsUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListOfLists_thenCheckNames() {
|
public void givenListOfLists_thenCheckNames() {
|
||||||
assertEquals("Pen 1", ((Pen) listOfLists.get(0)
|
assertEquals("Pen 1", ((Pen) listOfLists.get(0).get(0)).getName());
|
||||||
.get(0)).getName());
|
assertEquals("Pencil 1", ((Pencil) listOfLists.get(1).get(0)).getName());
|
||||||
assertEquals("Pencil 1", ((Pencil) listOfLists.get(1)
|
assertEquals("Rubber 1", ((Rubber) listOfLists.get(2).get(0)).getName());
|
||||||
.get(0)).getName());
|
|
||||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(2)
|
|
||||||
.get(0)).getName());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@ -43,11 +40,9 @@ public class ListOfListsUnitTest {
|
|||||||
|
|
||||||
((ArrayList<Pencil>) listOfLists.get(1)).remove(0);
|
((ArrayList<Pencil>) listOfLists.get(1)).remove(0);
|
||||||
listOfLists.remove(1);
|
listOfLists.remove(1);
|
||||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1)
|
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1).get(0)).getName());
|
||||||
.get(0)).getName());
|
|
||||||
listOfLists.remove(0);
|
listOfLists.remove(0);
|
||||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0)
|
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0).get(0)).getName());
|
||||||
.get(0)).getName());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -67,11 +62,8 @@ public class ListOfListsUnitTest {
|
|||||||
list.add(pencils);
|
list.add(pencils);
|
||||||
list.add(rubbers);
|
list.add(rubbers);
|
||||||
|
|
||||||
assertEquals("Pen 1", ((Pen) list.get(0)
|
assertEquals("Pen 1", ((Pen) list.get(0).get(0)).getName());
|
||||||
.get(0)).getName());
|
assertEquals("Pencil 1", ((Pencil) list.get(1).get(0)).getName());
|
||||||
assertEquals("Pencil 1", ((Pencil) list.get(1)
|
assertEquals("Rubber 1", ((Rubber) list.get(2).get(0)).getName());
|
||||||
.get(0)).getName());
|
|
||||||
assertEquals("Rubber 1", ((Rubber) list.get(2)
|
|
||||||
.get(0)).getName());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java.networking.udp;
|
package com.baeldung.networking.udp;
|
||||||
|
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
@ -13,7 +13,6 @@ public class CoreThreadPoolIntegrationTest {
|
|||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class);
|
||||||
|
|
||||||
|
|
||||||
@Test(timeout = 1000)
|
@Test(timeout = 1000)
|
||||||
public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {
|
public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {
|
||||||
|
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
|
endpoint.name=client-endpoint
|
||||||
|
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
|
||||||
remote.connections=default
|
remote.connections=default
|
||||||
remote.connection.default.host=127.0.0.1
|
remote.connection.default.host=127.0.0.1
|
||||||
remote.connection.default.port=8080
|
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_NOANONYMOUS=false
|
||||||
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
|
remote.connection.default.username=myusername
|
||||||
remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER}
|
remote.connection.default.password=mypassword
|
||||||
remote.connection.default.username=testUser
|
|
||||||
remote.connection.default.password=admin1234!
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user