Merge pull request #1 from eugenp/master

Merge remote changes
This commit is contained in:
Graham Cox 2017-08-21 14:03:40 +01:00 committed by GitHub
commit e5cff86190
294 changed files with 7346 additions and 1150 deletions

View File

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

View File

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

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

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

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
resource.loader=webapp
webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader
webapp.resource.loader.path = .
webapp.resource.loader.path =
webapp.resource.loader.cache = true

View File

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

11
bootique/config.yml Normal file
View 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

View 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
View 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>

View 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();
}
}

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -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!";
}
}

View File

@ -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!";
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.bootique.service;
public interface HelloService {
boolean save();
}

View File

@ -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;
}
}

View File

@ -0,0 +1 @@
com.baeldung.bootique.module.ModuleProvider

View 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());
}
}

View File

@ -6,7 +6,7 @@ public class ServiceMain {
public static void main(String[] args) throws InterruptedException {
ProcessHandle thisProcess = ProcessHandle.current();
long pid = thisProcess.getPid();
long pid = thisProcess.pid();
Optional<String[]> opArgs = Optional.ofNullable(args);
String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));

View File

@ -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);
}
}

View File

@ -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>

View File

@ -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");
}
}
}

View File

@ -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
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -80,7 +80,11 @@
</dependency>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>

View File

@ -15,14 +15,12 @@ public class CyclicBarrierDemo {
private int NUM_PARTIAL_RESULTS;
private int NUM_WORKERS;
private void runSimulation(int numWorkers, int numberOfPartialResults) {
NUM_PARTIAL_RESULTS = numberOfPartialResults;
NUM_WORKERS = numWorkers;
cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute "
+ NUM_PARTIAL_RESULTS + " partial results each");
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " + NUM_PARTIAL_RESULTS + " partial results each");
for (int i = 0; i < NUM_WORKERS; i++) {
Thread worker = new Thread(new NumberCruncherThread());
worker.setName("Thread " + i);
@ -38,8 +36,7 @@ public class CyclicBarrierDemo {
List<Integer> partialResult = new ArrayList<>();
for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
Integer num = random.nextInt(10);
System.out.println(thisThreadName
+ ": Crunching some numbers! Final result - " + num);
System.out.println(thisThreadName + ": Crunching some numbers! Final result - " + num);
partialResult.add(num);
}
partialResults.add(partialResult);
@ -57,13 +54,12 @@ public class CyclicBarrierDemo {
@Override
public void run() {
String thisThreadName = Thread.currentThread().getName();
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS
+ " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS + " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
int sum = 0;
for (List<Integer> threadResult : partialResults) {
System.out.print("Adding ");
for (Integer partialResult : threadResult) {
System.out.print(partialResult+" ");
System.out.print(partialResult + " ");
sum += partialResult;
}
System.out.println();

View File

@ -15,7 +15,8 @@ public class Philosopher implements Runnable {
Thread.sleep(((int) (Math.random() * 100)));
}
@Override public void run() {
@Override
public void run() {
try {
while (true) {
doAction(System.nanoTime() + ": Thinking"); // thinking

View File

@ -6,22 +6,22 @@ import java.util.concurrent.TimeUnit;
public class ExecutorServiceDemo {
ExecutorService executor = Executors.newFixedThreadPool(10);
ExecutorService executor = Executors.newFixedThreadPool(10);
public void execute() {
public void execute() {
executor.submit(() -> {
new Task();
});
executor.submit(() -> {
new Task();
});
executor.shutdown();
executor.shutdownNow();
try {
executor.awaitTermination(20l, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
executor.shutdownNow();
try {
executor.awaitTermination(20l, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

View File

@ -9,36 +9,36 @@ import java.util.concurrent.TimeoutException;
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(() -> {
// Task
Thread.sleep(10000l);
return "Hellow world";
});
Future<String> future = executorService.submit(() -> {
// Task
Thread.sleep(10000l);
return "Hellow world";
});
future.cancel(false);
future.cancel(false);
try {
future.get(20, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e1) {
e1.printStackTrace();
}
try {
future.get(20, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e1) {
e1.printStackTrace();
}
if (future.isDone() && !future.isCancelled()) {
try {
str = future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
if (future.isDone() && !future.isCancelled()) {
try {
str = future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
return str;
return str;
}
}
}

View File

@ -4,20 +4,20 @@ import java.util.concurrent.ThreadFactory;
public class BaeldungThreadFactory implements ThreadFactory {
private int threadId;
private String name;
private int threadId;
private String name;
public BaeldungThreadFactory(String name) {
threadId = 1;
this.name = name;
}
public BaeldungThreadFactory(String name) {
threadId = 1;
this.name = name;
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, name + "-Thread_" + threadId);
System.out.println("created new thread with id : " + threadId + " and name : " + t.getName());
threadId++;
return t;
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, name + "-Thread_" + threadId);
System.out.println("created new thread with id : " + threadId + " and name : " + t.getName());
threadId++;
return t;
}
}

View File

@ -2,9 +2,9 @@ package com.baeldung.concurrent.threadfactory;
public class Task implements Runnable {
@Override
public void run() {
// task details
}
@Override
public void run() {
// task details
}
}

View File

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

View File

@ -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.");
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.designpatterns.adapter;
public interface LuxuryCarsSpeedAdapter {
public double bugattiVeyronInKMPH();
public double mcLarenInKMPH();
public double astonMartinInKMPH();
}

View File

@ -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;
}
}

View File

@ -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");
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.bridge;
public interface Color {
public void fillColor();
}

View File

@ -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");
}
}

View File

@ -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();
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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";
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.decorator;
public interface ChristmasTree {
public String decorate();
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.decorator;
public class ChristmasTreeImpl implements ChristmasTree {
@Override
public String decorate() {
return "Christmas tree";
}
}

View File

@ -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());
}
}

View File

@ -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";
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.proxy;
public interface ExpensiveObject {
public void process();
}

View File

@ -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...");
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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
}
}

View File

@ -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);
}
}

View File

@ -14,26 +14,25 @@ public class LookupFSJNDI {
super();
init();
}
private void init() throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put (Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
// URI to namespace (actual directory)
env.put(Context.PROVIDER_URL, "file:./src/test/resources");
ctx = new InitialContext(env);
}
public InitialContext getCtx() {
return ctx;
}
public File getFile(String fileName) {
File file;
try {
file = (File)getCtx().lookup(fileName);
file = (File) getCtx().lookup(fileName);
} catch (NamingException e) {
file = null;
}

View File

@ -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");
}
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.entities;
package com.baeldung.hashcode.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -18,13 +18,16 @@ public class User {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (this.getClass() != o.getClass()) return false;
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;

View File

@ -10,7 +10,6 @@ public class JMXTutorialMainlauncher {
private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class);
public static void main(String[] args) {
// TODO Auto-generated method stub

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -8,9 +8,8 @@ import java.net.*;
public class EchoClient {
private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;

View File

@ -1,6 +1,5 @@
package com.baeldung.stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -12,15 +12,10 @@ class StringHelper {
}
static String removeLastCharOptional(String s) {
return Optional.ofNullable(s)
.filter(str -> str.length() != 0)
.map(str -> str.substring(0, str.length() - 1))
.orElse(s);
return Optional.ofNullable(s).filter(str -> str.length() != 0).map(str -> str.substring(0, str.length() - 1)).orElse(s);
}
static String removeLastCharRegexOptional(String s) {
return Optional.ofNullable(s)
.map(str -> str.replaceAll(".$", ""))
.orElse(s);
return Optional.ofNullable(s).map(str -> str.replaceAll(".$", "")).orElse(s);
}
}

View File

@ -25,11 +25,7 @@ public class MyTokenizer {
}
public List<String> getTokensWithCollection(String str) {
return Collections
.list(new StringTokenizer(str, ","))
.stream()
.map(token -> (String) token)
.collect(Collectors.toList());
return Collections.list(new StringTokenizer(str, ",")).stream().map(token -> (String) token).collect(Collectors.toList());
}
public List<String> getTokensFromFile(String path, String delim) {

View File

@ -11,12 +11,12 @@ public class CustomTemporalAdjuster implements TemporalAdjuster {
@Override
public Temporal adjustInto(Temporal temporal) {
switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) {
case FRIDAY:
return temporal.plus(3, ChronoUnit.DAYS);
case SATURDAY:
return temporal.plus(2, ChronoUnit.DAYS);
default:
return temporal.plus(1, ChronoUnit.DAYS);
case FRIDAY:
return temporal.plus(3, ChronoUnit.DAYS);
case SATURDAY:
return temporal.plus(2, ChronoUnit.DAYS);
default:
return temporal.plus(1, ChronoUnit.DAYS);
}
}
}

View File

@ -9,7 +9,6 @@ import java.util.concurrent.atomic.AtomicInteger;
public class Consumer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
private final TransferQueue<String> transferQueue;
private final String name;
private final int numberOfMessagesToConsume;

View File

@ -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

View File

@ -15,28 +15,24 @@ public class LongAccumulatorUnitTest {
@Test
public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException {
//given
// given
ExecutorService executorService = Executors.newFixedThreadPool(8);
LongBinaryOperator sum = Long::sum;
LongAccumulator accumulator = new LongAccumulator(sum, 0L);
int numberOfThreads = 4;
int numberOfIncrements = 100;
//when
Runnable accumulateAction = () -> IntStream
.rangeClosed(0, numberOfIncrements)
.forEach(accumulator::accumulate);
// when
Runnable accumulateAction = () -> IntStream.rangeClosed(0, numberOfIncrements).forEach(accumulator::accumulate);
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(accumulateAction);
}
//then
// then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown();
assertEquals(accumulator.get(), 20200);
}
}

View File

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

View File

@ -0,0 +1,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);
}
}

View File

@ -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);
}
}

View File

@ -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");
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -1,30 +1,26 @@
package com.baeldung.application;
package com.baeldung.hashcode.application;
import org.junit.After;
import org.junit.Before;
import com.baeldung.hashcode.entities.User;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertTrue;
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());
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);
assertTrue(users.containsKey(user1));
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.entities;
package com.baeldung.hashcode.entities;
import org.junit.After;
import org.junit.Assert;
@ -23,7 +23,7 @@ public class UserTest {
}
@Test
public void equals_EqualUserInstance_TrueAssertion(){
public void equals_EqualUserInstance_TrueAssertion() {
Assert.assertTrue(user.equals(comparisonUser));
}

View File

@ -15,7 +15,6 @@ public class LambdaExceptionWrappersUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class);
private List<Integer> integers;
@Before

View File

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

View File

@ -29,12 +29,9 @@ public class ListOfListsUnitTest {
@Test
public void givenListOfLists_thenCheckNames() {
assertEquals("Pen 1", ((Pen) listOfLists.get(0)
.get(0)).getName());
assertEquals("Pencil 1", ((Pencil) listOfLists.get(1)
.get(0)).getName());
assertEquals("Rubber 1", ((Rubber) listOfLists.get(2)
.get(0)).getName());
assertEquals("Pen 1", ((Pen) listOfLists.get(0).get(0)).getName());
assertEquals("Pencil 1", ((Pencil) listOfLists.get(1).get(0)).getName());
assertEquals("Rubber 1", ((Rubber) listOfLists.get(2).get(0)).getName());
}
@SuppressWarnings("unchecked")
@ -43,11 +40,9 @@ public class ListOfListsUnitTest {
((ArrayList<Pencil>) listOfLists.get(1)).remove(0);
listOfLists.remove(1);
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1)
.get(0)).getName());
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1).get(0)).getName());
listOfLists.remove(0);
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0)
.get(0)).getName());
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0).get(0)).getName());
}
@Test
@ -67,11 +62,8 @@ public class ListOfListsUnitTest {
list.add(pencils);
list.add(rubbers);
assertEquals("Pen 1", ((Pen) list.get(0)
.get(0)).getName());
assertEquals("Pencil 1", ((Pencil) list.get(1)
.get(0)).getName());
assertEquals("Rubber 1", ((Rubber) list.get(2)
.get(0)).getName());
assertEquals("Pen 1", ((Pen) list.get(0).get(0)).getName());
assertEquals("Pencil 1", ((Pencil) list.get(1).get(0)).getName());
assertEquals("Rubber 1", ((Rubber) list.get(2).get(0)).getName());
}
}

View File

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

View File

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

View File

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

View File

@ -13,7 +13,6 @@ public class CoreThreadPoolIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class);
@Test(timeout = 1000)
public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {

View File

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

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