[BAEL-16824] - Added modules alphabatically
This commit is contained in:
+3
-2
@@ -1,11 +1,12 @@
|
||||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
public class SequenceGenerator {
|
||||
|
||||
private int currentValue = 0;
|
||||
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
public int getNextSequence() {
|
||||
currentValue = currentValue + 1;
|
||||
Thread.sleep(500);
|
||||
return currentValue;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+5
-4
@@ -4,15 +4,16 @@ import com.google.common.util.concurrent.Monitor;
|
||||
|
||||
public class SequenceGeneratorUsingMonitor extends SequenceGenerator {
|
||||
|
||||
private Monitor monitor = new Monitor();
|
||||
private Monitor mutex = new Monitor();
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
monitor.enter();
|
||||
public int getNextSequence() {
|
||||
mutex.enter();
|
||||
try {
|
||||
return super.getNextSequence();
|
||||
} finally {
|
||||
monitor.leave();
|
||||
mutex.leave();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-1
@@ -7,7 +7,7 @@ public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator {
|
||||
private ReentrantLock mutex = new ReentrantLock();
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
public int getNextSequence() {
|
||||
try {
|
||||
mutex.lock();
|
||||
return super.getNextSequence();
|
||||
@@ -15,4 +15,5 @@ public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator {
|
||||
mutex.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+4
-1
@@ -7,12 +7,15 @@ public class SequenceGeneratorUsingSemaphore extends SequenceGenerator {
|
||||
private Semaphore mutex = new Semaphore(1);
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
public int getNextSequence() {
|
||||
try {
|
||||
mutex.acquire();
|
||||
return super.getNextSequence();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException("Exception in critical section.", e);
|
||||
} finally {
|
||||
mutex.release();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+4
-2
@@ -2,9 +2,11 @@ package com.baeldung.concurrent.mutex;
|
||||
|
||||
public class SequenceGeneratorUsingSynchronizedBlock extends SequenceGenerator {
|
||||
|
||||
private Object mutex = new Object();
|
||||
|
||||
@Override
|
||||
public int getNextSequence() throws InterruptedException {
|
||||
synchronized (this) {
|
||||
public int getNextSequence() {
|
||||
synchronized (mutex) {
|
||||
return super.getNextSequence();
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ package com.baeldung.concurrent.mutex;
|
||||
public class SequenceGeneratorUsingSynchronizedMethod extends SequenceGenerator {
|
||||
|
||||
@Override
|
||||
public synchronized int getNextSequence() throws InterruptedException {
|
||||
public synchronized int getNextSequence() {
|
||||
return super.getNextSequence();
|
||||
}
|
||||
|
||||
|
||||
+26
-27
@@ -1,7 +1,7 @@
|
||||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -12,59 +12,58 @@ import java.util.concurrent.TimeUnit;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.concurrent.mutex.SequenceGenerator;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingMonitor;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingReentrantLock;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSemaphore;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedBlock;
|
||||
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedMethod;
|
||||
|
||||
public class MutexUnitTest {
|
||||
|
||||
private final int RANGE = 30;
|
||||
|
||||
@Test
|
||||
// @Test
|
||||
// This test verifies the race condition use case, it may pass or fail based on execution environment
|
||||
// Uncomment @Test to run it
|
||||
public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavior() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGenerator());
|
||||
Assert.assertNotEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGenerator(), count);
|
||||
Assert.assertNotEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingSynchronizedMethod_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedMethod());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingSynchronizedMethod(), count);
|
||||
Assert.assertEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingSynchronizedBlock_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedBlock());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingSynchronizedBlock(), count);
|
||||
Assert.assertEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingReentrantLock_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingReentrantLock());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingReentrantLock(), count);
|
||||
Assert.assertEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingSemaphore_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSemaphore());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingSemaphore(), count);
|
||||
Assert.assertEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSequenceGeneratorUsingMonitor_whenRaceCondition_thenSuccess() throws Exception {
|
||||
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingMonitor());
|
||||
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||
int count = 1000;
|
||||
Set<Integer> uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingMonitor(), count);
|
||||
Assert.assertEquals(count, uniqueSequences.size());
|
||||
}
|
||||
|
||||
private Set<Integer> getASetOFUniqueSequences(SequenceGenerator generator) throws Exception {
|
||||
private Set<Integer> getUniqueSequences(SequenceGenerator generator, int count) throws Exception {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||
Set<Integer> uniqueSequences = new HashSet<>();
|
||||
Set<Integer> uniqueSequences = new LinkedHashSet<>();
|
||||
List<Future<Integer>> futures = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < RANGE; i++) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
futures.add(executor.submit(generator::getNextSequence));
|
||||
}
|
||||
|
||||
@@ -72,7 +71,7 @@ public class MutexUnitTest {
|
||||
uniqueSequences.add(future.get());
|
||||
}
|
||||
|
||||
executor.awaitTermination(15, TimeUnit.SECONDS);
|
||||
executor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
executor.shutdown();
|
||||
|
||||
return uniqueSequences;
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.exceptions;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
|
||||
public class CheckedUncheckedExceptions {
|
||||
public static void checkedExceptionWithThrows() throws FileNotFoundException {
|
||||
File file = new File("not_existing_file.txt");
|
||||
FileInputStream stream = new FileInputStream(file);
|
||||
}
|
||||
|
||||
public static void checkedExceptionWithTryCatch() {
|
||||
File file = new File("not_existing_file.txt");
|
||||
try {
|
||||
FileInputStream stream = new FileInputStream(file);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static int divideByZero() {
|
||||
int numerator = 1;
|
||||
int denominator = 0;
|
||||
return numerator / denominator;
|
||||
}
|
||||
|
||||
public static void checkFile(String fileName) throws IncorrectFileNameException {
|
||||
if (fileName == null || fileName.isEmpty()) {
|
||||
throw new NullOrEmptyException("The filename is null.");
|
||||
}
|
||||
if (!isCorrectFileName(fileName)) {
|
||||
throw new IncorrectFileNameException("Incorrect filename : " + fileName);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isCorrectFileName(String fileName) {
|
||||
if (fileName.equals("wrongFileName.txt"))
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.exceptions;
|
||||
|
||||
public class IncorrectFileNameException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileNameException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
}
|
||||
|
||||
public IncorrectFileNameException(String errorMessage, Throwable thr) {
|
||||
super(errorMessage, thr);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.exceptions;
|
||||
|
||||
public class NullOrEmptyException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public NullOrEmptyException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
}
|
||||
|
||||
public NullOrEmptyException(String errorMessage, Throwable thr) {
|
||||
super(errorMessage, thr);
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.exceptions;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests the {@link CheckedUncheckedExceptions}.
|
||||
*/
|
||||
public class CheckedUncheckedExceptionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenFileNotExist_thenThrowException() {
|
||||
assertThrows(FileNotFoundException.class, () -> {
|
||||
CheckedUncheckedExceptions.checkedExceptionWithThrows();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTryCatchExcetpion_thenSuccess() {
|
||||
try {
|
||||
CheckedUncheckedExceptions.checkedExceptionWithTryCatch();
|
||||
} catch (Exception e) {
|
||||
Assertions.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivideByZero_thenThrowException() {
|
||||
assertThrows(ArithmeticException.class, () -> {
|
||||
CheckedUncheckedExceptions.divideByZero();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInvalidFile_thenThrowException() {
|
||||
|
||||
assertThrows(IncorrectFileNameException.class, () -> {
|
||||
CheckedUncheckedExceptions.checkFile("wrongFileName.txt");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullOrEmptyFile_thenThrowException() {
|
||||
assertThrows(NullOrEmptyException.class, () -> {
|
||||
CheckedUncheckedExceptions.checkFile(null);
|
||||
});
|
||||
assertThrows(NullOrEmptyException.class, () -> {
|
||||
CheckedUncheckedExceptions.checkFile("");
|
||||
});
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.core.modifiers;
|
||||
|
||||
public class Employee {
|
||||
|
||||
private String privateId;
|
||||
public String name;
|
||||
private boolean manager;
|
||||
|
||||
public Employee(String id, String name) {
|
||||
changeId(id);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
private Employee(String id, String name, boolean managerAttribute) {
|
||||
this.privateId = id;
|
||||
this.name = name;
|
||||
this.privateId = id + "_ID-MANAGER";
|
||||
}
|
||||
|
||||
public void changeId(String customId) {
|
||||
if (customId.endsWith("_ID")) {
|
||||
this.privateId = customId;
|
||||
} else {
|
||||
this.privateId = customId + "_ID";
|
||||
}
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return privateId;
|
||||
}
|
||||
|
||||
public boolean isManager() {
|
||||
return manager;
|
||||
}
|
||||
|
||||
public void elevateToManager() {
|
||||
if ("Carl".equals(this.name)) {
|
||||
setManager(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void setManager(boolean manager) {
|
||||
this.manager = manager;
|
||||
}
|
||||
|
||||
public static Employee buildManager(String id, String name) {
|
||||
return new Employee(id, name, true);
|
||||
}
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.core.modifiers;
|
||||
|
||||
public class ExampleClass {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Employee employee = new Employee("Bob","ABC123");
|
||||
employee.changeId("BCD234");
|
||||
System.out.println(employee.getId());
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.core.modifiers;
|
||||
|
||||
public class PublicOuterClass {
|
||||
|
||||
public PrivateInnerClass getInnerClassInstance() {
|
||||
PrivateInnerClass myPrivateClassInstance = this.new PrivateInnerClass();
|
||||
myPrivateClassInstance.id = "ID1";
|
||||
myPrivateClassInstance.name = "Bob";
|
||||
return myPrivateClassInstance;
|
||||
}
|
||||
|
||||
private class PrivateInnerClass {
|
||||
public String name;
|
||||
public String id;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
/build/
|
||||
/bin/
|
||||
.settings
|
||||
.gradle
|
||||
.project
|
||||
.classpath
|
||||
@@ -0,0 +1,26 @@
|
||||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
||||
@@ -0,0 +1,6 @@
|
||||
=========
|
||||
|
||||
## Basic Implementation of Blockchian in Java
|
||||
|
||||
### Relevant Articles:
|
||||
- []()
|
||||
@@ -0,0 +1,40 @@
|
||||
<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.blockchain</groupId>
|
||||
<artifactId>java-blockchain</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>java-blockchain</name>
|
||||
<packaging>jar</packaging>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
<build>
|
||||
<finalName>java-blockchain</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.blockchain;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Date;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class Block {
|
||||
|
||||
private static Logger logger = Logger.getLogger(Block.class.getName());
|
||||
|
||||
private String hash;
|
||||
private String previousHash;
|
||||
private String data;
|
||||
private long timeStamp;
|
||||
private int nonce;
|
||||
|
||||
public Block(String data, String previousHash) {
|
||||
this.data = data;
|
||||
this.previousHash = previousHash;
|
||||
this.timeStamp = new Date().getTime();
|
||||
this.hash = calculateBlockHash();
|
||||
}
|
||||
|
||||
public String mineBlock(int prefix) {
|
||||
String prefixString = new String(new char[prefix]).replace('\0', '0');
|
||||
while (!hash.substring(0, prefix)
|
||||
.equals(prefixString)) {
|
||||
nonce++;
|
||||
hash = calculateBlockHash();
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
public String calculateBlockHash() {
|
||||
String dataToHash = previousHash + Long.toString(timeStamp) + Integer.toString(nonce) + data;
|
||||
MessageDigest digest = null;
|
||||
byte[] bytes = null;
|
||||
try {
|
||||
digest = MessageDigest.getInstance("SHA-256");
|
||||
bytes = digest.digest(dataToHash.getBytes("UTF-8"));
|
||||
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
|
||||
logger.log(Level.SEVERE, ex.getMessage());
|
||||
}
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
for (byte b : bytes) {
|
||||
buffer.append(String.format("%02x", b));
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
public String getHash() {
|
||||
return this.hash;
|
||||
}
|
||||
|
||||
public String getPreviousHash() {
|
||||
return this.previousHash;
|
||||
}
|
||||
|
||||
public void setData(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.blockchain;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class BlockchainUnitTest {
|
||||
|
||||
public static List<Block> blockchain = new ArrayList<Block>();
|
||||
public static int prefix = 4;
|
||||
public static String prefixString = new String(new char[prefix]).replace('\0', '0');
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
Block genesisBlock = new Block("The is the Genesis Block.", "0");
|
||||
genesisBlock.mineBlock(prefix);
|
||||
blockchain.add(genesisBlock);
|
||||
Block firstBlock = new Block("The is the First Block.", genesisBlock.getHash());
|
||||
firstBlock.mineBlock(prefix);
|
||||
blockchain.add(firstBlock);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBlockchain_whenNewBlockAdded_thenSuccess() {
|
||||
Block newBlock = new Block("The is a New Block.", blockchain.get(blockchain.size() - 1)
|
||||
.getHash());
|
||||
newBlock.mineBlock(prefix);
|
||||
assertTrue(newBlock.getHash()
|
||||
.substring(0, prefix)
|
||||
.equals(prefixString));
|
||||
blockchain.add(newBlock);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBlockchain_whenValidated_thenSuccess() {
|
||||
boolean flag = true;
|
||||
for (int i = 0; i < blockchain.size(); i++) {
|
||||
String previousHash = i == 0 ? "0"
|
||||
: blockchain.get(i - 1)
|
||||
.getHash();
|
||||
flag = blockchain.get(i)
|
||||
.getHash()
|
||||
.equals(blockchain.get(i)
|
||||
.calculateBlockHash())
|
||||
&& previousHash.equals(blockchain.get(i)
|
||||
.getPreviousHash())
|
||||
&& blockchain.get(i)
|
||||
.getHash()
|
||||
.substring(0, prefix)
|
||||
.equals(prefixString);
|
||||
if (!flag)
|
||||
break;
|
||||
}
|
||||
assertTrue(flag);
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDown() {
|
||||
blockchain.clear();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.baeldung.jdi;
|
||||
|
||||
public class JDIExample {
|
||||
public class JDIExampleDebuggee {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String jpda = "Java Platform Debugger Architecture";
|
||||
@@ -123,7 +123,7 @@ public class JDIExampleDebugger {
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
JDIExampleDebugger debuggerInstance = new JDIExampleDebugger();
|
||||
debuggerInstance.setDebugClass(JDIExample.class);
|
||||
debuggerInstance.setDebugClass(JDIExampleDebuggee.class);
|
||||
int[] breakPoints = {6, 9};
|
||||
debuggerInstance.setBreakPointLines(breakPoints);
|
||||
VirtualMachine vm = null;
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.string.streamtokenizer;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class StreamTokenizerDemo {
|
||||
|
||||
private static final String INPUT_FILE = "/stream-tokenizer-example.txt";
|
||||
private static final int QUOTE_CHARACTER = '\'';
|
||||
private static final int DOUBLE_QUOTE_CHARACTER = '"';
|
||||
|
||||
public static List<Object> streamTokenizerWithDefaultConfiguration(Reader reader) throws IOException {
|
||||
StreamTokenizer streamTokenizer = new StreamTokenizer(reader);
|
||||
List<Object> tokens = new ArrayList<>();
|
||||
|
||||
int currentToken = streamTokenizer.nextToken();
|
||||
while (currentToken != StreamTokenizer.TT_EOF) {
|
||||
|
||||
if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER) {
|
||||
tokens.add(streamTokenizer.nval);
|
||||
} else if (streamTokenizer.ttype == StreamTokenizer.TT_WORD
|
||||
|| streamTokenizer.ttype == QUOTE_CHARACTER
|
||||
|| streamTokenizer.ttype == DOUBLE_QUOTE_CHARACTER) {
|
||||
tokens.add(streamTokenizer.sval);
|
||||
} else {
|
||||
tokens.add((char) currentToken);
|
||||
}
|
||||
|
||||
currentToken = streamTokenizer.nextToken();
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
public static List<Object> streamTokenizerWithCustomConfiguration(Reader reader) throws IOException {
|
||||
StreamTokenizer streamTokenizer = new StreamTokenizer(reader);
|
||||
List<Object> tokens = new ArrayList<>();
|
||||
|
||||
streamTokenizer.wordChars('!', '-');
|
||||
streamTokenizer.ordinaryChar('/');
|
||||
streamTokenizer.commentChar('#');
|
||||
streamTokenizer.eolIsSignificant(true);
|
||||
|
||||
int currentToken = streamTokenizer.nextToken();
|
||||
while (currentToken != StreamTokenizer.TT_EOF) {
|
||||
|
||||
if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER) {
|
||||
tokens.add(streamTokenizer.nval);
|
||||
} else if (streamTokenizer.ttype == StreamTokenizer.TT_WORD
|
||||
|| streamTokenizer.ttype == QUOTE_CHARACTER
|
||||
|| streamTokenizer.ttype == DOUBLE_QUOTE_CHARACTER) {
|
||||
tokens.add(streamTokenizer.sval);
|
||||
} else {
|
||||
tokens.add((char) currentToken);
|
||||
}
|
||||
currentToken = streamTokenizer.nextToken();
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
public static Reader createReaderFromFile() throws FileNotFoundException {
|
||||
String inputFile = StreamTokenizerDemo.class.getResource(INPUT_FILE).getFile();
|
||||
return new FileReader(inputFile);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
List<Object> tokens1 = streamTokenizerWithDefaultConfiguration(createReaderFromFile());
|
||||
List<Object> tokens2 = streamTokenizerWithCustomConfiguration(createReaderFromFile());
|
||||
|
||||
System.out.println(tokens1);
|
||||
System.out.println(tokens2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
3 quick brown foxes jump over the "lazy" dog!
|
||||
#test1
|
||||
//test2
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.string.streamtokenizer;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
public class StreamTokenizerDemoUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenStreamTokenizerWithDefaultConfigurationIsCalled_ThenCorrectTokensAreReturned() throws IOException {
|
||||
Reader reader = StreamTokenizerDemo.createReaderFromFile();
|
||||
List<Object> expectedTokens = Arrays.asList(3.0, "quick", "brown", "foxes", "jump", "over", "the", "lazy", "dog", '!', '#', "test1");
|
||||
|
||||
List<Object> actualTokens = StreamTokenizerDemo.streamTokenizerWithDefaultConfiguration(reader);
|
||||
|
||||
assertArrayEquals(expectedTokens.toArray(), actualTokens.toArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStreamTokenizerWithCustomConfigurationIsCalled_ThenCorrectTokensAreReturned() throws IOException {
|
||||
Reader reader = StreamTokenizerDemo.createReaderFromFile();
|
||||
List<Object> expectedTokens = Arrays.asList(3.0, "quick", "brown", "foxes", "jump", "over", "the", "\"lazy\"", "dog!", '\n', '\n', '/', '/', "test2");
|
||||
|
||||
List<Object> actualTokens = StreamTokenizerDemo.streamTokenizerWithCustomConfiguration(reader);
|
||||
|
||||
assertArrayEquals(expectedTokens.toArray(), actualTokens.toArray());
|
||||
}
|
||||
|
||||
}
|
||||
+16
-1
@@ -32,7 +32,7 @@
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.containers</groupId>
|
||||
<artifactId>jersey-container-grizzly2-servlet</artifactId>
|
||||
<version>${jersey.version}</version>
|
||||
<version>${jersey.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.ext</groupId>
|
||||
@@ -44,6 +44,21 @@
|
||||
<artifactId>jersey-bean-validation</artifactId>
|
||||
<version>${jersey.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.security</groupId>
|
||||
<artifactId>oauth1-client</artifactId>
|
||||
<version>${jersey.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.security</groupId>
|
||||
<artifactId>oauth2-client</artifactId>
|
||||
<version>${jersey.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-sse</artifactId>
|
||||
<version>${jersey.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.test-framework</groupId>
|
||||
<artifactId>jersey-test-framework-core</artifactId>
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.baeldung.jersey.client;
|
||||
|
||||
import com.baeldung.jersey.client.filter.AddHeaderOnRequestFilter;
|
||||
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
|
||||
import org.glassfish.jersey.client.oauth1.AccessToken;
|
||||
import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
|
||||
import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
|
||||
import org.glassfish.jersey.client.oauth2.OAuth2ClientSupport;
|
||||
|
||||
import javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.client.ClientBuilder;
|
||||
import javax.ws.rs.client.Invocation;
|
||||
import javax.ws.rs.client.WebTarget;
|
||||
import javax.ws.rs.core.Feature;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.sse.InboundSseEvent;
|
||||
import javax.ws.rs.sse.SseEventSource;
|
||||
|
||||
import static org.glassfish.jersey.client.authentication.HttpAuthenticationFeature.*;
|
||||
|
||||
public class JerseyClientHeaders {
|
||||
|
||||
private static final String BEARER_CONSUMER_SECRET = "my-consumer-secret";
|
||||
private static final String BEARER_ACCESS_TOKEN_SECRET = "my-access-token-secret";
|
||||
private static final String TARGET = "http://localhost:9998/";
|
||||
private static final String MAIN_RESOURCE = "echo-headers";
|
||||
private static final String RESOURCE_AUTH_DIGEST = "digest";
|
||||
|
||||
private static String sseHeaderValue;
|
||||
|
||||
public static Response simpleHeader(String headerKey, String headerValue) {
|
||||
Client client = ClientBuilder.newClient();
|
||||
WebTarget webTarget = client.target(TARGET);
|
||||
WebTarget resourceWebTarget = webTarget.path(MAIN_RESOURCE);
|
||||
Invocation.Builder invocationBuilder = resourceWebTarget.request();
|
||||
invocationBuilder.header(headerKey, headerValue);
|
||||
return invocationBuilder.get();
|
||||
}
|
||||
|
||||
public static Response simpleHeaderFluently(String headerKey, String headerValue) {
|
||||
Client client = ClientBuilder.newClient();
|
||||
return client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.request()
|
||||
.header(headerKey, headerValue)
|
||||
.get();
|
||||
}
|
||||
|
||||
public static Response basicAuthenticationAtClientLevel(String username, String password) {
|
||||
//To simplify we removed de SSL/TLS protection, but it's required to have an encryption
|
||||
// when using basic authentication schema as it's send only on Base64 encoding
|
||||
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
|
||||
Client client = ClientBuilder.newBuilder().register(feature).build();
|
||||
return client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.request()
|
||||
.get();
|
||||
}
|
||||
|
||||
public static Response basicAuthenticationAtRequestLevel(String username, String password) {
|
||||
//To simplify we removed de SSL/TLS protection, but it's required to have an encryption
|
||||
// when using basic authentication schema as it's send only on Base64 encoding
|
||||
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder().build();
|
||||
Client client = ClientBuilder.newBuilder().register(feature).build();
|
||||
return client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.request()
|
||||
.property(HTTP_AUTHENTICATION_BASIC_USERNAME, username)
|
||||
.property(HTTP_AUTHENTICATION_BASIC_PASSWORD, password)
|
||||
.get();
|
||||
}
|
||||
|
||||
public static Response digestAuthenticationAtClientLevel(String username, String password) {
|
||||
HttpAuthenticationFeature feature = HttpAuthenticationFeature.digest(username, password);
|
||||
Client client = ClientBuilder.newBuilder().register(feature).build();
|
||||
return client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.path(RESOURCE_AUTH_DIGEST)
|
||||
.request()
|
||||
.get();
|
||||
}
|
||||
|
||||
public static Response digestAuthenticationAtRequestLevel(String username, String password) {
|
||||
HttpAuthenticationFeature feature = HttpAuthenticationFeature.digest();
|
||||
|
||||
Client client = ClientBuilder.newBuilder().register(feature).build();
|
||||
return client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.path(RESOURCE_AUTH_DIGEST)
|
||||
.request()
|
||||
.property(HTTP_AUTHENTICATION_DIGEST_USERNAME, username)
|
||||
.property(HTTP_AUTHENTICATION_DIGEST_PASSWORD, password)
|
||||
.get();
|
||||
}
|
||||
|
||||
public static Response bearerAuthenticationWithOAuth1AtClientLevel(String token, String consumerKey) {
|
||||
ConsumerCredentials consumerCredential = new ConsumerCredentials(consumerKey, BEARER_CONSUMER_SECRET);
|
||||
AccessToken accessToken = new AccessToken(token, BEARER_ACCESS_TOKEN_SECRET);
|
||||
Feature feature = OAuth1ClientSupport
|
||||
.builder(consumerCredential)
|
||||
.feature()
|
||||
.accessToken(accessToken)
|
||||
.build();
|
||||
|
||||
Client client = ClientBuilder.newBuilder().register(feature).build();
|
||||
return client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.request()
|
||||
.get();
|
||||
}
|
||||
|
||||
public static Response bearerAuthenticationWithOAuth1AtRequestLevel(String token, String consumerKey) {
|
||||
ConsumerCredentials consumerCredential = new ConsumerCredentials(consumerKey, BEARER_CONSUMER_SECRET);
|
||||
AccessToken accessToken = new AccessToken(token, BEARER_ACCESS_TOKEN_SECRET);
|
||||
Feature feature = OAuth1ClientSupport
|
||||
.builder(consumerCredential)
|
||||
.feature()
|
||||
.build();
|
||||
|
||||
Client client = ClientBuilder.newBuilder().register(feature).build();
|
||||
return client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.request()
|
||||
.property(OAuth1ClientSupport.OAUTH_PROPERTY_ACCESS_TOKEN, accessToken)
|
||||
.get();
|
||||
}
|
||||
|
||||
public static Response bearerAuthenticationWithOAuth2AtClientLevel(String token) {
|
||||
Feature feature = OAuth2ClientSupport.feature(token);
|
||||
|
||||
Client client = ClientBuilder.newBuilder().register(feature).build();
|
||||
return client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.request()
|
||||
.get();
|
||||
}
|
||||
|
||||
public static Response bearerAuthenticationWithOAuth2AtRequestLevel(String token, String otherToken) {
|
||||
Feature feature = OAuth2ClientSupport.feature(token);
|
||||
|
||||
Client client = ClientBuilder.newBuilder().register(feature).build();
|
||||
return client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.request()
|
||||
.property(OAuth2ClientSupport.OAUTH2_PROPERTY_ACCESS_TOKEN, otherToken)
|
||||
.get();
|
||||
}
|
||||
|
||||
public static Response filter() {
|
||||
Client client = ClientBuilder.newBuilder().register(AddHeaderOnRequestFilter.class).build();
|
||||
return client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.request()
|
||||
.get();
|
||||
}
|
||||
|
||||
public static Response sendRestrictedHeaderThroughDefaultTransportConnector(String headerKey, String headerValue) {
|
||||
Client client = ClientBuilder.newClient();
|
||||
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
|
||||
|
||||
return client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.request()
|
||||
.header(headerKey, headerValue)
|
||||
.get();
|
||||
}
|
||||
|
||||
public static String simpleSSEHeader() throws InterruptedException {
|
||||
Client client = ClientBuilder.newBuilder()
|
||||
.register(AddHeaderOnRequestFilter.class)
|
||||
.build();
|
||||
|
||||
WebTarget webTarget = client.target(TARGET)
|
||||
.path(MAIN_RESOURCE)
|
||||
.path("events");
|
||||
|
||||
SseEventSource sseEventSource = SseEventSource.target(webTarget).build();
|
||||
sseEventSource.register(JerseyClientHeaders::receiveEvent);
|
||||
sseEventSource.open();
|
||||
Thread.sleep(3_000);
|
||||
sseEventSource.close();
|
||||
|
||||
return sseHeaderValue;
|
||||
}
|
||||
|
||||
private static void receiveEvent(InboundSseEvent event) {
|
||||
sseHeaderValue = event.readData();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.jersey.client.filter;
|
||||
|
||||
import javax.ws.rs.client.ClientRequestContext;
|
||||
import javax.ws.rs.client.ClientRequestFilter;
|
||||
import java.io.IOException;
|
||||
|
||||
public class AddHeaderOnRequestFilter implements ClientRequestFilter {
|
||||
|
||||
public static final String FILTER_HEADER_VALUE = "filter-header-value";
|
||||
public static final String FILTER_HEADER_KEY = "x-filter-header";
|
||||
|
||||
@Override
|
||||
public void filter(ClientRequestContext requestContext) throws IOException {
|
||||
requestContext.getHeaders().add(FILTER_HEADER_KEY, FILTER_HEADER_VALUE);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user