Merge branch 'master' into master
This commit is contained in:
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.concurrent.diningphilosophers;
|
||||
|
||||
public class DiningPhilosophers {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
Philosopher[] philosophers = new Philosopher[5];
|
||||
Object[] forks = new Object[philosophers.length];
|
||||
|
||||
for (int i = 0; i < forks.length; i++) {
|
||||
forks[i] = new Object();
|
||||
}
|
||||
|
||||
for (int i = 0; i < philosophers.length; i++) {
|
||||
|
||||
Object leftFork = forks[i];
|
||||
Object rightFork = forks[(i + 1) % forks.length];
|
||||
|
||||
if (i == philosophers.length - 1) {
|
||||
philosophers[i] = new Philosopher(rightFork, leftFork); // The last philosopher picks up the right fork first
|
||||
} else {
|
||||
philosophers[i] = new Philosopher(leftFork, rightFork);
|
||||
}
|
||||
|
||||
Thread t = new Thread(philosophers[i], "Philosopher " + (i + 1));
|
||||
t.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.concurrent.diningphilosophers;
|
||||
|
||||
public class Philosopher implements Runnable {
|
||||
|
||||
private final Object leftFork;
|
||||
private final Object rightFork;
|
||||
|
||||
public Philosopher(Object left, Object right) {
|
||||
this.leftFork = left;
|
||||
this.rightFork = right;
|
||||
}
|
||||
|
||||
private void doAction(String action) throws InterruptedException {
|
||||
System.out.println(Thread.currentThread().getName() + " " + action);
|
||||
Thread.sleep(((int) (Math.random() * 100)));
|
||||
}
|
||||
|
||||
@Override public void run() {
|
||||
try {
|
||||
while (true) {
|
||||
doAction(System.nanoTime() + ": Thinking"); // thinking
|
||||
synchronized (leftFork) {
|
||||
doAction(System.nanoTime() + ": Picked up left fork");
|
||||
synchronized (rightFork) {
|
||||
doAction(System.nanoTime() + ": Picked up right fork - eating"); // eating
|
||||
doAction(System.nanoTime() + ": Put down right fork");
|
||||
}
|
||||
doAction(System.nanoTime() + ": Put down left fork. Returning to thinking");
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.java.enumiteration;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public enum DaysOfWeekEnum {
|
||||
SUNDAY("off"),
|
||||
MONDAY("working"),
|
||||
TUESDAY("working"),
|
||||
WEDNESDAY("working"),
|
||||
THURSDAY("working"),
|
||||
FRIDAY("working"),
|
||||
SATURDAY("off");
|
||||
|
||||
private String typeOfDay;
|
||||
|
||||
DaysOfWeekEnum(String typeOfDay) {
|
||||
this.typeOfDay = typeOfDay;
|
||||
}
|
||||
|
||||
public String getTypeOfDay() {
|
||||
return typeOfDay;
|
||||
}
|
||||
|
||||
public void setTypeOfDay(String typeOfDay) {
|
||||
this.typeOfDay = typeOfDay;
|
||||
}
|
||||
|
||||
public static Stream<DaysOfWeekEnum> stream() {
|
||||
return Stream.of(DaysOfWeekEnum.values());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.java.enumiteration;
|
||||
|
||||
import java.util.EnumSet;
|
||||
|
||||
public class EnumIterationExamples {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Enum iteration using forEach:");
|
||||
EnumSet.allOf(DaysOfWeekEnum.class).forEach(day -> System.out.println(day));
|
||||
|
||||
System.out.println("Enum iteration using Stream:");
|
||||
DaysOfWeekEnum.stream().filter(d -> d.getTypeOfDay().equals("off")).forEach(System.out::println);
|
||||
|
||||
System.out.println("Enum iteration using for loop:");
|
||||
for (DaysOfWeekEnum day : DaysOfWeekEnum.values()) {
|
||||
System.out.println(day);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ public class Round {
|
||||
|
||||
public static double roundNotPrecise(double value, int places) {
|
||||
if (places < 0) throw new IllegalArgumentException();
|
||||
|
||||
|
||||
BigDecimal bd = new BigDecimal(value);
|
||||
bd = bd.setScale(places, RoundingMode.HALF_UP);
|
||||
return bd.doubleValue();
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.noclassdeffounderror;
|
||||
|
||||
public class ClassWithInitErrors {
|
||||
static int data = 1 / 0;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.noclassdeffounderror;
|
||||
|
||||
public class NoClassDefFoundErrorExample {
|
||||
public ClassWithInitErrors getClassWithInitErrors() {
|
||||
ClassWithInitErrors test;
|
||||
try {
|
||||
test = new ClassWithInitErrors();
|
||||
} catch (Throwable t) {
|
||||
System.out.println(t);
|
||||
}
|
||||
test = new ClassWithInitErrors();
|
||||
return test;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class StreamApi {
|
||||
|
||||
public String getLastElementUsingReduce(List<String> valueList) {
|
||||
Stream<String> stream = valueList.stream();
|
||||
return stream.reduce((first, second) -> second).orElse(null);
|
||||
}
|
||||
|
||||
public Integer getInfiniteStreamLastElementUsingReduce() {
|
||||
Stream<Integer> stream = Stream.iterate(0, i -> i + 1);
|
||||
return stream.limit(20).reduce((first, second) -> second).orElse(null);
|
||||
}
|
||||
|
||||
public String getLastElementUsingSkip(List<String> valueList) {
|
||||
long count = valueList.stream().count();
|
||||
Stream<String> stream = valueList.stream();
|
||||
return stream.skip(count - 1).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,23 +2,23 @@ package com.baeldung.string;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class StringHelper {
|
||||
public static String removeLastChar(String s) {
|
||||
class StringHelper {
|
||||
static String removeLastChar(String s) {
|
||||
return (s == null || s.length() == 0) ? s : (s.substring(0, s.length() - 1));
|
||||
}
|
||||
|
||||
public static String removeLastCharRegex(String s) {
|
||||
static String removeLastCharRegex(String s) {
|
||||
return (s == null) ? s : s.replaceAll(".$", "");
|
||||
}
|
||||
|
||||
public static String removeLastCharOptional(String s) {
|
||||
static String removeLastCharOptional(String s) {
|
||||
return Optional.ofNullable(s)
|
||||
.filter(str -> str.length() != 0)
|
||||
.map(str -> str.substring(0, str.length() - 1))
|
||||
.orElse(s);
|
||||
}
|
||||
|
||||
public static String removeLastCharRegexOptional(String s) {
|
||||
static String removeLastCharRegexOptional(String s) {
|
||||
return Optional.ofNullable(s)
|
||||
.map(str -> str.replaceAll(".$", ""))
|
||||
.orElse(s);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.uuid;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDGenerator {
|
||||
|
||||
/**
|
||||
* These are predefined UUID for name spaces
|
||||
*/
|
||||
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
|
||||
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
|
||||
|
||||
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
System.out.println("Type 3 : " + generateType3UUID(NAMESPACE_DNS, "google.com"));
|
||||
System.out.println("Type 4 : " + generateType4UUID());
|
||||
System.out.println("Type 5 : " + generateType5UUID(NAMESPACE_URL, "google.com"));
|
||||
System.out.println("Unique key : " + generateUniqueKeysWithUUIDAndMessageDigest());
|
||||
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Type 4 UUID Generation
|
||||
*/
|
||||
public static UUID generateType4UUID() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type 3 UUID Generation
|
||||
*
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static UUID generateType3UUID(String namespace, String name) throws UnsupportedEncodingException {
|
||||
String source = namespace + name;
|
||||
byte[] bytes = source.getBytes("UTF-8");
|
||||
UUID uuid = UUID.nameUUIDFromBytes(bytes);
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type 5 UUID Generation
|
||||
*
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static UUID generateType5UUID(String namespace, String name) throws UnsupportedEncodingException {
|
||||
String source = namespace + name;
|
||||
byte[] bytes = source.getBytes("UTF-8");
|
||||
UUID uuid = type5UUIDFromBytes(bytes);
|
||||
return uuid;
|
||||
}
|
||||
|
||||
|
||||
public static UUID type5UUIDFromBytes(byte[] name) {
|
||||
MessageDigest md;
|
||||
try {
|
||||
md = MessageDigest.getInstance("SHA-1");
|
||||
} catch (NoSuchAlgorithmException nsae) {
|
||||
throw new InternalError("MD5 not supported", nsae);
|
||||
}
|
||||
byte[] bytes = md.digest(name);
|
||||
bytes[6] &= 0x0f; /* clear version */
|
||||
bytes[6] |= 0x50; /* set to version 5 */
|
||||
bytes[8] &= 0x3f; /* clear variant */
|
||||
bytes[8] |= 0x80; /* set to IETF variant */
|
||||
return constructType5UUID(bytes);
|
||||
}
|
||||
|
||||
private static UUID constructType5UUID(byte[] data) {
|
||||
long msb = 0;
|
||||
long lsb = 0;
|
||||
assert data.length == 16 : "data must be 16 bytes in length";
|
||||
|
||||
for (int i=0; i<8; i++)
|
||||
msb = (msb << 8) | (data[i] & 0xff);
|
||||
|
||||
for (int i=8; i<16; i++)
|
||||
lsb = (lsb << 8) | (data[i] & 0xff);
|
||||
return new UUID(msb, lsb);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Unique Keys Generation Using Message Digest and Type 4 UUID
|
||||
*
|
||||
* @throws NoSuchAlgorithmException
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static String generateUniqueKeysWithUUIDAndMessageDigest() throws NoSuchAlgorithmException, UnsupportedEncodingException {
|
||||
MessageDigest salt = MessageDigest.getInstance("SHA-256");
|
||||
salt.update(UUID.randomUUID()
|
||||
.toString()
|
||||
.getBytes("UTF-8"));
|
||||
String digest = bytesToHex(salt.digest());
|
||||
return digest;
|
||||
}
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
char[] hexChars = new char[bytes.length * 2];
|
||||
for (int j = 0; j < bytes.length; j++) {
|
||||
int v = bytes[j] & 0xFF;
|
||||
hexChars[j * 2] = hexArray[v >>> 4];
|
||||
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
|
||||
}
|
||||
return new String(hexChars);
|
||||
}
|
||||
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.classnotfoundexception;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ClassNotFoundExceptionTest {
|
||||
|
||||
@Test(expected = ClassNotFoundException.class)
|
||||
public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException {
|
||||
Class.forName("oracle.jdbc.driver.OracleDriver");
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.noclassdeffounderror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class NoClassDefFoundErrorTest {
|
||||
|
||||
@Test(expected = NoClassDefFoundError.class)
|
||||
public void givenInitErrorInClass_whenloadClass_thenNoClassDefFoundError() {
|
||||
NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample();
|
||||
sample.getClassWithInitErrors();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.regexp;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class EscapingCharsTest {
|
||||
@Test
|
||||
public void givenRegexWithDot_whenMatchingStr_thenMatches() {
|
||||
String strInput = "foof";
|
||||
String strRegex = "foo.";
|
||||
|
||||
assertEquals(true, strInput.matches(strRegex));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDotEsc_whenMatchingStr_thenNotMatching() {
|
||||
String strInput = "foof";
|
||||
String strRegex = "foo\\.";
|
||||
|
||||
assertEquals(false, strInput.matches(strRegex));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithPipeEscaped_whenSplitStr_thenSplits() {
|
||||
String strInput = "foo|bar|hello|world";
|
||||
String strRegex = "\\Q|\\E";
|
||||
|
||||
assertEquals(4, strInput.split(strRegex).length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithPipeEscQuoteMeth_whenSplitStr_thenSplits() {
|
||||
String strInput = "foo|bar|hello|world";
|
||||
String strRegex = "|";
|
||||
|
||||
assertEquals(4,strInput.split(Pattern.quote(strRegex)).length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDollar_whenReplacing_thenNotReplace() {
|
||||
String strInput = "I gave $50 to my brother."
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
String strRegex = "$";
|
||||
String strReplacement = "£";
|
||||
String output = "I gave £50 to my brother."
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
Pattern p = Pattern.compile(strRegex);
|
||||
Matcher m = p.matcher(strInput);
|
||||
|
||||
assertThat(output, not(equalTo(m.replaceAll(strReplacement))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDollarEsc_whenReplacing_thenReplace() {
|
||||
String strInput = "I gave $50 to my brother."
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
String strRegex = "\\$";
|
||||
String strReplacement = "£";
|
||||
String output = "I gave £50 to my brother."
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
Pattern p = Pattern.compile(strRegex);
|
||||
Matcher m = p.matcher(strInput);
|
||||
|
||||
assertEquals(output,m.replaceAll(strReplacement));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamAddUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStream_whenAppendingObject_thenAppended() {
|
||||
Stream<String> anStream = Stream.of("a", "b", "c", "d", "e");
|
||||
|
||||
Stream<String> newStream = Stream.concat(anStream, Stream.of("A"));
|
||||
|
||||
List<String> resultList = newStream.collect(Collectors.toList());
|
||||
assertEquals(resultList.get(resultList.size() - 1), "A");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenPrependingObject_thenPrepended() {
|
||||
Stream<Integer> anStream = Stream.of(1, 2, 3, 4, 5);
|
||||
|
||||
Stream<Integer> newStream = Stream.concat(Stream.of(99), anStream);
|
||||
|
||||
assertEquals(newStream.findFirst()
|
||||
.get(), (Integer) 99);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenInsertingObject_thenInserted() {
|
||||
Stream<Double> anStream = Stream.of(1.1, 2.2, 3.3);
|
||||
|
||||
Stream<Double> newStream = insertInStream(anStream, 9.9, 3);
|
||||
|
||||
List<Double> resultList = newStream.collect(Collectors.toList());
|
||||
assertEquals(resultList.get(3), (Double) 9.9);
|
||||
}
|
||||
|
||||
public <T> Stream<T> insertInStream(Stream<T> stream, T elem, int index) {
|
||||
List<T> result = stream.collect(Collectors.toList());
|
||||
result.add(index, elem);
|
||||
return result.stream();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamApiTest {
|
||||
private StreamApi streamApi = new StreamApi();
|
||||
|
||||
@Test
|
||||
public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() {
|
||||
List<String> valueList = new ArrayList<String>();
|
||||
valueList.add("Joe");
|
||||
valueList.add("John");
|
||||
valueList.add("Sean");
|
||||
|
||||
String last = streamApi.getLastElementUsingReduce(valueList);
|
||||
|
||||
assertEquals("Sean", last);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() {
|
||||
Integer last = streamApi.getInfiniteStreamLastElementUsingReduce();
|
||||
assertEquals(new Integer(19), last);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() {
|
||||
List<String> valueList = new ArrayList<String>();
|
||||
valueList.add("Joe");
|
||||
valueList.add("John");
|
||||
valueList.add("Sean");
|
||||
|
||||
String last = streamApi.getLastElementUsingSkip(valueList);
|
||||
|
||||
assertEquals("Sean", last);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -167,9 +167,11 @@ public class JavaRandomUnitTest {
|
||||
final int leftLimit = 97; // letter 'a'
|
||||
final int rightLimit = 122; // letter 'z'
|
||||
final int targetStringLength = 10;
|
||||
final Random random = new Random();
|
||||
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||
|
||||
for (int i = 0; i < targetStringLength; i++) {
|
||||
final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit + 1));
|
||||
final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
|
||||
buffer.append((char) randomLimitedInt);
|
||||
}
|
||||
final String generatedString = buffer.toString();
|
||||
|
||||
Reference in New Issue
Block a user