Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
4f34159616
@ -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
|
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 {
|
||||
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"));
|
||||
|
@ -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>
|
||||
|
||||
<!-- logging -->
|
||||
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
|
@ -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();
|
||||
|
@ -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
|
||||
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.concurrent.volatilekeyword;
|
||||
|
||||
|
||||
public class SharedObject {
|
||||
private volatile int count=0;
|
||||
|
||||
public 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);
|
||||
}
|
||||
}
|
@ -18,8 +18,7 @@ public class LookupFSJNDI {
|
||||
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");
|
||||
|
||||
@ -33,7 +32,7 @@ public class LookupFSJNDI {
|
||||
public File getFile(String fileName) {
|
||||
File file;
|
||||
try {
|
||||
file = (File)getCtx().lookup(fileName);
|
||||
file = (File) getCtx().lookup(fileName);
|
||||
} catch (NamingException e) {
|
||||
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.LoggerFactory;
|
||||
@ -18,9 +18,12 @@ 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));
|
||||
}
|
||||
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.java.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.java.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.java.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.java.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();
|
||||
}
|
||||
}
|
@ -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
|
||||
|
||||
|
@ -8,7 +8,6 @@ import java.net.*;
|
||||
|
||||
public class EchoClient {
|
||||
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
|
||||
|
||||
private Socket clientSocket;
|
||||
|
@ -1,6 +1,5 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
@ -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) {
|
||||
|
@ -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;
|
||||
|
@ -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
|
||||
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);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,99 @@
|
||||
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 {
|
||||
|
||||
SharedObject sharedObject;
|
||||
int valueReadByThread2;
|
||||
int valueReadByThread3;
|
||||
|
||||
@Before
|
||||
public void setUp(){
|
||||
sharedObject = new SharedObject();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
|
||||
Thread writer = new Thread(){
|
||||
public void run(){
|
||||
sharedObject.increamentCount();
|
||||
}
|
||||
};
|
||||
writer.start();
|
||||
|
||||
|
||||
Thread readerOne = new Thread(){
|
||||
public void run(){
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
valueReadByThread2= sharedObject.getCount();
|
||||
}
|
||||
};
|
||||
readerOne.start();
|
||||
|
||||
Thread readerTwo = new Thread(){
|
||||
public void run(){
|
||||
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(){
|
||||
public void run(){
|
||||
sharedObject.increamentCount();
|
||||
}
|
||||
};
|
||||
writerOne.start();
|
||||
Thread.sleep(100);
|
||||
|
||||
Thread writerTwo = new Thread(){
|
||||
public void run(){
|
||||
sharedObject.increamentCount();
|
||||
}
|
||||
};
|
||||
writerTwo.start();
|
||||
Thread.sleep(100);
|
||||
|
||||
Thread readerOne = new Thread(){
|
||||
public void run(){
|
||||
valueReadByThread2= sharedObject.getCount();
|
||||
}
|
||||
};
|
||||
readerOne.start();
|
||||
|
||||
Thread readerTwo = new Thread(){
|
||||
public void run(){
|
||||
valueReadByThread3=sharedObject.getCount();
|
||||
}
|
||||
};
|
||||
readerTwo.start();
|
||||
|
||||
assertEquals(2,valueReadByThread2);
|
||||
assertEquals(2,valueReadByThread3);
|
||||
|
||||
}
|
||||
@After
|
||||
public void cleanup(){
|
||||
sharedObject = null;
|
||||
}
|
||||
}
|
@ -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 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));
|
||||
}
|
||||
}
|
@ -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));
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.java.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.java.networking.udp.multicast;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MulticastIntegrationTest {
|
||||
private MulticastingClient client;
|
||||
|
||||
@Test
|
||||
public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception {
|
||||
int expectedServers = 4;
|
||||
initializeForExpectedServers(expectedServers);
|
||||
|
||||
int serversDiscovered = client.discoverServers("hello server");
|
||||
assertEquals(expectedServers, serversDiscovered);
|
||||
}
|
||||
|
||||
private void initializeForExpectedServers(int expectedServers) throws Exception {
|
||||
for (int i = 0; i < expectedServers; i++) {
|
||||
new MulticastEchoServer().start();
|
||||
}
|
||||
|
||||
client = new MulticastingClient(expectedServers);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws IOException {
|
||||
stopEchoServer();
|
||||
client.close();
|
||||
}
|
||||
|
||||
private void stopEchoServer() throws IOException {
|
||||
client.discoverServers("end");
|
||||
}
|
||||
}
|
@ -15,7 +15,6 @@ public class LambdaExceptionWrappersUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class);
|
||||
|
||||
|
||||
private List<Integer> integers;
|
||||
|
||||
@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
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
@ -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 {
|
||||
|
||||
|
@ -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
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.ejbclient.application;
|
||||
|
||||
import com.baeldung.ejbmodule.TextProcessorBean;
|
||||
import com.baeldung.ejbmodule.TextProcessorRemote;
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import java.util.Properties;
|
||||
|
||||
public class TextApplication {
|
||||
|
||||
public static void main(String[] args) throws NamingException {
|
||||
TextProcessorRemote textProcessor = EJBFactory.createTextProcessorBeanFromJNDI("ejb:");
|
||||
System.out.print(textProcessor.processText("sample text"));
|
||||
}
|
||||
|
||||
private static class EJBFactory {
|
||||
|
||||
private static TextProcessorRemote createTextProcessorBeanFromJNDI(String namespace) throws NamingException {
|
||||
return lookupTextProcessorBean(namespace);
|
||||
}
|
||||
|
||||
private static TextProcessorRemote lookupTextProcessorBean(String namespace) throws NamingException {
|
||||
Context ctx = createInitialContext();
|
||||
final String appName = "";
|
||||
final String moduleName = "EJBModule";
|
||||
final String distinctName = "";
|
||||
final String beanName = TextProcessorBean.class.getSimpleName();
|
||||
final String viewClassName = TextProcessorRemote.class.getName();
|
||||
return (TextProcessorRemote) ctx.lookup(namespace + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName);
|
||||
}
|
||||
|
||||
private static Context createInitialContext() throws NamingException {
|
||||
Properties jndiProperties = new Properties();
|
||||
jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
|
||||
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
|
||||
jndiProperties.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
|
||||
jndiProperties.put("jboss.naming.client.ejb.context", true);
|
||||
return new InitialContext(jndiProperties);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
endpoint.name=client-endpoint
|
||||
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
|
||||
remote.connections=default
|
||||
remote.connection.default.host=127.0.0.1
|
||||
remote.connection.default.port=8080
|
||||
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
|
||||
remote.connection.default.username=myusername
|
||||
remote.connection.default.password=mypassword
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.ejbclient.application;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import javax.naming.NamingException;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class TextApplicationTest {
|
||||
|
||||
private static ByteArrayOutputStream outContent;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpPrintStreamInstance() {
|
||||
outContent = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(outContent));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownByteArrayOutputStream() {
|
||||
outContent = null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputString_whenCompareTtoStringPrintedToConsole_thenSuccessful() throws NamingException {
|
||||
TextApplication.main(new String[]{});
|
||||
assertEquals("SAMPLE TEXT", outContent.toString());
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.baeldung.ejbmodule;
|
||||
|
||||
import javax.ejb.Stateless;
|
||||
|
||||
@Stateless
|
||||
public class TextProcessorBean implements TextProcessorRemote {
|
||||
public String processText(String text) {
|
||||
return text.toUpperCase();
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.ejbmodule;
|
||||
|
||||
import javax.ejb.Remote;
|
||||
|
||||
@Remote
|
||||
public interface TextProcessorRemote {
|
||||
|
||||
String processText(String text);
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.ejbmodule;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class TextProcessorBeanTest {
|
||||
@Test
|
||||
public void givenInputString_whenComparedToStringParsedByBean_thenSuccessful() {
|
||||
TextProcessorBean textProcessor = new TextProcessorBean();
|
||||
assertEquals("TEST", textProcessor.processText("test"));
|
||||
}
|
||||
}
|
@ -1,19 +1,23 @@
|
||||
package com.baeldung.jackson.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.deserialization.ItemDeserializer;
|
||||
import com.baeldung.jackson.dtos.Item;
|
||||
import com.baeldung.jackson.dtos.ItemWithSerializer;
|
||||
import com.baeldung.jackson.dtos.MyDto;
|
||||
import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreUnknown;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonFactory;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
@ -21,6 +25,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
|
||||
@ -165,4 +170,35 @@ public class JacksonDeserializationUnitTest {
|
||||
assertThat(readValue, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeserialisingZonedDateTimeWithDefaults_thenTimeZoneIsNotPreserved() throws IOException {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.findAndRegisterModules();
|
||||
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
// construct a new instance of ZonedDateTime
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
|
||||
String converted = objectMapper.writeValueAsString(now);
|
||||
// restore an instance of ZonedDateTime from String
|
||||
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
|
||||
System.out.println("serialized: " + now);
|
||||
System.out.println("restored: " + restored);
|
||||
assertThat(now, is(not(restored)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeserialisingZonedDateTimeWithFeaturesDisabled_thenTimeZoneIsPreserved() throws IOException {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.findAndRegisterModules();
|
||||
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
|
||||
// construct a new instance of ZonedDateTime
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
|
||||
String converted = objectMapper.writeValueAsString(now);
|
||||
// restore an instance of ZonedDateTime from String
|
||||
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
|
||||
System.out.println("serialized: " + now);
|
||||
System.out.println("restored: " + restored);
|
||||
assertThat(now, is(restored));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,3 +0,0 @@
|
||||
### Relevant articles
|
||||
|
||||
- [Introduction to jOOL](http://www.baeldung.com/jool)
|
@ -3,7 +3,7 @@
|
||||
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>
|
||||
<!-- NOT NEEDED - JSP <groupId>com.baeldung</groupId>-->
|
||||
<artifactId>junit5</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
@ -19,9 +19,9 @@
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<junit.jupiter.version>5.0.0-M5</junit.jupiter.version>
|
||||
<junit.platform.version>1.0.0-M5</junit.platform.version>
|
||||
<junit.vintage.version>4.12.0-M5</junit.vintage.version>
|
||||
<junit.jupiter.version>5.0.0-RC2</junit.jupiter.version>
|
||||
<junit.platform.version>1.0.0-RC2</junit.platform.version>
|
||||
<junit.vintage.version>4.12.0-RC2</junit.vintage.version>
|
||||
<log4j2.version>2.8.2</log4j2.version>
|
||||
<h2.version>1.4.196</h2.version>
|
||||
|
||||
|
@ -0,0 +1,50 @@
|
||||
package com.baeldung.param;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.api.extension.ParameterContext;
|
||||
import org.junit.jupiter.api.extension.ParameterResolutionException;
|
||||
import org.junit.jupiter.api.extension.ParameterResolver;
|
||||
|
||||
public class InvalidPersonParameterResolver implements ParameterResolver {
|
||||
|
||||
/**
|
||||
* The "bad" (invalid) data for testing purposes has to go somewhere, right?
|
||||
*/
|
||||
public static Person[] INVALID_PERSONS = {
|
||||
new Person().setId(1L).setLastName("Ad_ams").setFirstName("Jill,"),
|
||||
new Person().setId(2L).setLastName(",Baker").setFirstName(""),
|
||||
new Person().setId(3L).setLastName(null).setFirstName(null),
|
||||
new Person().setId(4L).setLastName("Daniel&").setFirstName("{Joseph}"),
|
||||
new Person().setId(5L).setLastName("").setFirstName("English, Jane"),
|
||||
new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */,
|
||||
// TODO: ADD MORE DATA HERE
|
||||
};
|
||||
|
||||
@Override
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
Object ret = null;
|
||||
//
|
||||
// Return a random, valid Person object if Person.class is the type of Parameter
|
||||
/// to be resolved. Otherwise return null.
|
||||
if (parameterContext.getParameter().getType() == Person.class) {
|
||||
ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)];
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
boolean ret = false;
|
||||
//
|
||||
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
|
||||
if (parameterContext.getParameter().getType() == Person.class) {
|
||||
ret = true;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
}
|
43
junit5/src/test/java/com/baeldung/param/Person.java
Normal file
43
junit5/src/test/java/com/baeldung/param/Person.java
Normal file
@ -0,0 +1,43 @@
|
||||
package com.baeldung.param;
|
||||
|
||||
/**
|
||||
* Very simple Person entity.
|
||||
* Use the Fluent-style interface to set properties.
|
||||
*
|
||||
* @author J Steven Perry
|
||||
*
|
||||
*/
|
||||
public class Person {
|
||||
|
||||
private Long id;
|
||||
private String lastName;
|
||||
private String firstName;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Person setId(Long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public Person setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public Person setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
142
junit5/src/test/java/com/baeldung/param/PersonValidator.java
Normal file
142
junit5/src/test/java/com/baeldung/param/PersonValidator.java
Normal file
@ -0,0 +1,142 @@
|
||||
package com.baeldung.param;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Somewhat contrived validation class to illustrate unit test
|
||||
* concepts.
|
||||
*
|
||||
* @author J Steven Perry
|
||||
*
|
||||
*/
|
||||
public class PersonValidator {
|
||||
|
||||
/**
|
||||
* Contrived checked exception to illustrate one possible
|
||||
* way to handle validation errors (via a checked exception).
|
||||
*
|
||||
* @author J Steven Perry
|
||||
*
|
||||
*/
|
||||
public static class ValidationException extends Exception {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -134518049431883102L;
|
||||
|
||||
// Probably should implement some more constructors, but don't want
|
||||
/// to tarnish the lesson...
|
||||
|
||||
/**
|
||||
* The one and only way to create this checked exception.
|
||||
*
|
||||
* @param message
|
||||
* The message accompanying the exception. Should be meaningful.
|
||||
*/
|
||||
public ValidationException(String message) {
|
||||
super(message);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final String[] ILLEGAL_NAME_CHARACTERS = {
|
||||
",",
|
||||
"_",
|
||||
"{",
|
||||
"}",
|
||||
"!"
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate the first name of the specified Person object.
|
||||
*
|
||||
* @param person
|
||||
* The Person object to validate.
|
||||
*
|
||||
* @return - returns true if the specified Person is valid
|
||||
*
|
||||
* @throws ValidationException
|
||||
* - this Exception is thrown if any kind of validation error occurs.
|
||||
*/
|
||||
public static boolean validateFirstName(Person person) throws ValidationException {
|
||||
boolean ret = true;
|
||||
// The validation rules go here.
|
||||
// Naive: use simple ifs
|
||||
if (person == null) {
|
||||
throw new ValidationException("Person is null (not allowed)!");
|
||||
}
|
||||
if (person.getFirstName() == null) {
|
||||
throw new ValidationException("Person FirstName is null (not allowed)!");
|
||||
}
|
||||
if (person.getFirstName().isEmpty()) {
|
||||
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
|
||||
}
|
||||
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
|
||||
throw new ValidationException(
|
||||
"Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: "
|
||||
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
|
||||
+ "!");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the last name of the specified Person object. Looks the same as first
|
||||
* name? Look closer. Just kidding. It's the same. But real world code can (and will) diverge.
|
||||
*
|
||||
* @param person
|
||||
* The Person object to validate.
|
||||
*
|
||||
* @return - returns true if the specified Person is valid
|
||||
*
|
||||
* @throws ValidationException
|
||||
* - this Exception is thrown if any kind of validation error occurs.
|
||||
*/
|
||||
public static boolean validateLastName(Person person) throws ValidationException {
|
||||
boolean ret = true;
|
||||
// The validation rules go here.
|
||||
// Naive: use simple ifs
|
||||
if (person == null) {
|
||||
throw new ValidationException("Person is null (not allowed)!");
|
||||
}
|
||||
if (person.getFirstName() == null) {
|
||||
throw new ValidationException("Person FirstName is null (not allowed)!");
|
||||
}
|
||||
if (person.getFirstName().isEmpty()) {
|
||||
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
|
||||
}
|
||||
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
|
||||
throw new ValidationException(
|
||||
"Person LastName (" + person.getLastName() + ") may not contain any of the following characters: "
|
||||
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
|
||||
+ "!");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the specified name. If it contains any of the illegalCharacters,
|
||||
* this method returns false (indicating the name is illegal). Otherwise it returns true.
|
||||
*
|
||||
* @param candidate
|
||||
* The candidate String to validate
|
||||
*
|
||||
* @param illegalCharacters
|
||||
* The characters the String is not allowed to have
|
||||
*
|
||||
* @return - boolean - true if the name is valid, false otherwise.
|
||||
*/
|
||||
private static boolean isStringValid(String candidate, String[] illegalCharacters) {
|
||||
boolean ret = true;
|
||||
for (String illegalChar : illegalCharacters) {
|
||||
if (candidate.contains(illegalChar)) {
|
||||
ret = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
}
|
102
junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java
Normal file
102
junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java
Normal file
@ -0,0 +1,102 @@
|
||||
package com.baeldung.param;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.platform.runner.JUnitPlatform;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
@RunWith(JUnitPlatform.class)
|
||||
@DisplayName("Testing PersonValidator")
|
||||
public class PersonValidatorTest {
|
||||
|
||||
/**
|
||||
* Nested class, uses ExtendWith
|
||||
* {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver}
|
||||
* to feed Test methods with "good" data.
|
||||
*/
|
||||
@Nested
|
||||
@DisplayName("When using Valid data")
|
||||
@ExtendWith(ValidPersonParameterResolver.class)
|
||||
public class ValidData {
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* A valid Person object to validate.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All first names are valid")
|
||||
public void validateFirstName(Person person) {
|
||||
try {
|
||||
assertTrue(PersonValidator.validateFirstName(person));
|
||||
} catch (PersonValidator.ValidationException e) {
|
||||
fail("Exception not expected: " + e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* A valid Person object to validate.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All last names are valid")
|
||||
public void validateLastName(Person person) {
|
||||
try {
|
||||
assertTrue(PersonValidator.validateLastName(person));
|
||||
} catch (PersonValidator.ValidationException e) {
|
||||
fail("Exception not expected: " + e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Nested class, uses ExtendWith
|
||||
* {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver}
|
||||
* to feed Test methods with "bad" data.
|
||||
*/
|
||||
@Nested
|
||||
@DisplayName("When using Invalid data")
|
||||
@ExtendWith(InvalidPersonParameterResolver.class)
|
||||
public class InvalidData {
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* An invalid Person object to validate.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All first names are invalid")
|
||||
public void validateFirstName(Person person) {
|
||||
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person));
|
||||
}
|
||||
|
||||
/**
|
||||
* Repeat the test ten times, that way we have a good shot at
|
||||
* running all of the data through at least once.
|
||||
*
|
||||
* @param person
|
||||
* An invalid Person object to validate.
|
||||
*/
|
||||
@RepeatedTest(value = 10)
|
||||
@DisplayName("All first names are invalid")
|
||||
public void validateLastName(Person person) {
|
||||
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.baeldung.param;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.api.extension.ParameterContext;
|
||||
import org.junit.jupiter.api.extension.ParameterResolutionException;
|
||||
import org.junit.jupiter.api.extension.ParameterResolver;
|
||||
|
||||
public class ValidPersonParameterResolver implements ParameterResolver {
|
||||
|
||||
/**
|
||||
* The "good" (valid) data for testing purposes has to go somewhere, right?
|
||||
*/
|
||||
public static Person[] VALID_PERSONS = {
|
||||
new Person().setId(1L).setLastName("Adams").setFirstName("Jill"),
|
||||
new Person().setId(2L).setLastName("Baker").setFirstName("James"),
|
||||
new Person().setId(3L).setLastName("Carter").setFirstName("Samanta"),
|
||||
new Person().setId(4L).setLastName("Daniels").setFirstName("Joseph"),
|
||||
new Person().setId(5L).setLastName("English").setFirstName("Jane"),
|
||||
new Person().setId(6L).setLastName("Fontana").setFirstName("Enrique"),
|
||||
// TODO: ADD MORE DATA HERE
|
||||
};
|
||||
|
||||
@Override
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
Object ret = null;
|
||||
//
|
||||
// Return a random, valid Person object if Person.class is the type of Parameter
|
||||
/// to be resolved. Otherwise return null.
|
||||
if (parameterContext.getParameter().getType() == Person.class) {
|
||||
ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)];
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
boolean ret = false;
|
||||
//
|
||||
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
|
||||
if (parameterContext.getParameter().getType() == Person.class) {
|
||||
ret = true;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
}
|
19
kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt
Normal file
19
kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt
Normal file
@ -0,0 +1,19 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
sealed class Result<out S, out F> {
|
||||
abstract fun <R> map(func: (S) -> R) : Result<R, F>
|
||||
abstract fun <R> mapFailure(func: (F) -> R) : Result<S, R>
|
||||
abstract fun get() : S?
|
||||
}
|
||||
|
||||
data class Success<out S, out F>(val success: S) : Result<S, F>() {
|
||||
override fun <R> map(func: (S) -> R) : Result<R, F> = Success(func(success))
|
||||
override fun <R> mapFailure(func: (F) -> R): Result<S, R> = Success(success)
|
||||
override fun get(): S? = success
|
||||
}
|
||||
|
||||
data class Failure<out S, out F>(val failure: F) : Result<S, F>() {
|
||||
override fun <R> map(func: (S) -> R) : Result<R, F> = Failure(failure)
|
||||
override fun <R> mapFailure(func: (F) -> R): Result<S, R> = Failure(func(failure))
|
||||
override fun get(): S? = null
|
||||
}
|
84
kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt
Normal file
84
kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt
Normal file
@ -0,0 +1,84 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class SealedTest {
|
||||
fun divide(a: Int, b: Int) : Result<Float, String> = when (b) {
|
||||
0 -> Failure("Division by zero")
|
||||
else -> Success(a.toFloat() / b)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSuccess() {
|
||||
val result = divide(10, 5)
|
||||
Assert.assertEquals(Success<Float, String>(2.0f), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testError() {
|
||||
val result = divide(10, 0)
|
||||
Assert.assertEquals(Failure<Float, String>("Division by zero"), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMatchOnSuccess() {
|
||||
val result = divide(10, 5)
|
||||
when (result) {
|
||||
is Success -> {
|
||||
// Expected
|
||||
}
|
||||
is Failure -> Assert.fail("Expected Success")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMatchOnError() {
|
||||
val result = divide(10, 0)
|
||||
when (result) {
|
||||
is Failure -> {
|
||||
// Expected
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSuccess() {
|
||||
val result = divide(10, 5)
|
||||
Assert.assertEquals(2.0f, result.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetError() {
|
||||
val result = divide(10, 0)
|
||||
Assert.assertNull(result.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMapOnSuccess() {
|
||||
val result = divide(10, 5)
|
||||
.map { "Result: $it" }
|
||||
Assert.assertEquals(Success<String, String>("Result: 2.0"), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMapOnError() {
|
||||
val result = divide(10, 0)
|
||||
.map { "Result: $it" }
|
||||
Assert.assertEquals(Failure<Float, String>("Division by zero"), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMapFailureOnSuccess() {
|
||||
val result = divide(10, 5)
|
||||
.mapFailure { "Failure: $it" }
|
||||
Assert.assertEquals(Success<Float, String>(2.0f), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMapFailureOnError() {
|
||||
val result = divide(10, 0)
|
||||
.mapFailure { "Failure: $it" }
|
||||
Assert.assertEquals(Failure<Float, String>("Failure: Division by zero"), result)
|
||||
}
|
||||
}
|
@ -28,6 +28,9 @@
|
||||
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)
|
||||
- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph)
|
||||
- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue)
|
||||
- [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss)
|
||||
- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception)
|
||||
|
||||
|
||||
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
|
||||
|
||||
|
@ -181,6 +181,11 @@
|
||||
<artifactId>jetty-servlet</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>rome</groupId>
|
||||
<artifactId>rome</artifactId>
|
||||
<version>${rome.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.specto</groupId>
|
||||
<artifactId>hoverfly-java</artifactId>
|
||||
@ -457,6 +462,16 @@
|
||||
<artifactId>pcollections</artifactId>
|
||||
<version>${pcollections.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.machinezoo.noexception</groupId>
|
||||
<artifactId>noexception</artifactId>
|
||||
<version>1.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.collections</groupId>
|
||||
<artifactId>eclipse-collections</artifactId>
|
||||
<version>${eclipse-collections.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<multiverse.version>0.7.0</multiverse.version>
|
||||
@ -497,5 +512,7 @@
|
||||
<hll.version>1.6.0</hll.version>
|
||||
<bytebuddy.version>1.7.1</bytebuddy.version>
|
||||
<pcollections.version>2.1.2</pcollections.version>
|
||||
<rome.version>1.0</rome.version>
|
||||
<eclipse-collections.version>8.2.0</eclipse-collections.version>
|
||||
</properties>
|
||||
</project>
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.eclipsecollections;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.collections.api.list.MutableList;
|
||||
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
|
||||
|
||||
public class ConvertContainerToAnother {
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static List convertToList() {
|
||||
UnifiedSet<String> cars = new UnifiedSet<>();
|
||||
|
||||
cars.add("Toyota");
|
||||
cars.add("Mercedes");
|
||||
cars.add("Volkswagen");
|
||||
|
||||
return cars.toList();
|
||||
}
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package com.baeldung.eclipsecollections;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Student {
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private List<String> addresses;
|
||||
|
||||
public Student(String firstName, String lastName) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Student(String firstName, String lastName, List<String> addresses) {
|
||||
super();
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.addresses = addresses;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return this.firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return this.lastName;
|
||||
}
|
||||
|
||||
public List<String> getAddresses() {
|
||||
return addresses;
|
||||
}
|
||||
|
||||
public void setAddresses(List<String> addresses) {
|
||||
this.addresses = addresses;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.noexception;
|
||||
|
||||
import com.machinezoo.noexception.ExceptionHandler;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class CustomExceptionHandler extends ExceptionHandler {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);
|
||||
|
||||
@Override
|
||||
public boolean handle(Throwable throwable) {
|
||||
|
||||
if (throwable.getClass()
|
||||
.isAssignableFrom(RuntimeException.class)
|
||||
|| throwable.getClass()
|
||||
.isAssignableFrom(Error.class)) {
|
||||
return false;
|
||||
} else {
|
||||
logger.error("Caught Exception ", throwable);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
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