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

This commit is contained in:
amit2103
2019-09-07 19:45:49 +05:30
236 changed files with 5263 additions and 3458 deletions
@@ -0,0 +1,70 @@
package com.baeldung.bucketsort;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class IntegerBucketSorter implements Sorter<Integer> {
private final Comparator<Integer> comparator;
public IntegerBucketSorter(Comparator<Integer> comparator) {
this.comparator = comparator;
}
public IntegerBucketSorter() {
comparator = Comparator.naturalOrder();
}
public List<Integer> sort(List<Integer> arrayToSort) {
List<List<Integer>> buckets = splitIntoUnsortedBuckets(arrayToSort);
for(List<Integer> bucket : buckets){
bucket.sort(comparator);
}
return concatenateSortedBuckets(buckets);
}
private List<Integer> concatenateSortedBuckets(List<List<Integer>> buckets){
List<Integer> sortedArray = new ArrayList<>();
int index = 0;
for(List<Integer> bucket : buckets){
for(int number : bucket){
sortedArray.add(index++, number);
}
}
return sortedArray;
}
private List<List<Integer>> splitIntoUnsortedBuckets(List<Integer> initialList){
final int[] codes = createHashes(initialList);
List<List<Integer>> buckets = new ArrayList<>(codes[1]);
for(int i = 0; i < codes[1]; i++) buckets.add(new ArrayList<>());
//distribute the data
for (int i : initialList) {
buckets.get(hash(i, codes)).add(i);
}
return buckets;
}
private int[] createHashes(List<Integer> input){
int m = input.get(0);
for (int i = 1; i < input.size(); i++) {
if (m < input.get(i)) {
m = input.get(i);
}
}
return new int[]{m, (int) Math.sqrt(input.size())};
}
private static int hash(int i, int[] code) {
return (int) ((double) i / code[0] * (code[1] - 1));
}
}
@@ -0,0 +1,8 @@
package com.baeldung.bucketsort;
import java.util.List;
public interface Sorter<T> {
List<T> sort(List<T> arrayToSort);
}
@@ -0,0 +1,33 @@
package com.baeldung.bucketsort;
import com.baeldung.bucketsort.IntegerBucketSorter;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class IntegerBucketSorterUnitTest {
private IntegerBucketSorter sorter;
@Before
public void setUp() throws Exception {
sorter = new IntegerBucketSorter();
}
@Test
public void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() {
List<Integer> unsorted = Arrays.asList(80,50,60,30,20,10,70,0,40,500,600,602,200,15);
List<Integer> expected = Arrays.asList(0,10,15,20,30,40,50,60,70,80,200,500,600,602);
List<Integer> actual = sorter.sort(unsorted);
assertEquals(expected, actual);
}
}
+3
View File
@@ -0,0 +1,3 @@
## Relevant Articles:
- [Building Java Applications with Bazel](https://www.baeldung.com/bazel-build-tool)
+6
View File
@@ -48,6 +48,11 @@
<version>${spock-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.groovy-wslite</groupId>
<artifactId>groovy-wslite</artifactId>
<version>${groovy-wslite.version}</version>
</dependency>
</dependencies>
<build>
@@ -175,6 +180,7 @@
<junit.platform.version>1.0.0</junit.platform.version>
<hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version>
<groovy-wslite.version>1.1.3</groovy-wslite.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<logback.version>1.2.3</logback.version>
<groovy.version>2.5.7</groovy.version>
@@ -0,0 +1,152 @@
package com.baeldung.webservice
import groovy.json.JsonSlurper
import wslite.rest.ContentType
import wslite.rest.RESTClient
import wslite.rest.RESTClientException
import wslite.soap.SOAPClient
import wslite.soap.SOAPMessageBuilder
import wslite.http.auth.HTTPBasicAuthorization
import org.junit.Test
class WebserviceUnitTest extends GroovyTestCase {
JsonSlurper jsonSlurper = new JsonSlurper()
static RESTClient client = new RESTClient("https://postman-echo.com")
static {
client.defaultAcceptHeader = ContentType.JSON
client.httpClient.sslTrustAllCerts = true
}
void test_whenSendingGet_thenRespose200() {
def postmanGet = new URL('https://postman-echo.com/get')
def getConnection = postmanGet.openConnection()
getConnection.requestMethod = 'GET'
assert getConnection.responseCode == 200
if (getConnection.responseCode == 200) {
assert jsonSlurper.parseText(getConnection.content.text)?.headers?.host == "postman-echo.com"
}
}
void test_whenSendingPost_thenRespose200() {
def postmanPost = new URL('https://postman-echo.com/post')
def query = "q=This is post request form parameter."
def postConnection = postmanPost.openConnection()
postConnection.requestMethod = 'POST'
assert postConnection.responseCode == 200
}
void test_whenSendingPostWithParams_thenRespose200() {
def postmanPost = new URL('https://postman-echo.com/post')
def form = "param1=This is request parameter."
def postConnection = postmanPost.openConnection()
postConnection.requestMethod = 'POST'
postConnection.doOutput = true
def text
postConnection.with {
outputStream.withWriter { outputStreamWriter ->
outputStreamWriter << form
}
text = content.text
}
assert postConnection.responseCode == 200
assert jsonSlurper.parseText(text)?.json.param1 == "This is request parameter."
}
void test_whenReadingRSS_thenReceiveFeed() {
def rssFeed = new XmlParser().parse("https://news.google.com/rss?hl=en-US&gl=US&ceid=US:en")
def stories = []
(0..4).each {
def item = rssFeed.channel.item.get(it)
stories << item.title.text()
}
assert stories.size() == 5
}
void test_whenReadingAtom_thenReceiveFeed() {
def atomFeed = new XmlParser().parse("https://news.google.com/atom?hl=en-US&gl=US&ceid=US:en")
def stories = []
(0..4).each {
def entry = atomFeed.entry.get(it)
stories << entry.title.text()
}
assert stories.size() == 5
}
void test_whenConsumingSoap_thenReceiveResponse() {
def url = "http://www.dataaccess.com/webservicesserver/numberconversion.wso"
def soapClient = new SOAPClient(url)
def message = new SOAPMessageBuilder().build({
body {
NumberToWords(xmlns: "http://www.dataaccess.com/webservicesserver/") {
ubiNum(1234)
}
}
})
def response = soapClient.send(message.toString());
def words = response.NumberToWordsResponse
assert words == "one thousand two hundred and thirty four "
}
void test_whenConsumingRestGet_thenReceiveResponse() {
def path = "/get"
def response
try {
response = client.get(path: path)
assert response.statusCode == 200
assert response.json?.headers?.host == "postman-echo.com"
} catch (RESTClientException e) {
assert e?.response?.statusCode != 200
}
}
void test_whenConsumingRestPost_thenReceiveResponse() {
def path = "/post"
def params = ["foo":1,"bar":2]
def response
try {
response = client.post(path: path) {
type ContentType.JSON
json params
}
assert response.json?.data == params
} catch (RESTClientException e) {
e.printStackTrace()
assert e?.response?.statusCode != 200
}
}
void test_whenBasicAuthentication_thenReceive200() {
def path = "/basic-auth"
def response
try {
client.authorization = new HTTPBasicAuthorization("postman", "password")
response = client.get(path: path)
assert response.statusCode == 200
assert response.json?.authenticated == true
} catch (RESTClientException e) {
e.printStackTrace()
assert e?.response?.statusCode != 200
}
}
void test_whenOAuth_thenReceive200() {
RESTClient oAuthClient = new RESTClient("https://postman-echo.com")
oAuthClient.defaultAcceptHeader = ContentType.JSON
oAuthClient.httpClient.sslTrustAllCerts = true
def path = "/oauth1"
def params = [oauth_consumer_key: "RKCGzna7bv9YD57c", oauth_signature_method: "HMAC-SHA1", oauth_timestamp:1567089944, oauth_nonce: "URT7v4", oauth_version: 1.0, oauth_signature: 'RGgR/ktDmclkM0ISWaFzebtlO0A=']
def response
try {
response = oAuthClient.get(path: path, query: params)
assert response.statusCode == 200
assert response.statusMessage == "OK"
assert response.json.status == "pass"
} catch (RESTClientException e) {
assert e?.response?.statusCode != 200
}
}
}
@@ -1,4 +1,4 @@
package com.baeldung.java8;
package com.baeldung.java_8_features.groupingby;
import com.baeldung.java_8_features.groupingby.BlogPost;
import com.baeldung.java_8_features.groupingby.BlogPostType;
@@ -0,0 +1,40 @@
package com.baeldung.java.list;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class RemoveFromList {
public static void main(String[] args) {
List<String> sports = new ArrayList<>();
sports.add("Football");
sports.add("Basketball");
sports.add("Baseball");
sports.add("Boxing");
sports.add("Cycling");
System.out.println("List before removing: " + sports);
// Remove with index
sports.remove(1);
// Remove with an element
sports.remove("Baseball");
// Iterator remove method
Iterator<String> iterator = sports.iterator();
while (iterator.hasNext()) {
if (iterator.next().equals("Boxing")) {
iterator.remove();
break;
}
}
// ArrayList removeIf method (Java 8)
sports.removeIf(p -> p.equals("Cycling"));
System.out.println("List after removing: " + sports);
}
}
@@ -1,4 +1,4 @@
package com.baeldung.java8;
package com.baeldung.concurrent.executorservice;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -0,0 +1,3 @@
# Intellij
.idea/
*.iml
+279
View File
@@ -0,0 +1,279 @@
<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-java-io-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-io-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version>
</dependency>
<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.decimal4j</groupId>
<artifactId>decimal4j</artifactId>
<version>${decimal4j.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<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>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>${moneta.version}</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>${esapi.version}</version>
</dependency>
<dependency>
<groupId>com.sun.messaging.mq</groupId>
<artifactId>fscontext</artifactId>
<version>${fscontext.version}</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>${async-http-client.version}</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>${opencsv.version}</version>
<scope>test</scope>
</dependency>
<!-- Mime Type Resolution Libraries -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>${tika.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jmimemagic</groupId>
<artifactId>jmimemagic</artifactId>
<version>${jmime-magic.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-io-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- util -->
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<fscontext.version>4.6-b01</fscontext.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<opencsv.version>4.1</opencsv.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<!-- maven plugins -->
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<hsqldb.version>2.4.0</hsqldb.version>
<esapi.version>2.1.0.1</esapi.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<async-http-client.version>2.4.5</async-http-client.version>
<!-- Mime Type Libraries -->
<tika.version>1.18</tika.version>
<jmime-magic.version>0.1.5</jmime-magic.version>
</properties>
</project>
@@ -0,0 +1,57 @@
package com.baeldung.filereader;
import java.io.*;
public class FileReaderExample {
public static String readAllCharactersOneByOne(Reader reader) throws IOException {
StringBuilder content = new StringBuilder();
int nextChar;
while ((nextChar = reader.read()) != -1) {
content.append((char) nextChar);
}
return String.valueOf(content);
}
public static String readMultipleCharacters(Reader reader, int length) throws IOException {
char[] buffer = new char[length];
int charactersRead = reader.read(buffer, 0, length);
if (charactersRead != -1) {
return new String(buffer, 0, charactersRead);
} else {
return "";
}
}
public static String readFile(String path) {
FileReader fileReader = null;
try {
fileReader = new FileReader(path);
return readAllCharactersOneByOne(fileReader);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static String readFileUsingTryWithResources(String path) {
try (FileReader fileReader = new FileReader(path)) {
return readAllCharactersOneByOne(fileReader);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@@ -0,0 +1,50 @@
package com.baeldung.filereader;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExampleUnitTest {
private static final String FILE_PATH = "src/test/resources/HelloWorld.txt";
@Test
public void givenFileReader_whenReadAllCharacters_thenReturnsContent() throws IOException {
String expectedText = "Hello, World!";
File file = new File(FILE_PATH);
try (FileReader fileReader = new FileReader(file)) {
String content = FileReaderExample.readAllCharactersOneByOne(fileReader);
Assert.assertEquals(expectedText, content);
}
}
@Test
public void givenFileReader_whenReadMultipleCharacters_thenReturnsContent() throws IOException {
String expectedText = "Hello";
File file = new File(FILE_PATH);
try (FileReader fileReader = new FileReader(file)) {
String content = FileReaderExample.readMultipleCharacters(fileReader, 5);
Assert.assertEquals(expectedText, content);
}
}
@Test
public void whenReadFile_thenReturnsContent() {
String expectedText = "Hello, World!";
String content = FileReaderExample.readFile(FILE_PATH);
Assert.assertEquals(expectedText, content);
}
@Test
public void whenReadFileUsingTryWithResources_thenReturnsContent() {
String expectedText = "Hello, World!";
String content = FileReaderExample.readFileUsingTryWithResources(FILE_PATH);
Assert.assertEquals(expectedText, content);
}
}
@@ -0,0 +1 @@
Hello, World!
+17
View File
@@ -207,6 +207,21 @@
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.baeldung.resource.MyResourceLoader</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
@@ -274,6 +289,8 @@
<!-- Mime Type Libraries -->
<tika.version>1.18</tika.version>
<jmime-magic.version>0.1.5</jmime-magic.version>
<maven-jar-plugin.version>3.1.0</maven-jar-plugin.version>
</properties>
</project>
@@ -0,0 +1,42 @@
package com.baeldung.resource;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
public class MyResourceLoader {
private void loadFileWithReader() throws IOException {
try (FileReader fileReader = new FileReader("src/main/resources/input.txt");
BufferedReader reader = new BufferedReader(fileReader)) {
String contents = reader.lines()
.collect(Collectors.joining(System.lineSeparator()));
System.out.println(contents);
}
}
private void loadFileAsResource() throws IOException {
try (InputStream inputStream = getClass().getResourceAsStream("/input.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String contents = reader.lines()
.collect(Collectors.joining(System.lineSeparator()));
System.out.println(contents);
}
}
public static void main(String[] args) throws IOException {
MyResourceLoader resourceLoader = new MyResourceLoader();
resourceLoader.loadFileAsResource();
resourceLoader.loadFileWithReader();
}
}
@@ -0,0 +1,25 @@
*.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
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml
@@ -0,0 +1,5 @@
=========
## Core Java Lang Cookbooks and Examples
### Relevant Articles:
@@ -0,0 +1,33 @@
<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-lang-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
</dependencies>
<build>
<finalName>core-java-lang-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
</properties>
</project>
@@ -0,0 +1,12 @@
package com.baeldung.commandlinearguments;
public class CliExample {
public static void main(String[] args) {
System.out.println("Argument count: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
@@ -0,0 +1,12 @@
package com.baeldung.commandlinearguments;
public class CliExampleWithVarargs {
public static void main(String... args) {
System.out.println("Argument count: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
@@ -14,6 +14,19 @@
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<h2.version>1.4.199</h2.version>
</properties>
<build>
<finalName>core-java-lang-oop-2</finalName>
<resources>
@@ -0,0 +1,31 @@
package com.baeldung.accessmodifiers.publicmodifier;
import java.util.AbstractList;
import java.util.Arrays;
public class ListOfThree<E> extends AbstractList<E> {
private static final int LENGTH = 3;
private Object[] elements;
public ListOfThree(E[] data) {
if(data == null
|| data.length != LENGTH)
throw new IllegalArgumentException();
this.elements = Arrays.copyOf(data, data.length); //shallow copy
}
@Override
@SuppressWarnings("unchecked")
public E get(int index) {
return (E)elements[index];
}
@Override
public int size() {
return LENGTH;
}
}
@@ -0,0 +1,7 @@
package com.baeldung.accessmodifiers.publicmodifier;
public class SpecialCharacters {
public static final String SLASH = "/";
}
@@ -0,0 +1,67 @@
package com.baeldung.accessmodifiers.publicmodifier;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
public class Student {
private StudentGrade grade; //new data representation
// private int grade; //old data representation
private String name;
private int age;
public void setGrade(int grade) {
this.grade = new StudentGrade(grade);
}
public int getGrade() {
return this.grade.getGrade().intValue(); //int is returned for backward compatibility
}
public Connection getConnection() throws SQLException {
final String URL = "jdbc:h2:~/test";
return DriverManager.getConnection(URL, "sa", "");
}
public void setAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException();
}
this.age = age;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return this.name;
}
private class StudentGrade {
private BigDecimal grade = BigDecimal.ZERO;
private Date updatedAt;
public StudentGrade(int grade) {
this.grade = new BigDecimal(grade);
this.updatedAt = new Date();
}
public BigDecimal getGrade() {
return grade;
}
public Date getDate() {
return updatedAt;
}
}
}
@@ -0,0 +1,30 @@
package com.baeldung.copyconstructor;
import java.util.Date;
public class Employee {
protected int id;
protected String name;
protected Date startDate;
public Employee(int id, String name, Date startDate) {
this.id = id;
this.name = name;
this.startDate = startDate;
}
public Employee(Employee employee) {
this.id = employee.id;
this.name = employee.name;
this.startDate = new Date(employee.startDate.getTime());
}
Date getStartDate() {
return startDate;
}
public Employee copy() {
return new Employee(this);
}
}
@@ -0,0 +1,31 @@
package com.baeldung.copyconstructor;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
public class Manager extends Employee {
private List<Employee> directReports;
public Manager(int id, String name, Date startDate, List<Employee> directReports) {
super(id, name, startDate);
this.directReports = directReports;
}
public Manager(Manager manager) {
super(manager.id, manager.name, manager.startDate);
this.directReports = manager.directReports.stream()
.collect(Collectors.toList());
}
@Override
public Employee copy() {
return new Manager(this);
}
List<Employee> getDirectReport() {
return this.directReports;
}
}
@@ -3,12 +3,12 @@ package com.baeldung.core.modifiers;
public class Employee {
private String privateId;
public String name;
private String name;
private boolean manager;
public Employee(String id, String name) {
changeId(id);
this.name = name;
setPrivateId(id);
setName(name);
}
private Employee(String id, String name, boolean managerAttribute) {
@@ -17,7 +17,7 @@ public class Employee {
this.privateId = id + "_ID-MANAGER";
}
public void changeId(String customId) {
public void setPrivateId(String customId) {
if (customId.endsWith("_ID")) {
this.privateId = customId;
} else {
@@ -25,7 +25,7 @@ public class Employee {
}
}
public String getId() {
public String getPrivateId() {
return privateId;
}
@@ -43,6 +43,15 @@ public class Employee {
this.manager = manager;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Employee buildManager(String id, String name) {
return new Employee(id, name, true);
}
@@ -4,7 +4,7 @@ public class ExampleClass {
public static void main(String[] args) {
Employee employee = new Employee("Bob","ABC123");
employee.changeId("BCD234");
System.out.println(employee.getId());
employee.setPrivateId("BCD234");
System.out.println(employee.getPrivateId());
}
}
@@ -0,0 +1,93 @@
package com.baeldung.accessmodifiers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import com.baeldung.accessmodifiers.publicmodifier.ListOfThree;
import com.baeldung.accessmodifiers.publicmodifier.Student;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@TestInstance(Lifecycle.PER_CLASS)
public class PublicAccessModifierUnitTest {
@Test
public void whenUsingBigDecimalIntValueMethod_correspondingIntIsReturned() {
assertEquals(0, new BigDecimal(0).intValue()); //instance member
}
@Test
public void whenUsingIntegerMaxValueField_maxPossibleIntValueIsReturned() {
assertEquals(2147483647, Integer.MAX_VALUE); //static field
}
@Test
public void whenChangingStudentInternalRepresentation_clientCodeWillNotBreak() {
Student student = new Student();
student.setGrade(100);
assertEquals(100, student.getGrade());
}
@Test
public void whenUsingEntrySet_keyValuePairsAreReturned() {
Map<String, String> mapObject = new HashMap<String, String>();
mapObject.put("name", "Alex");
for(Map.Entry<String, String> entry : mapObject.entrySet()) {
assertEquals("name", entry.getKey());
assertEquals("Alex", entry.getValue());
}
}
@Test
public void whenUsingStringToLowerCase_stringTurnsToLowerCase() {
assertEquals("alex", "ALEX".toLowerCase());
}
@Test
public void whenParsingStringOne_parseIntReturns1() {
assertEquals(1, Integer.parseInt("1"));
}
@Test
public void whenConnectingToH2_connectionInstanceIsReturned() throws SQLException {
final String url = "jdbc:h2:~/test";
Connection conn = DriverManager.getConnection(url, "sa", "");
assertNotNull(conn);
}
@Test
public void whenCreatingCustomList_concreteAndInheritedMethodsWork() {
String[] dataSet1 = new String[] {"zero", "one", "two"};
List<String> list1 = new ListOfThree<String>(dataSet1);
//our implemented methods
assertEquals("one", list1.get(1));
assertEquals(3, list1.size());
//inherited implementations
assertEquals(1, list1.indexOf("one"));
String[] dataSet2 = new String[] {"two", "zero", "one"};
List<String> list2 = new ListOfThree<String>(dataSet2);
assertTrue(list1.containsAll(list2));
}
}

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