Merge branch 'master' of https://github.com/eugenp/tutorials into story/BAEL-7636

This commit is contained in:
Dhawal Kapil 2018-08-19 22:59:08 +05:30
commit 847c9e9edd
205 changed files with 2923 additions and 959 deletions

View File

@ -5,29 +5,37 @@ import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class AvroDeSerealizer {
private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) {
DatumReader<AvroHttpRequest> reader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = null;
try {
decoder = DecoderFactory.get().jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
decoder = DecoderFactory.get()
.jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
return reader.read(null, decoder);
} catch (IOException e) {
return null;
logger.error("Deserialization error" + e.getMessage());
}
return null;
}
public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) {
DatumReader<AvroHttpRequest> employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
Decoder decoder = DecoderFactory.get()
.binaryDecoder(data, null);
try {
return employeeReader.read(null, decoder);
} catch (IOException e) {
logger.error("Deserialization error" + e.getMessage());
}
return null;
}
}
}

View File

@ -3,24 +3,29 @@ package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class AvroSerealizer {
private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) {
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = null;
try {
jsonEncoder = EncoderFactory.get().jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
jsonEncoder = EncoderFactory.get()
.jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
data =null;
logger.error("Serialization error " + e.getMessage());
}
return data;
}
@ -29,13 +34,14 @@ public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request){
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = EncoderFactory.get().binaryEncoder(stream,null);
Encoder jsonEncoder = EncoderFactory.get()
.binaryEncoder(stream, null);
try {
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
data = null;
logger.error("Serialization error " + e.getMessage());
}
return data;

View File

@ -24,8 +24,10 @@ public class AvroSerealizerDeSerealizerTest {
serealizer = new AvroSerealizer();
deSerealizer = new AvroDeSerealizer();
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder().
setHostName("localhost").setIpAddress("255.255.255.0").build();
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder()
.setHostName("localhost")
.setIpAddress("255.255.255.0")
.build();
List<CharSequence> employees = new ArrayList();
employees.add("James");
@ -33,9 +35,12 @@ public class AvroSerealizerDeSerealizerTest {
employees.add("David");
employees.add("Han");
request = AvroHttpRequest.newBuilder().setRequestTime(01l)
.setActive(Active.YES).setClientIdentifier(clientIdentifier)
.setEmployeeNames(employees).build();
request = AvroHttpRequest.newBuilder()
.setRequestTime(01l)
.setActive(Active.YES)
.setClientIdentifier(clientIdentifier)
.setEmployeeNames(employees)
.build();
}
@After
@ -43,33 +48,36 @@ public class AvroSerealizerDeSerealizerTest {
}
@Test
public void WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){
public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() {
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){
public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() {
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){
public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() {
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
assertEquals(actualRequest, request);
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
assertTrue(actualRequest.getRequestTime()
.equals(request.getRequestTime()));
}
@Test
public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){
public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() {
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
assertEquals(actualRequest, request);
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
}
assertTrue(actualRequest.getRequestTime()
.equals(request.getRequestTime()));
}
}

View File

@ -137,7 +137,7 @@
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
<gson.version>2.8.0</gson.version>
<aws-java-sdk.version>1.11.290</aws-java-sdk.version>
<mockito-core.version>2.8.9</mockito-core.version>
<mockito-core.version>2.21.0</mockito-core.version>
<assertj-core.version>3.8.0</assertj-core.version>
<dynamodblocal.version>1.11.86</dynamodblocal.version>
<dynamodblocal.repository.url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</dynamodblocal.repository.url>

View File

@ -14,7 +14,6 @@
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams)
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
@ -34,13 +33,11 @@
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
@ -54,7 +51,6 @@
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)

View File

@ -17,7 +17,6 @@
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)

View File

@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
@ -48,4 +49,14 @@ public class RemoveFirstElementUnitTest {
assertThat(linkedList, not(contains("cat")));
}
@Test
public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
String[] stringArray = {"foo", "bar", "baz"};
String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
assertThat(modifiedArray.length, is(2));
assertThat(modifiedArray[0], is("bar"));
}
}

View File

@ -0,0 +1,26 @@
package org.baeldung.java.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
class CollectionsEmpty {
@Test
public void givenArrayList_whenAddingElement_addsNewElement() {
ArrayList<String> mutableList = new ArrayList<>();
mutableList.add("test");
Assert.assertEquals(mutableList.size(), 1);
Assert.assertEquals(mutableList.get(0), "test");
}
@Test(expected = UnsupportedOperationException.class)
public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() {
List<String> immutableList = Collections.emptyList();
immutableList.add("test");
}
}

View File

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

View File

@ -0,0 +1,15 @@
=========
## Core Java Concurrency Collections Examples
### Relevant Articles:
- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map)
- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue)
- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception)
- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)

View File

@ -0,0 +1,94 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-concurrency-collections</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-concurrency-collections</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-concurrency-collections</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<!-- util -->
<guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-math3.version>3.6.1</commons-math3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
</properties>
</project>

View File

@ -10,15 +10,18 @@ public class BlockingQueueUsage {
int N_CONSUMERS = Runtime.getRuntime().availableProcessors();
int poisonPill = Integer.MAX_VALUE;
int poisonPillPerProducer = N_CONSUMERS / N_PRODUCERS;
int mod = N_CONSUMERS % N_PRODUCERS;
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(BOUND);
for (int i = 0; i < N_PRODUCERS; i++) {
for (int i = 1; i < N_PRODUCERS; i++) {
new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer)).start();
}
for (int j = 0; j < N_CONSUMERS; j++) {
new Thread(new NumbersConsumer(queue, poisonPill)).start();
}
new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer+mod)).start();
}
}

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -7,22 +7,12 @@
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future)
- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)
- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map)
- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue)
- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception)
- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks)
- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal)
- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
- [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers)
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
- [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables)

View File

@ -0,0 +1,8 @@
=========
## Core Java Persistence Examples
### Relevant Articles:
- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)

View File

@ -3,18 +3,14 @@
## Core Java Cookbooks and Examples
### Relevant Articles:
- [Java Generate Random String](http://www.baeldung.com/java-random-string)
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [Java Try with Resources](http://www.baeldung.com/java-try-with-resources)
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
- [Introduction to Java Generics](http://www.baeldung.com/java-generics)
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
@ -37,8 +33,6 @@
- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng)
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
@ -53,36 +47,28 @@
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string)
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
- [Split a String in Java](http://www.baeldung.com/java-split-string)
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
@ -90,7 +76,6 @@
- [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree)
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions)
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
- [Nested Classes in Java](http://www.baeldung.com/java-nested-classes)
- [A Guide to Java Loops](http://www.baeldung.com/java-loops)
- [Varargs in Java](http://www.baeldung.com/java-varargs)
@ -105,15 +90,12 @@
- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
- [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy)
- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
@ -139,11 +121,9 @@
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
- [Using Java Assertions](http://www.baeldung.com/java-assert)
- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding)
- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers)
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
- [Singletons in Java](http://www.baeldung.com/java-singleton)
@ -157,7 +137,6 @@
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day)
- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time)
- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case)
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object)
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
@ -171,3 +150,4 @@
- [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation)
- [Getting a Files Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods)

View File

@ -137,11 +137,6 @@
<artifactId>mail</artifactId>
<version>${javax.mail.version}</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>${icu4j.version}</version>
</dependency>
<!-- Mime Type Resolution Libraries -->
<dependency>
<groupId>org.apache.tika</groupId>

View File

@ -0,0 +1,12 @@
package com.baeldung.constructorsstaticfactorymethods.application;
import com.baeldung.constructorsstaticfactorymethods.entities.User;
public class Application {
public static void main(String[] args) {
User user1 = User.createWithDefaultCountry("John", "john@domain.com");
User user2 = User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina");
User user3 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.constructorsstaticfactorymethods.entities;
import java.time.LocalTime;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class User {
private static volatile User instance = null;
private static final Logger LOGGER = Logger.getLogger(User.class.getName());
private final String name;
private final String email;
private final String country;
public static User createWithDefaultCountry(String name, String email) {
return new User(name, email, "Argentina");
}
public static User createWithLoggedInstantiationTime(String name, String email, String country) {
setLoggerProperties();
LOGGER.log(Level.INFO, "Creating User instance at : {0}", LocalTime.now());
return new User(name, email, country);
}
public static User getSingletonInstance(String name, String email, String country) {
if (instance == null) {
synchronized (User.class) {
if (instance == null) {
instance = new User(name, email, country);
}
}
}
return instance;
}
private User(String name, String email, String country) {
this.name = name;
this.email = email;
this.country = country;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getCountry() {
return country;
}
private static void setLoggerProperties() {
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.INFO);
handler.setFormatter(new SimpleFormatter());
LOGGER.addHandler(handler);
}
}

View File

@ -25,7 +25,11 @@ public class Exceptions {
}
public List<Player> loadAllPlayers(String playersFile) throws IOException{
try {
throw new IOException();
} catch(IOException ex) {
throw new IllegalStateException();
}
}
public int getPlayerScoreThrows(String playerFile) throws FileNotFoundException {
@ -160,7 +164,13 @@ public class Exceptions {
}
public void throwAsGotoAntiPattern() throws MyException {
try {
// bunch of code
throw new MyException();
// second bunch of code
} catch ( MyException e ) {
// third bunch of code
}
}
public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) {

View File

@ -25,7 +25,7 @@ public class User {
if (this.getClass() != o.getClass())
return false;
User user = (User) o;
return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
return id == user.id && (name.equals(user.name) && email.equals(user.email));
}
@Override
@ -38,4 +38,5 @@ public class User {
return hash;
}
// getters and setters here
}

View File

@ -1,42 +0,0 @@
package com.baeldung.array;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class RemoveFirstElementUnitTest {
@Test
public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
String[] stringArray = {"foo", "bar", "baz"};
String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
assertThat(modifiedArray.length).isEqualTo(2);
assertThat(modifiedArray[0]).isEqualTo("bar");
}
@Test
public void givenArrayList_whenRemovingFirstElement_thenListSmallerAndElementRemoved() {
List<String> stringList = new ArrayList<>(Arrays.asList("foo", "bar", "baz"));
stringList.remove(0);
assertThat(stringList.size()).isEqualTo(2);
assertThat(stringList.get(0)).isEqualTo("bar");
}
@Test
public void givenLinkedList_whenRemovingFirstElement_thenListSmallerAndElementRemoved() {
List<String> stringList = new LinkedList<>(Arrays.asList("foo", "bar", "baz"));
stringList.remove(0);
assertThat(stringList.size()).isEqualTo(2);
assertThat(stringList.get(0)).isEqualTo("bar");
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.constructorsstaticfactorymethods;
import com.baeldung.constructorsstaticfactorymethods.entities.User;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class UserUnitTest {
@Test
public void givenUserClass_whenCalledcreateWithDefaultCountry_thenCorrect() {
assertThat(User.createWithDefaultCountry("John", "john@domain.com")).isInstanceOf(User.class);
}
@Test
public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetName_thenCorrect() {
User user = User.createWithDefaultCountry("John", "john@domain.com");
assertThat(user.getName()).isEqualTo("John");
}
@Test
public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetEmail_thenCorrect() {
User user = User.createWithDefaultCountry("John", "john@domain.com");
assertThat(user.getEmail()).isEqualTo("john@domain.com");
}
@Test
public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetCountry_thenCorrect() {
User user = User.createWithDefaultCountry("John", "john@domain.com");
assertThat(user.getCountry()).isEqualTo("Argentina");
}
@Test
public void givenUserInstanceCreatedWithcreateWithInstantiationTime_whenCalledcreateWithInstantiationTime_thenCorrect() {
assertThat(User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina")).isInstanceOf(User.class);
}
@Test
public void givenUserInstanceCreatedWithgetSingletonIntance_whenCalledgetSingletonInstance_thenCorrect() {
User user1 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
User user2 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
assertThat(user1).isEqualTo(user2);
}
}

View File

@ -76,25 +76,4 @@ public class PizzaUnitTest {
pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
}
@Test
public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {
String pizzaEnumValue = "READY";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
}
@Test(expected = IllegalArgumentException.class)
public void whenConvertedIntoEnum_thenThrowsException() {
String pizzaEnumValue = "rEAdY";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
}
@Test(expected = IllegalArgumentException.class)
public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() {
String pizzaEnumValue = "invalid";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
}
}

View File

@ -21,7 +21,7 @@ public class ExceptionsUnitTest {
@Test
public void loadAllPlayers() {
assertThatThrownBy(() -> exceptions.loadAllPlayers(""))
.isInstanceOf(IOException.class);
.isInstanceOf(IllegalStateException.class);
}
@Test
@ -72,12 +72,6 @@ public class ExceptionsUnitTest {
.isInstanceOf(NullPointerException.class);
}
@Test
public void throwAsGotoAntiPattern() {
assertThatThrownBy(() -> exceptions.throwAsGotoAntiPattern())
.isInstanceOf(MyException.class);
}
@Test
public void getPlayerScoreSwallowingExceptionAntiPatternAlternative2() {
assertThatThrownBy(() -> exceptions.getPlayerScoreSwallowingExceptionAntiPatternAlternative2(""))

View File

@ -1,81 +0,0 @@
package org.baeldung.java.enums;
import static junit.framework.TestCase.assertTrue;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import org.junit.Test;
import com.baeldung.enums.Pizza;
public class PizzaUnitTest {
@Test
public void givenPizaOrder_whenReady_thenDeliverable() {
Pizza testPz = new Pizza();
testPz.setStatus(Pizza.PizzaStatusEnum.READY);
assertTrue(testPz.isDeliverable());
}
@Test
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
List<Pizza> pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
Pizza pz2 = new Pizza();
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz3 = new Pizza();
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz4 = new Pizza();
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
pzList.add(pz1);
pzList.add(pz2);
pzList.add(pz3);
pzList.add(pz4);
List<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
assertTrue(undeliveredPzs.size() == 3);
}
@Test
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
List<Pizza> pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
Pizza pz2 = new Pizza();
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz3 = new Pizza();
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz4 = new Pizza();
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
pzList.add(pz1);
pzList.add(pz2);
pzList.add(pz3);
pzList.add(pz4);
EnumMap<Pizza.PizzaStatusEnum, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
}
@Test
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
Pizza pz = new Pizza();
pz.setStatus(Pizza.PizzaStatusEnum.READY);
pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
}
}

View File

@ -1,39 +1,22 @@
package com.baeldung.builder
class FoodOrder private constructor(builder: FoodOrder.Builder) {
val bread: String?
val condiments: String?
val meat: String?
class FoodOrder(
val bread: String?,
val condiments: String?,
val meat: String?,
val fish: String?
init {
this.bread = builder.bread
this.condiments = builder.condiments
this.meat = builder.meat
this.fish = builder.fish
}
class Builder {
var bread: String? = null
private set
var condiments: String? = null
private set
var meat: String? = null
private set
var fish: String? = null
private set
) {
data class Builder(
var bread: String? = null,
var condiments: String? = null,
var meat: String? = null,
var fish: String? = null) {
fun bread(bread: String) = apply { this.bread = bread }
fun condiments(condiments: String) = apply { this.condiments = condiments }
fun meat(meat: String) = apply { this.meat = meat }
fun fish(fish: String) = apply { this.fish = fish }
fun build() = FoodOrder(this)
fun build() = FoodOrder(bread, condiments, meat, fish)
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.builder
fun main(args: Array<String>) {
FoodOrder.Builder()
.bread("bread")
.condiments("condiments")
.meat("meat")
.fish("bread").let { println(it) }
}

View File

@ -103,7 +103,7 @@ class CoroutinesTest {
//given
val job = launch(CommonPool) {
while (isActive) {
println("is working")
//println("is working")
}
}

View File

@ -0,0 +1,55 @@
import org.junit.jupiter.api.Test
import java.util.concurrent.ThreadLocalRandom
import kotlin.test.assertTrue
class RandomNumberTest {
@Test
fun whenRandomNumberWithJavaUtilMath_thenResultIsBetween0And1() {
val randomNumber = Math.random()
assertTrue { randomNumber >=0 }
assertTrue { randomNumber <= 1 }
}
@Test
fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInDefaultRanges() {
val randomDouble = ThreadLocalRandom.current().nextDouble()
val randomInteger = ThreadLocalRandom.current().nextInt()
val randomLong = ThreadLocalRandom.current().nextLong()
assertTrue { randomDouble >= 0 }
assertTrue { randomDouble <= 1 }
assertTrue { randomInteger >= Integer.MIN_VALUE }
assertTrue { randomInteger <= Integer.MAX_VALUE }
assertTrue { randomLong >= Long.MIN_VALUE }
assertTrue { randomLong <= Long.MAX_VALUE }
}
@Test
fun whenRandomNumberWithKotlinJSMath_thenResultIsBetween0And1() {
val randomDouble = Math.random()
assertTrue { randomDouble >=0 }
assertTrue { randomDouble <= 1 }
}
@Test
fun whenRandomNumberWithKotlinNumberRange_thenResultInGivenRange() {
val randomInteger = (1..12).shuffled().first()
assertTrue { randomInteger >= 1 }
assertTrue { randomInteger <= 12 }
}
@Test
fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInGivenRanges() {
val randomDouble = ThreadLocalRandom.current().nextDouble(1.0, 10.0)
val randomInteger = ThreadLocalRandom.current().nextInt(1, 10)
val randomLong = ThreadLocalRandom.current().nextLong(1, 10)
assertTrue { randomDouble >= 1 }
assertTrue { randomDouble <= 10 }
assertTrue { randomInteger >= 1 }
assertTrue { randomInteger <= 10 }
assertTrue { randomLong >= 1 }
assertTrue { randomLong <= 10 }
}
}

View File

@ -214,7 +214,7 @@
<web3j.core.version>3.3.1</web3j.core.version>
<springframework.version>5.0.5.RELEASE</springframework.version>
<spring.boot.version>1.5.6.RELEASE</spring.boot.version>
<mockito.version>1.10.19</mockito.version>
<mockito.version>2.21.0</mockito.version>
<jackson-databind.version>2.5.0</jackson-databind.version>
<hamcrest.version>1.3</hamcrest.version>
<jackson.version>2.9.3</jackson.version>

14
guest/core-kotlin/.gitignore vendored Normal file
View File

@ -0,0 +1,14 @@
/bin/
#ignore gradle
.gradle/
#ignore build and generated files
build/
node/
out/
#ignore installed node modules and package lock file
node_modules/
package-lock.json

199
guest/core-kotlin/pom.xml Normal file
View File

@ -0,0 +1,199 @@
<?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>
<artifactId>core-kotlin</artifactId>
<version>1.0-SNAPSHOT</version>
<groupId>com.stackify</groupId>
<packaging>jar</packaging>
<repositories>
<repository>
<id>jcenter</id>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin-stdlib.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin-stdlib.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test-junit</artifactId>
<version>${kotlin-test-junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${kotlin-reflect.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-api</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-subject-extension</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-junit-platform-engine</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.nhaarman</groupId>
<artifactId>mockito-kotlin</artifactId>
<version>${mockito-kotlin.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin-maven-plugin.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin-maven-plugin.version}</version>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
<executions>
<!-- Replacing default-compile as it is treated specially
by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially
by maven -->
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>junit5</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*Test5.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<maven-failsafe-plugin.version>2.22.0</maven-failsafe-plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kotlin-maven-plugin.version>1.2.60</kotlin-maven-plugin.version>
<kotlin-test-junit.version>1.2.51</kotlin-test-junit.version>
<kotlin-stdlib.version>1.2.51</kotlin-stdlib.version>
<kotlin-reflect.version>1.2.51</kotlin-reflect.version>
<kotlinx.version>0.22.5</kotlinx.version>
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
<commons-math3.version>3.6.1</commons-math3.version>
<junit.platform.version>1.0.0</junit.platform.version>
<junit.vintage.version>5.2.0</junit.vintage.version>
<assertj.version>3.10.0</assertj.version>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -24,7 +24,7 @@ class ExceptionsTest {
fun givenANullString_whenUsingElvisOperator_thenExceptionIsThrown() {
val sampleString: String? = null
val length: Int = sampleString?.length ?: throw IllegalArgumentException("String must not be null")
sampleString?.length ?: throw IllegalArgumentException("String must not be null")
}
private fun funThrowingException(): Nothing {

27
java-strings/README.md Normal file
View File

@ -0,0 +1,27 @@
=========
## Java Strings Cookbooks and Examples
### Relevant Articles:
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
- [Java Generate Random String](http://www.baeldung.com/java-random-string)
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
- [Split a String in Java](http://www.baeldung.com/java-split-string)
- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case)
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)

107
java-strings/pom.xml Normal file
View File

@ -0,0 +1,107 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>java-strings</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>java-strings</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>${icu4j.version}</version>
</dependency>
</dependencies>
<build>
<finalName>java-strings</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<commons-codec.version>1.10</commons-codec.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<jmh-core.version>1.19</jmh-core.version>
<icu4j.version>61.1</icu4j.version>
</properties>
</project>

View File

@ -0,0 +1,44 @@
package com.baeldung.enums;
public enum PizzaStatusEnum {
ORDERED(5) {
@Override
public boolean isOrdered() {
return true;
}
},
READY(2) {
@Override
public boolean isReady() {
return true;
}
},
DELIVERED(0) {
@Override
public boolean isDelivered() {
return true;
}
};
private int timeToDelivery;
public boolean isOrdered() {
return false;
}
public boolean isReady() {
return false;
}
public boolean isDelivered() {
return false;
}
public int getTimeToDelivery() {
return timeToDelivery;
}
PizzaStatusEnum(int timeToDelivery) {
this.timeToDelivery = timeToDelivery;
}
}

View File

@ -1,12 +1,13 @@
package com.baeldung.string;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.BreakIterator;
import org.apache.commons.lang.WordUtils;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.apache.commons.lang3.text.WordUtils;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.BreakIterator;
public class TitleCaseConverter {
private static final String WORD_SEPARATOR = " ";

View File

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

View File

@ -0,0 +1,27 @@
package com.baeldung.enums;
import static junit.framework.TestCase.assertTrue;
import org.junit.Test;
public class PizzaUnitTest {
@Test
public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {
String pizzaEnumValue = "READY";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
}
@Test(expected = IllegalArgumentException.class)
public void whenConvertedIntoEnum_thenThrowsException() {
String pizzaEnumValue = "rEAdY";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
}
@Test(expected = IllegalArgumentException.class)
public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() {
String pizzaEnumValue = "invalid";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
}
}

View File

@ -1,13 +1,14 @@
package com.baeldung.java.countingChars;
import com.google.common.base.CharMatcher;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import com.google.common.base.CharMatcher;
/***

View File

@ -1,12 +1,13 @@
package com.baeldung.string;
import com.google.common.base.Splitter;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import com.google.common.base.Splitter;
public class SplitUnitTest {

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