Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-16767
This commit is contained in:
commit
3166e2eee5
|
@ -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);
|
||||
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant Articles:
|
||||
|
||||
- [Building Java Applications with Bazel](https://www.baeldung.com/bazel-build-tool)
|
|
@ -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
|
|
@ -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!
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.copyconstructor;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class EmployeeUnitTest {
|
||||
@Test
|
||||
public void givenCopyConstructor_whenDeepCopy_thenDistinct() {
|
||||
Date d1 = new Date(123);
|
||||
Employee e1 = new Employee(1, "Baeldung", d1);
|
||||
Employee e2 = new Employee(e1);
|
||||
assertEquals(d1, e1.getStartDate());
|
||||
assertEquals(d1, e2.getStartDate());
|
||||
|
||||
d1.setTime(456);
|
||||
assertEquals(d1, e1.getStartDate());
|
||||
assertNotEquals(d1, e2.getStartDate());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCopyMethod_whenCopy_thenDistinct() {
|
||||
Date d1 = new Date(123);
|
||||
Employee e1 = new Employee(1, "Baeldung", d1);
|
||||
Employee e2 = e1.copy();
|
||||
assertEquals(d1, e1.getStartDate());
|
||||
assertEquals(d1, e2.getStartDate());
|
||||
|
||||
d1.setTime(456);
|
||||
assertEquals(d1, e1.getStartDate());
|
||||
assertNotEquals(d1, e2.getStartDate());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.copyconstructor;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ManagerUnitTest {
|
||||
@Test
|
||||
public void givenCopyConstructor_whenDeepCopy_thenDistinct() {
|
||||
Date startDate = new Date(123);
|
||||
Employee e1 = new Employee(1, "Baeldung", startDate);
|
||||
Employee e2 = new Employee(e1);
|
||||
List<Employee> directReports = new ArrayList<Employee>();
|
||||
directReports.add(e1);
|
||||
directReports.add(e2);
|
||||
|
||||
Manager m1 = new Manager(1, "Baeldung Manager", startDate, directReports);
|
||||
Manager m2 = new Manager(m1);
|
||||
List<Employee> directReports1 = m1.getDirectReport();
|
||||
List<Employee> directReports2 = m2.getDirectReport();
|
||||
assertEquals(directReports1.size(), directReports2.size());
|
||||
assertArrayEquals(directReports1.toArray(), directReports2.toArray());
|
||||
|
||||
// clear m1's direct reports list. m2's list should not be affected
|
||||
directReports.clear();
|
||||
directReports1 = m1.getDirectReport();
|
||||
directReports2 = m2.getDirectReport();
|
||||
assertEquals(0, directReports1.size());
|
||||
assertEquals(2, directReports2.size());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCopyMethod_whenCopy_thenDistinct() {
|
||||
Date startDate = new Date(123);
|
||||
Employee e1 = new Employee(1, "Baeldung", startDate);
|
||||
Employee e2 = new Employee(e1);
|
||||
List<Employee> directReports = new ArrayList<Employee>();
|
||||
directReports.add(e1);
|
||||
directReports.add(e2);
|
||||
|
||||
// a Manager object whose declaration type is Employee.
|
||||
Employee source = new Manager(1, "Baeldung Manager", startDate, directReports);
|
||||
Employee clone = source.copy();
|
||||
|
||||
// after copy, clone should be still a Manager object.
|
||||
assertTrue(clone instanceof Manager);
|
||||
List<Employee> directReports1 = ((Manager) source).getDirectReport();
|
||||
List<Employee> directReports2 = ((Manager) clone).getDirectReport();
|
||||
assertEquals(directReports1.size(), directReports2.size());
|
||||
assertArrayEquals(directReports1.toArray(), directReports2.toArray());
|
||||
|
||||
// clear source's direct reports list. clone's list should not be affected
|
||||
directReports.clear();
|
||||
directReports1 = ((Manager) source).getDirectReport();
|
||||
directReports2 = ((Manager) clone).getDirectReport();
|
||||
assertEquals(0, directReports1.size());
|
||||
assertEquals(2, directReports2.size());
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.booleanoperators;
|
||||
|
||||
public class Car {
|
||||
|
||||
private boolean diesel;
|
||||
private boolean manual;
|
||||
|
||||
public Car(boolean diesel, boolean manual) {
|
||||
this.diesel = diesel;
|
||||
this.manual = manual;
|
||||
}
|
||||
|
||||
public boolean isDiesel() {
|
||||
return diesel;
|
||||
}
|
||||
|
||||
public boolean isManual() {
|
||||
return manual;
|
||||
}
|
||||
|
||||
static Car dieselAndManualCar() {
|
||||
return new Car(true, true);
|
||||
}
|
||||
|
||||
static Car dieselAndAutomaticCar() {
|
||||
return new Car(true, false);
|
||||
}
|
||||
|
||||
static Car oilAndManualCar() {
|
||||
return new Car(false, true);
|
||||
}
|
||||
|
||||
static Car oilAndAutomaticCar() {
|
||||
return new Car(false, false);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package com.baeldung.booleanoperators;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class XorUnitTest {
|
||||
|
||||
@Test
|
||||
void givenDieselManualCar_whenXorOldSchool_thenFalse() {
|
||||
Car car = Car.dieselAndManualCar();
|
||||
boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual());
|
||||
assertThat(dieselXorManual).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDieselAutomaticCar_whenXorOldSchool_thenTrue() {
|
||||
Car car = Car.dieselAndAutomaticCar();
|
||||
boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual());
|
||||
assertThat(dieselXorManual).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonDieselManualCar_whenXorOldSchool_thenTrue() {
|
||||
Car car = Car.oilAndManualCar();
|
||||
boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual());
|
||||
assertThat(dieselXorManual).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonDieselAutomaticCar_whenXorOldSchool_thenFalse() {
|
||||
Car car = Car.oilAndAutomaticCar();
|
||||
boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual());
|
||||
assertThat(dieselXorManual).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDieselManualCar_whenXor_thenFalse() {
|
||||
Car car = Car.dieselAndManualCar();
|
||||
boolean dieselXorManual = car.isDiesel() ^ car.isManual();
|
||||
assertThat(dieselXorManual).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDieselAutomaticCar_whenXor_thenTrue() {
|
||||
Car car = Car.dieselAndAutomaticCar();
|
||||
boolean dieselXorManual = car.isDiesel() ^ car.isManual();
|
||||
assertThat(dieselXorManual).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonDieselManualCar_whenXor_thenTrue() {
|
||||
Car car = Car.oilAndManualCar();
|
||||
boolean dieselXorManual = car.isDiesel() ^ car.isManual();
|
||||
assertThat(dieselXorManual).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonDieselAutomaticCar_whenXor_thenFalse() {
|
||||
Car car = Car.oilAndAutomaticCar();
|
||||
boolean dieselXorManual = car.isDiesel() ^ car.isManual();
|
||||
assertThat(dieselXorManual).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNumbersOneAndThree_whenXor_thenTwo() {
|
||||
assertThat(1 ^ 3).isEqualTo(2);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
<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-security-manager</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-security-manager</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.security.manager;
|
||||
|
||||
import java.security.BasicPermission;
|
||||
|
||||
public class CustomPermission extends BasicPermission {
|
||||
public CustomPermission(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public CustomPermission(String name, String actions) {
|
||||
super(name, actions);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.security.manager;
|
||||
|
||||
public class Service {
|
||||
|
||||
public static final String OPERATION = "my-operation";
|
||||
|
||||
public void operation() {
|
||||
SecurityManager securityManager = System.getSecurityManager();
|
||||
if (securityManager != null) {
|
||||
securityManager.checkPermission(new CustomPermission(OPERATION));
|
||||
}
|
||||
System.out.println("Operation is executed");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new Service().operation();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.security.manager;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.URL;
|
||||
import java.security.AccessControlException;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class SecurityManagerUnitTest {
|
||||
|
||||
@Test(expected = AccessControlException.class)
|
||||
public void whenSecurityManagerIsActive_thenNetworkIsNotAccessibleByDefault() throws Exception {
|
||||
doTest(() -> {
|
||||
new URL("http://www.google.com").openConnection().connect();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@Test(expected = AccessControlException.class)
|
||||
public void whenUnauthorizedClassTriesToAccessProtectedOperation_thenAnExceptionIsThrown() throws Exception {
|
||||
doTest(() -> {
|
||||
new Service().operation();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void doTest(Callable<Void> action) throws Exception {
|
||||
System.setSecurityManager(new SecurityManager());
|
||||
try {
|
||||
action.call();
|
||||
} finally {
|
||||
System.setSecurityManager(null);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -3,6 +3,7 @@ package com.baeldung.uuid;
|
|||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Arrays;
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDGenerator {
|
||||
|
@ -65,9 +66,9 @@ public class UUIDGenerator {
|
|||
try {
|
||||
md = MessageDigest.getInstance("SHA-1");
|
||||
} catch (NoSuchAlgorithmException nsae) {
|
||||
throw new InternalError("MD5 not supported", nsae);
|
||||
throw new InternalError("SHA-1 not supported", nsae);
|
||||
}
|
||||
byte[] bytes = md.digest(name);
|
||||
byte[] bytes = Arrays.copyOfRange(md.digest(name), 0, 16);
|
||||
bytes[6] &= 0x0f; /* clear version */
|
||||
bytes[6] |= 0x50; /* set to version 5 */
|
||||
bytes[8] &= 0x3f; /* clear variant */
|
||||
|
|
|
@ -19,6 +19,7 @@
|
|||
<module>core-java-optional</module>
|
||||
<module>core-java-lang-operators</module>
|
||||
<module>core-java-networking-2</module>
|
||||
<module>core-java-security-manager</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.test;
|
||||
package com.baeldung.jackson.ignore;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
@ -15,9 +15,9 @@ import com.baeldung.jackson.dtos.MyDtoIncludeNonDefault;
|
|||
import com.baeldung.jackson.dtos.MyDtoWithFilter;
|
||||
import com.baeldung.jackson.dtos.MyDtoWithSpecialField;
|
||||
import com.baeldung.jackson.dtos.MyMixInForIgnoreType;
|
||||
import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreField;
|
||||
import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreFieldByName;
|
||||
import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreNull;
|
||||
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreField;
|
||||
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreFieldByName;
|
||||
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreNull;
|
||||
import com.baeldung.jackson.serialization.MyDtoNullKeySerializer;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.dtos.ignore;
|
||||
package com.baeldung.jackson.ignore.dtos;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.dtos.ignore;
|
||||
package com.baeldung.jackson.ignore.dtos;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.dtos.ignore;
|
||||
package com.baeldung.jackson.ignore.dtos;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
|
@ -3,7 +3,6 @@ package com.baeldung.blockchain;
|
|||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Date;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
@ -17,10 +16,10 @@ public class Block {
|
|||
private long timeStamp;
|
||||
private int nonce;
|
||||
|
||||
public Block(String data, String previousHash) {
|
||||
public Block(String data, String previousHash, long timeStamp) {
|
||||
this.data = data;
|
||||
this.previousHash = previousHash;
|
||||
this.timeStamp = new Date().getTime();
|
||||
this.timeStamp = timeStamp;
|
||||
this.hash = calculateBlockHash();
|
||||
}
|
||||
|
||||
|
|
|
@ -3,6 +3,7 @@ package com.baeldung.blockchain;
|
|||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
|
@ -17,10 +18,10 @@ public class BlockchainUnitTest {
|
|||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
Block genesisBlock = new Block("The is the Genesis Block.", "0");
|
||||
Block genesisBlock = new Block("The is the Genesis Block.", "0", new Date().getTime());
|
||||
genesisBlock.mineBlock(prefix);
|
||||
blockchain.add(genesisBlock);
|
||||
Block firstBlock = new Block("The is the First Block.", genesisBlock.getHash());
|
||||
Block firstBlock = new Block("The is the First Block.", genesisBlock.getHash(), new Date().getTime());
|
||||
firstBlock.mineBlock(prefix);
|
||||
blockchain.add(firstBlock);
|
||||
}
|
||||
|
@ -28,7 +29,7 @@ public class BlockchainUnitTest {
|
|||
@Test
|
||||
public void givenBlockchain_whenNewBlockAdded_thenSuccess() {
|
||||
Block newBlock = new Block("The is a New Block.", blockchain.get(blockchain.size() - 1)
|
||||
.getHash());
|
||||
.getHash(), new Date().getTime());
|
||||
newBlock.mineBlock(prefix);
|
||||
assertTrue(newBlock.getHash()
|
||||
.substring(0, prefix)
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
@ -12,7 +12,7 @@ import java.util.Date;
|
|||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.java9.datetime.DateToLocalDateConverter;
|
||||
import com.baeldung.datetolocaldate.DateToLocalDateConverter;
|
||||
|
||||
/**
|
||||
* JUnits for {@link DateToLocalDateConverter} class.
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
@ -12,7 +12,7 @@ import java.util.Date;
|
|||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.java9.datetime.DateToLocalDateTimeConverter;
|
||||
import com.baeldung.datetolocaldate.DateToLocalDateTimeConverter;
|
||||
|
||||
/**
|
||||
* JUnits for {@link DateToLocalDateTimeConverter} class.
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
@ -11,6 +11,8 @@ import java.util.Date;
|
|||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.datetolocaldate.LocalDateTimeToDateConverter;
|
||||
|
||||
/**
|
||||
*
|
||||
* JUnits for {@link LocalDateTimeToDateConverter} class.
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
@ -11,6 +11,8 @@ import java.util.Date;
|
|||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.datetolocaldate.LocalDateToDateConverter;
|
||||
|
||||
/**
|
||||
*
|
||||
* JUnits for {@link LocalDateToDateConverter} class.
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.java8;
|
||||
package com.baeldung.java8.streams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.java8;
|
||||
package com.baeldung.java8.streams;
|
||||
|
||||
import com.baeldung.stream.Product;
|
||||
import org.junit.Before;
|
|
@ -0,0 +1,72 @@
|
|||
package com.baeldung.string.charArrayToString;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class CharArrayToStringConversionUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenStringConstructor_thenOK() {
|
||||
final char[] charArray = { 'b', 'a', 'e', 'l', 'd', 'u', 'n', 'g' };
|
||||
|
||||
String string = new String(charArray);
|
||||
|
||||
assertThat(string, is("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringCopyValueOf_thenOK() {
|
||||
final char[] charArray = { 'b', 'a', 'e', 'l', 'd', 'u', 'n', 'g' };
|
||||
|
||||
String string = String.copyValueOf(charArray);
|
||||
|
||||
assertThat(string, is("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringValueOf_thenOK() {
|
||||
final char[] charArray = { 'b', 'a', 'e', 'l', 'd', 'u', 'n', 'g' };
|
||||
|
||||
String string = String.valueOf(charArray);
|
||||
|
||||
assertThat(string, is("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBuilder_thenOK() {
|
||||
final char[][] arrayOfCharArray = { { 'b', 'a' }, { 'e', 'l', 'd', 'u' }, { 'n', 'g' } };
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (char[] subArray : arrayOfCharArray) {
|
||||
sb.append(subArray);
|
||||
}
|
||||
|
||||
assertThat(sb.toString(), is("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStreamCollectors_thenOK() {
|
||||
final Character[] charArray = { 'b', 'a', 'e', 'l', 'd', 'u', 'n', 'g' };
|
||||
|
||||
Stream<Character> charStream = Arrays.stream(charArray);
|
||||
String string = charStream.map(String::valueOf).collect(Collectors.joining());
|
||||
|
||||
assertThat(string, is("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGoogleCommonBaseJoiners_thenOK() {
|
||||
final Character[] charArray = { 'b', 'a', 'e', 'l', 'd', 'u', 'n', 'g' };
|
||||
|
||||
String string = Joiner.on("|").join(charArray);
|
||||
|
||||
assertThat(string, is("b|a|e|l|d|u|n|g"));
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.string;
|
||||
package com.baeldung.string.newline;
|
||||
|
||||
public class AddingNewLineToString {
|
||||
|
|
@ -2,9 +2,6 @@
|
|||
|
||||
## Java Bean Validation Examples
|
||||
|
||||
###The Course
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java Bean Validation Basics](http://www.baeldung.com/javax-validation)
|
||||
- [Validating Container Elements with Bean Validation 2.0](http://www.baeldung.com/bean-validation-container-elements)
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package org.baeldung;
|
||||
package org.baeldung.javaxval.beanvalidation;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
|
@ -1,20 +1,18 @@
|
|||
package org.baeldung;
|
||||
package org.baeldung.javaxval.beanvalidation;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import javax.validation.ValidatorFactory;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ValidationIntegrationTest {
|
||||
|
|
@ -9,9 +9,14 @@
|
|||
<version>1.0-SNAPSHOT</version>
|
||||
<name>libraries-primitive</name>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/it.unimi.dsi/fastutil -->
|
||||
<dependency>
|
||||
<!-- https://mvnrepository.com/artifact/it.unimi.dsi/fastutil -->
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>8.2.2</version>
|
||||
|
@ -36,5 +41,18 @@
|
|||
<version>1.19</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Eclipse Collections -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.collections</groupId>
|
||||
<artifactId>eclipse-collections-api</artifactId>
|
||||
<version>10.0.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.eclipse.collections</groupId>
|
||||
<artifactId>eclipse-collections</artifactId>
|
||||
<version>10.0.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</project>
|
||||
</project>
|
|
@ -0,0 +1,70 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.eclipse.collections.api.list.primitive.ImmutableIntList;
|
||||
import org.eclipse.collections.api.list.primitive.MutableLongList;
|
||||
import org.eclipse.collections.api.map.primitive.MutableIntIntMap;
|
||||
import org.eclipse.collections.api.set.primitive.MutableIntSet;
|
||||
import org.eclipse.collections.impl.factory.primitive.*;
|
||||
import org.eclipse.collections.impl.list.Interval;
|
||||
import org.eclipse.collections.impl.list.primitive.IntInterval;
|
||||
import org.eclipse.collections.impl.map.mutable.primitive.IntIntHashMap;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.stream.DoubleStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
||||
public class PrimitiveCollectionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenListOfLongHasOneTwoThree_thenSumIsSix() {
|
||||
MutableLongList longList = LongLists.mutable.of(1L, 2L, 3L);
|
||||
assertEquals(6, longList.sum());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListOfIntHasOneTwoThree_thenMaxIsThree() {
|
||||
ImmutableIntList intList = IntLists.immutable.of(1, 2, 3);
|
||||
assertEquals(3, intList.max());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertFromIterableToPrimitive_thenValuesAreEquals() {
|
||||
Iterable<Integer> iterable = Interval.oneTo(3);
|
||||
MutableIntSet intSet = IntSets.mutable.withAll(iterable);
|
||||
IntInterval intInterval = IntInterval.oneTo(3);
|
||||
assertEquals(intInterval.toSet(), intSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOperationsOnIntIntMap() {
|
||||
MutableIntIntMap map = new IntIntHashMap();
|
||||
assertEquals(5, map.addToValue(0, 5));
|
||||
assertEquals(5, map.get(0));
|
||||
assertEquals(3, map.getIfAbsentPut(1, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateDoubleStream_thenAverageIsThree() {
|
||||
DoubleStream doubleStream = DoubleLists
|
||||
.mutable.with(1.0, 2.0, 3.0, 4.0, 5.0)
|
||||
.primitiveStream();
|
||||
assertEquals(3, doubleStream.average().getAsDouble(), 0.001);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMapFromStream_thenValuesMustMatch() {
|
||||
Iterable<Integer> integers = Interval.oneTo(3);
|
||||
MutableIntIntMap map =
|
||||
IntIntMaps.mutable.from(
|
||||
integers,
|
||||
key -> key,
|
||||
value -> value * value);
|
||||
MutableIntIntMap expected = IntIntMaps.mutable.empty()
|
||||
.withKeyValue(1, 1)
|
||||
.withKeyValue(2, 4)
|
||||
.withKeyValue(3, 9);
|
||||
assertEquals(expected, map);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.dto;
|
||||
|
||||
public class CustomerDto {
|
||||
|
||||
private String forename;
|
||||
private String surname;
|
||||
|
||||
public String getForename() {
|
||||
return forename;
|
||||
}
|
||||
|
||||
public CustomerDto setForename(String forename) {
|
||||
this.forename = forename;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getSurname() {
|
||||
return surname;
|
||||
}
|
||||
|
||||
public CustomerDto setSurname(String surname) {
|
||||
this.surname = surname;
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.entity;
|
||||
|
||||
public class Address {
|
||||
|
||||
private String street;
|
||||
private String postalcode;
|
||||
private String county;
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public Address setStreet(String street) {
|
||||
this.street = street;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPostalcode() {
|
||||
return postalcode;
|
||||
}
|
||||
|
||||
public Address setPostalcode(String postalcode) {
|
||||
this.postalcode = postalcode;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getCounty() {
|
||||
return county;
|
||||
}
|
||||
|
||||
public Address setCounty(String county) {
|
||||
this.county = county;
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.entity;
|
||||
|
||||
public class Customer {
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public Customer setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public Customer setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.baeldung.entity;
|
||||
|
||||
public class DeliveryAddress {
|
||||
|
||||
private String forename;
|
||||
private String surname;
|
||||
private String street;
|
||||
private String postalcode;
|
||||
private String county;
|
||||
|
||||
public String getForename() {
|
||||
return forename;
|
||||
}
|
||||
|
||||
public DeliveryAddress setForename(String forename) {
|
||||
this.forename = forename;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getSurname() {
|
||||
return surname;
|
||||
}
|
||||
|
||||
public DeliveryAddress setSurname(String surname) {
|
||||
this.surname = surname;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public DeliveryAddress setStreet(String street) {
|
||||
this.street = street;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPostalcode() {
|
||||
return postalcode;
|
||||
}
|
||||
|
||||
public DeliveryAddress setPostalcode(String postalcode) {
|
||||
this.postalcode = postalcode;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getCounty() {
|
||||
return county;
|
||||
}
|
||||
|
||||
public DeliveryAddress setCounty(String county) {
|
||||
this.county = county;
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
import com.baeldung.dto.CustomerDto;
|
||||
import com.baeldung.entity.Customer;
|
||||
|
||||
@Mapper
|
||||
public interface CustomerDtoMapper {
|
||||
|
||||
@Mapping(source = "firstName", target = "forename")
|
||||
@Mapping(source = "lastName", target = "surname")
|
||||
CustomerDto from(Customer customer);
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.MappingTarget;
|
||||
|
||||
import com.baeldung.entity.Address;
|
||||
import com.baeldung.entity.Customer;
|
||||
import com.baeldung.entity.DeliveryAddress;
|
||||
|
||||
@Mapper
|
||||
public interface DeliveryAddressMapper {
|
||||
|
||||
@Mapping(source = "customer.firstName", target = "forename")
|
||||
@Mapping(source = "customer.lastName", target = "surname")
|
||||
@Mapping(source = "address.street", target = "street")
|
||||
@Mapping(source = "address.postalcode", target = "postalcode")
|
||||
@Mapping(source = "address.county", target = "county")
|
||||
DeliveryAddress from(Customer customer, Address address);
|
||||
|
||||
@Mapping(source = "address.postalcode", target = "postalcode")
|
||||
@Mapping(source = "address.county", target = "county")
|
||||
DeliveryAddress updateAddress(@MappingTarget DeliveryAddress deliveryAddress, Address address);
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.mapper;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
|
||||
import com.baeldung.dto.CustomerDto;
|
||||
import com.baeldung.entity.Customer;
|
||||
|
||||
public class CustomerDtoMapperUnitTest {
|
||||
|
||||
private CustomerDtoMapper customerDtoMapper = Mappers.getMapper(CustomerDtoMapper.class);
|
||||
|
||||
@Test
|
||||
void testGivenCustomer_mapsToCustomerDto() {
|
||||
|
||||
// given
|
||||
Customer customer = new Customer().setFirstName("Max")
|
||||
.setLastName("Powers");
|
||||
|
||||
// when
|
||||
CustomerDto customerDto = customerDtoMapper.from(customer);
|
||||
|
||||
// then
|
||||
assertEquals(customerDto.getForename(), customer.getFirstName());
|
||||
assertEquals(customerDto.getSurname(), customer.getLastName());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
package com.baeldung.mapper;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertSame;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
|
||||
import com.baeldung.entity.Address;
|
||||
import com.baeldung.entity.Customer;
|
||||
import com.baeldung.entity.DeliveryAddress;
|
||||
|
||||
public class DeliveryAddressMapperUnitTest {
|
||||
|
||||
private DeliveryAddressMapper deliveryAddressMapper = Mappers.getMapper(DeliveryAddressMapper.class);
|
||||
|
||||
@Test
|
||||
public void testGivenCustomerAndAddress_mapsToDeliveryAddress() {
|
||||
|
||||
// given
|
||||
Customer customer = new Customer().setFirstName("Max")
|
||||
.setLastName("Powers");
|
||||
|
||||
Address homeAddress = new Address().setStreet("123 Some Street")
|
||||
.setCounty("Nevada")
|
||||
.setPostalcode("89123");
|
||||
|
||||
// when
|
||||
DeliveryAddress deliveryAddress = deliveryAddressMapper.from(customer, homeAddress);
|
||||
|
||||
// then
|
||||
assertEquals(deliveryAddress.getForename(), customer.getFirstName());
|
||||
assertEquals(deliveryAddress.getSurname(), customer.getLastName());
|
||||
assertEquals(deliveryAddress.getStreet(), homeAddress.getStreet());
|
||||
assertEquals(deliveryAddress.getCounty(), homeAddress.getCounty());
|
||||
assertEquals(deliveryAddress.getPostalcode(), homeAddress.getPostalcode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGivenDeliveryAddressAndSomeOtherAddress_updatesDeliveryAddress() {
|
||||
|
||||
// given
|
||||
Customer customer = new Customer().setFirstName("Max")
|
||||
.setLastName("Powers");
|
||||
|
||||
DeliveryAddress deliveryAddress = new DeliveryAddress().setStreet("123 Some Street")
|
||||
.setCounty("Nevada")
|
||||
.setPostalcode("89123");
|
||||
|
||||
Address otherAddress = new Address().setStreet("456 Some other street")
|
||||
.setCounty("Arizona")
|
||||
.setPostalcode("12345");
|
||||
|
||||
// when
|
||||
DeliveryAddress updatedDeliveryAddress = deliveryAddressMapper.updateAddress(deliveryAddress, otherAddress);
|
||||
|
||||
// then
|
||||
assertSame(deliveryAddress, updatedDeliveryAddress);
|
||||
|
||||
assertEquals(deliveryAddress.getStreet(), otherAddress.getStreet());
|
||||
assertEquals(deliveryAddress.getCounty(), otherAddress.getCounty());
|
||||
assertEquals(deliveryAddress.getPostalcode(), otherAddress.getPostalcode());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
### Logistic Regression in Java
|
||||
This is a soft introduction to ML using [deeplearning4j](https://deeplearning4j.org) library
|
||||
|
||||
### Relevant Articles:
|
||||
- [Logistic Regression in Java](http://www.baeldung.com/)
|
|
@ -0,0 +1,52 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.deeplearning4j</groupId>
|
||||
<artifactId>ml</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>Machine Learning</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.nd4j</groupId>
|
||||
<artifactId>nd4j-native-platform</artifactId>
|
||||
<version>${dl4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.deeplearning4j</groupId>
|
||||
<artifactId>deeplearning4j-core</artifactId>
|
||||
<version>${dl4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.deeplearning4j</groupId>
|
||||
<artifactId>deeplearning4j-nn</artifactId>
|
||||
<version>${dl4j.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.datavec/datavec-api -->
|
||||
<dependency>
|
||||
<groupId>org.datavec</groupId>
|
||||
<artifactId>datavec-api</artifactId>
|
||||
<version>${dl4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>4.3.5</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<dl4j.version>1.0.0-beta4</dl4j.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,168 @@
|
|||
package com.baeldung.logreg;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
||||
import org.datavec.api.io.labels.ParentPathLabelGenerator;
|
||||
import org.datavec.api.split.FileSplit;
|
||||
import org.datavec.image.loader.NativeImageLoader;
|
||||
import org.datavec.image.recordreader.ImageRecordReader;
|
||||
import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator;
|
||||
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
|
||||
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
|
||||
import org.deeplearning4j.nn.conf.inputs.InputType;
|
||||
import org.deeplearning4j.nn.conf.layers.ConvolutionLayer;
|
||||
import org.deeplearning4j.nn.conf.layers.DenseLayer;
|
||||
import org.deeplearning4j.nn.conf.layers.OutputLayer;
|
||||
import org.deeplearning4j.nn.conf.layers.SubsamplingLayer;
|
||||
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
|
||||
import org.deeplearning4j.nn.weights.WeightInit;
|
||||
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
|
||||
import org.deeplearning4j.util.ModelSerializer;
|
||||
import org.nd4j.evaluation.classification.Evaluation;
|
||||
import org.nd4j.linalg.activations.Activation;
|
||||
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
|
||||
import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;
|
||||
import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler;
|
||||
import org.nd4j.linalg.learning.config.Nesterovs;
|
||||
import org.nd4j.linalg.lossfunctions.LossFunctions;
|
||||
import org.nd4j.linalg.schedule.MapSchedule;
|
||||
import org.nd4j.linalg.schedule.ScheduleType;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Handwritten digit image classification based on LeNet-5 architecture by Yann LeCun.
|
||||
*
|
||||
* This code accompanies the article "Logistic regression in Java" and is heavily based on
|
||||
* <a href="https://github.com/deeplearning4j/dl4j-examples/blob/master/dl4j-examples/src/main/java/org/deeplearning4j/examples/convolution/mnist/MnistClassifier.java">MnistClassifier</a>.
|
||||
* Some minor changes have been made in order to make article's flow smoother.
|
||||
*
|
||||
*/
|
||||
|
||||
public class MnistClassifier {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MnistClassifier.class);
|
||||
private static final String basePath = System.getProperty("java.io.tmpdir") + "mnist" + File.separator;
|
||||
private static final File modelPath = new File(basePath + "mnist-model.zip");
|
||||
private static final String dataUrl = "http://github.com/myleott/mnist_png/raw/master/mnist_png.tar.gz";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// input image sizes in pixels
|
||||
int height = 28;
|
||||
int width = 28;
|
||||
// input image colour depth (1 for gray scale images)
|
||||
int channels = 1;
|
||||
// the number of output classes
|
||||
int outputClasses = 10;
|
||||
// number of samples that will be propagated through the network in each iteration
|
||||
int batchSize = 54;
|
||||
// total number of training epochs
|
||||
int epochs = 1;
|
||||
|
||||
// initialize a pseudorandom number generator
|
||||
int seed = 1234;
|
||||
Random randNumGen = new Random(seed);
|
||||
|
||||
final String path = basePath + "mnist_png" + File.separator;
|
||||
if (!new File(path).exists()) {
|
||||
logger.info("Downloading data {}", dataUrl);
|
||||
String localFilePath = basePath + "mnist_png.tar.gz";
|
||||
File file = new File(localFilePath);
|
||||
if (!file.exists()) {
|
||||
file.getParentFile()
|
||||
.mkdirs();
|
||||
Utils.downloadAndSave(dataUrl, file);
|
||||
Utils.extractTarArchive(file, basePath);
|
||||
}
|
||||
} else {
|
||||
logger.info("Using the local data from folder {}", path);
|
||||
}
|
||||
|
||||
logger.info("Vectorizing the data from folder {}", path);
|
||||
// vectorization of train data
|
||||
File trainData = new File(path + "training");
|
||||
FileSplit trainSplit = new FileSplit(trainData, NativeImageLoader.ALLOWED_FORMATS, randNumGen);
|
||||
// use parent directory name as the image label
|
||||
ParentPathLabelGenerator labelMaker = new ParentPathLabelGenerator();
|
||||
ImageRecordReader trainRR = new ImageRecordReader(height, width, channels, labelMaker);
|
||||
trainRR.initialize(trainSplit);
|
||||
DataSetIterator train = new RecordReaderDataSetIterator(trainRR, batchSize, 1, outputClasses);
|
||||
|
||||
// pixel values from 0-255 to 0-1 (min-max scaling)
|
||||
DataNormalization imageScaler = new ImagePreProcessingScaler();
|
||||
imageScaler.fit(train);
|
||||
train.setPreProcessor(imageScaler);
|
||||
|
||||
// vectorization of test data
|
||||
File testData = new File(path + "testing");
|
||||
FileSplit testSplit = new FileSplit(testData, NativeImageLoader.ALLOWED_FORMATS, randNumGen);
|
||||
ImageRecordReader testRR = new ImageRecordReader(height, width, channels, labelMaker);
|
||||
testRR.initialize(testSplit);
|
||||
DataSetIterator test = new RecordReaderDataSetIterator(testRR, batchSize, 1, outputClasses);
|
||||
// same normalization for better results
|
||||
test.setPreProcessor(imageScaler);
|
||||
|
||||
logger.info("Network configuration and training...");
|
||||
// reduce the learning rate as the number of training epochs increases
|
||||
// iteration #, learning rate
|
||||
Map<Integer, Double> learningRateSchedule = new HashMap<>();
|
||||
learningRateSchedule.put(0, 0.06);
|
||||
learningRateSchedule.put(200, 0.05);
|
||||
learningRateSchedule.put(600, 0.028);
|
||||
learningRateSchedule.put(800, 0.0060);
|
||||
learningRateSchedule.put(1000, 0.001);
|
||||
|
||||
final ConvolutionLayer layer1 = new ConvolutionLayer.Builder(5, 5).nIn(channels)
|
||||
.stride(1, 1)
|
||||
.nOut(20)
|
||||
.activation(Activation.IDENTITY)
|
||||
.build();
|
||||
final SubsamplingLayer layer2 = new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX).kernelSize(2, 2)
|
||||
.stride(2, 2)
|
||||
.build();
|
||||
// nIn need not specified in later layers
|
||||
final ConvolutionLayer layer3 = new ConvolutionLayer.Builder(5, 5).stride(1, 1)
|
||||
.nOut(50)
|
||||
.activation(Activation.IDENTITY)
|
||||
.build();
|
||||
final DenseLayer layer4 = new DenseLayer.Builder().activation(Activation.RELU)
|
||||
.nOut(500)
|
||||
.build();
|
||||
final OutputLayer layer5 = new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD).nOut(outputClasses)
|
||||
.activation(Activation.SOFTMAX)
|
||||
.build();
|
||||
final MultiLayerConfiguration config = new NeuralNetConfiguration.Builder().seed(seed)
|
||||
.l2(0.0005) // ridge regression value
|
||||
.updater(new Nesterovs(new MapSchedule(ScheduleType.ITERATION, learningRateSchedule)))
|
||||
.weightInit(WeightInit.XAVIER)
|
||||
.list()
|
||||
.layer(layer1)
|
||||
.layer(layer2)
|
||||
.layer(layer3)
|
||||
.layer(layer2)
|
||||
.layer(layer4)
|
||||
.layer(layer5)
|
||||
.setInputType(InputType.convolutionalFlat(height, width, channels))
|
||||
.build();
|
||||
|
||||
final MultiLayerNetwork model = new MultiLayerNetwork(config);
|
||||
model.init();
|
||||
model.setListeners(new ScoreIterationListener(100));
|
||||
logger.info("Total num of params: {}", model.numParams());
|
||||
|
||||
// evaluation while training (the score should go down)
|
||||
for (int i = 0; i < epochs; i++) {
|
||||
model.fit(train);
|
||||
logger.info("Completed epoch {}", i);
|
||||
train.reset();
|
||||
test.reset();
|
||||
}
|
||||
Evaluation eval = model.evaluate(test);
|
||||
logger.info(eval.stats());
|
||||
|
||||
ModelSerializer.writeModel(model, modelPath, true);
|
||||
logger.info("The MINIST model has been saved in {}", modelPath.getPath());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.logreg;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.swing.JFileChooser;
|
||||
|
||||
import org.datavec.image.loader.NativeImageLoader;
|
||||
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
|
||||
import org.deeplearning4j.util.ModelSerializer;
|
||||
import org.nd4j.linalg.api.ndarray.INDArray;
|
||||
import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class MnistPrediction {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MnistPrediction.class);
|
||||
private static final File modelPath = new File(System.getProperty("java.io.tmpdir") + "mnist" + File.separator + "mnist-model.zip");
|
||||
private static final int height = 28;
|
||||
private static final int width = 28;
|
||||
private static final int channels = 1;
|
||||
|
||||
/**
|
||||
* Opens a popup that allows to select a file from the filesystem.
|
||||
* @return
|
||||
*/
|
||||
public static String fileChose() {
|
||||
JFileChooser fc = new JFileChooser();
|
||||
int ret = fc.showOpenDialog(null);
|
||||
if (ret == JFileChooser.APPROVE_OPTION) {
|
||||
File file = fc.getSelectedFile();
|
||||
return file.getAbsolutePath();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
if (!modelPath.exists()) {
|
||||
logger.info("The model not found. Have you trained it?");
|
||||
return;
|
||||
}
|
||||
MultiLayerNetwork model = ModelSerializer.restoreMultiLayerNetwork(modelPath);
|
||||
String path = fileChose();
|
||||
File file = new File(path);
|
||||
|
||||
INDArray image = new NativeImageLoader(height, width, channels).asMatrix(file);
|
||||
new ImagePreProcessingScaler(0, 1).transform(image);
|
||||
|
||||
// Pass through to neural Net
|
||||
INDArray output = model.output(image);
|
||||
|
||||
logger.info("File: {}", path);
|
||||
logger.info("Probabilities: {}", output);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,103 @@
|
|||
package com.baeldung.logreg;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.apache.commons.compress.archivers.ArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Utility class for digit classifier.
|
||||
*
|
||||
*/
|
||||
public class Utils {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Utils.class);
|
||||
|
||||
private Utils() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Download the content of the given url and save it into a file.
|
||||
* @param url
|
||||
* @param file
|
||||
*/
|
||||
public static void downloadAndSave(String url, File file) throws IOException {
|
||||
CloseableHttpClient client = HttpClientBuilder.create()
|
||||
.build();
|
||||
logger.info("Connecting to {}", url);
|
||||
try (CloseableHttpResponse response = client.execute(new HttpGet(url))) {
|
||||
HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
logger.info("Downloaded {} bytes", entity.getContentLength());
|
||||
try (FileOutputStream outstream = new FileOutputStream(file)) {
|
||||
logger.info("Saving to the local file");
|
||||
entity.writeTo(outstream);
|
||||
outstream.flush();
|
||||
logger.info("Local file saved");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a "tar.gz" file into a given folder.
|
||||
* @param file
|
||||
* @param folder
|
||||
*/
|
||||
public static void extractTarArchive(File file, String folder) throws IOException {
|
||||
logger.info("Extracting archive {} into folder {}", file.getName(), folder);
|
||||
// @formatter:off
|
||||
try (FileInputStream fis = new FileInputStream(file);
|
||||
BufferedInputStream bis = new BufferedInputStream(fis);
|
||||
GzipCompressorInputStream gzip = new GzipCompressorInputStream(bis);
|
||||
TarArchiveInputStream tar = new TarArchiveInputStream(gzip)) {
|
||||
// @formatter:on
|
||||
TarArchiveEntry entry;
|
||||
while ((entry = (TarArchiveEntry) tar.getNextEntry()) != null) {
|
||||
extractEntry(entry, tar, folder);
|
||||
}
|
||||
}
|
||||
logger.info("Archive extracted");
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract an entry of the input stream into a given folder
|
||||
* @param entry
|
||||
* @param tar
|
||||
* @param folder
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void extractEntry(ArchiveEntry entry, InputStream tar, String folder) throws IOException {
|
||||
final int bufferSize = 4096;
|
||||
final String path = folder + entry.getName();
|
||||
if (entry.isDirectory()) {
|
||||
new File(path).mkdirs();
|
||||
} else {
|
||||
int count;
|
||||
byte[] data = new byte[bufferSize];
|
||||
// @formatter:off
|
||||
try (FileOutputStream os = new FileOutputStream(path);
|
||||
BufferedOutputStream dest = new BufferedOutputStream(os, bufferSize)) {
|
||||
// @formatter:off
|
||||
while ((count = tar.read(data, 0, bufferSize)) != -1) {
|
||||
dest.write(data, 0, count);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -35,6 +35,11 @@
|
|||
<artifactId>java-driver-core</artifactId>
|
||||
<version>${datastax-cassandra.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.datastax.oss</groupId>
|
||||
<artifactId>java-driver-query-builder</artifactId>
|
||||
<version>${datastax-cassandra.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
|
|
|
@ -26,7 +26,7 @@ public class Application {
|
|||
|
||||
KeyspaceRepository keyspaceRepository = new KeyspaceRepository(session);
|
||||
|
||||
keyspaceRepository.createKeyspace("testKeyspace", "SimpleStrategy", 1);
|
||||
keyspaceRepository.createKeyspace("testKeyspace", 1);
|
||||
keyspaceRepository.useKeyspace("testKeyspace");
|
||||
|
||||
VideoRepository videoRepository = new VideoRepository(session);
|
||||
|
|
|
@ -1,7 +1,11 @@
|
|||
package com.baeldung.datastax.cassandra.repository;
|
||||
|
||||
import com.datastax.oss.driver.api.core.CqlIdentifier;
|
||||
import com.datastax.oss.driver.api.core.CqlSession;
|
||||
|
||||
import com.datastax.oss.driver.api.querybuilder.SchemaBuilder;
|
||||
import com.datastax.oss.driver.api.querybuilder.schema.CreateKeyspace;
|
||||
|
||||
public class KeyspaceRepository {
|
||||
private final CqlSession session;
|
||||
|
||||
|
@ -9,19 +13,15 @@ public class KeyspaceRepository {
|
|||
this.session = session;
|
||||
}
|
||||
|
||||
public void createKeyspace(String keyspaceName, String replicationStrategy, int numberOfReplicas) {
|
||||
StringBuilder sb = new StringBuilder("CREATE KEYSPACE IF NOT EXISTS ").append(keyspaceName)
|
||||
.append(" WITH replication = {")
|
||||
.append("'class':'").append(replicationStrategy)
|
||||
.append("','replication_factor':").append(numberOfReplicas)
|
||||
.append("};");
|
||||
public void createKeyspace(String keyspaceName, int numberOfReplicas) {
|
||||
CreateKeyspace createKeyspace = SchemaBuilder.createKeyspace(keyspaceName)
|
||||
.ifNotExists()
|
||||
.withSimpleStrategy(numberOfReplicas);
|
||||
|
||||
final String query = sb.toString();
|
||||
|
||||
session.execute(query);
|
||||
session.execute(createKeyspace.build());
|
||||
}
|
||||
|
||||
public void useKeyspace(String keyspace) {
|
||||
session.execute("USE " + keyspace);
|
||||
session.execute("USE " + CqlIdentifier.fromCql(keyspace));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,6 +7,12 @@ import com.datastax.oss.driver.api.core.cql.BoundStatement;
|
|||
import com.datastax.oss.driver.api.core.cql.PreparedStatement;
|
||||
import com.datastax.oss.driver.api.core.cql.ResultSet;
|
||||
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
|
||||
import com.datastax.oss.driver.api.core.type.DataTypes;
|
||||
import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
|
||||
import com.datastax.oss.driver.api.querybuilder.SchemaBuilder;
|
||||
import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert;
|
||||
import com.datastax.oss.driver.api.querybuilder.schema.CreateTable;
|
||||
import com.datastax.oss.driver.api.querybuilder.select.Select;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
@ -27,15 +33,12 @@ public class VideoRepository {
|
|||
}
|
||||
|
||||
public void createTable(String keyspace) {
|
||||
StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS ").append(TABLE_NAME).append(" (")
|
||||
.append("video_id UUID,")
|
||||
.append("title TEXT,")
|
||||
.append("creation_date TIMESTAMP,")
|
||||
.append("PRIMARY KEY(video_id));");
|
||||
CreateTable createTable = SchemaBuilder.createTable(TABLE_NAME).ifNotExists()
|
||||
.withPartitionKey("video_id", DataTypes.UUID)
|
||||
.withColumn("title", DataTypes.TEXT)
|
||||
.withColumn("creation_date", DataTypes.TIMESTAMP);
|
||||
|
||||
String query = sb.toString();
|
||||
|
||||
executeStatement(SimpleStatement.newInstance(query), keyspace);
|
||||
executeStatement(createTable.build(), keyspace);
|
||||
}
|
||||
|
||||
public UUID insertVideo(Video video) {
|
||||
|
@ -47,17 +50,23 @@ public class VideoRepository {
|
|||
|
||||
video.setId(videoId);
|
||||
|
||||
String absoluteTableName = keyspace != null ? keyspace + "." + TABLE_NAME: TABLE_NAME;
|
||||
RegularInsert insertInto = QueryBuilder.insertInto(TABLE_NAME)
|
||||
.value("video_id", QueryBuilder.bindMarker())
|
||||
.value("title", QueryBuilder.bindMarker())
|
||||
.value("creation_date", QueryBuilder.bindMarker());
|
||||
|
||||
StringBuilder sb = new StringBuilder("INSERT INTO ").append(absoluteTableName)
|
||||
.append("(video_id, title, creation_date) values (:video_id, :title, :creation_date)");
|
||||
SimpleStatement insertStatement = insertInto.build();
|
||||
|
||||
PreparedStatement preparedStatement = session.prepare(sb.toString());
|
||||
if (keyspace != null) {
|
||||
insertStatement = insertStatement.setKeyspace(keyspace);
|
||||
}
|
||||
|
||||
PreparedStatement preparedStatement = session.prepare(insertStatement);
|
||||
|
||||
BoundStatement statement = preparedStatement.bind()
|
||||
.setUuid("video_id", video.getId())
|
||||
.setString("title", video.getTitle())
|
||||
.setInstant("creation_date", video.getCreationDate());
|
||||
.setUuid(0, video.getId())
|
||||
.setString(1, video.getTitle())
|
||||
.setInstant(2, video.getCreationDate());
|
||||
|
||||
session.execute(statement);
|
||||
|
||||
|
@ -69,11 +78,9 @@ public class VideoRepository {
|
|||
}
|
||||
|
||||
public List<Video> selectAll(String keyspace) {
|
||||
StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME);
|
||||
Select select = QueryBuilder.selectFrom(TABLE_NAME).all();
|
||||
|
||||
String query = sb.toString();
|
||||
|
||||
ResultSet resultSet = executeStatement(SimpleStatement.newInstance(query), keyspace);
|
||||
ResultSet resultSet = executeStatement(select.build(), keyspace);
|
||||
|
||||
List<Video> result = new ArrayList<>();
|
||||
|
||||
|
|
|
@ -60,5 +60,6 @@
|
|||
<module>spring-persistence-simple</module>
|
||||
<module>jpa-hibernate-cascade-type</module>
|
||||
<module>r2dbc</module>
|
||||
<module>spring-boot-jdbi</module>
|
||||
</modules>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
HELP.md
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**
|
||||
!**/src/test/**
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
114
persistence-modules/spring-boot-jdbi/.mvn/wrapper/MavenWrapperDownloader.java
vendored
Normal file
114
persistence-modules/spring-boot-jdbi/.mvn/wrapper/MavenWrapperDownloader.java
vendored
Normal file
|
@ -0,0 +1,114 @@
|
|||
/*
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
*/
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.nio.channels.Channels;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
import java.util.Properties;
|
||||
|
||||
public class MavenWrapperDownloader {
|
||||
|
||||
/**
|
||||
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
|
||||
*/
|
||||
private static final String DEFAULT_DOWNLOAD_URL =
|
||||
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
|
||||
|
||||
/**
|
||||
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
|
||||
* use instead of the default one.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
|
||||
".mvn/wrapper/maven-wrapper.properties";
|
||||
|
||||
/**
|
||||
* Path where the maven-wrapper.jar will be saved to.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_JAR_PATH =
|
||||
".mvn/wrapper/maven-wrapper.jar";
|
||||
|
||||
/**
|
||||
* Name of the property which should be used to override the default download url for the wrapper.
|
||||
*/
|
||||
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
|
||||
|
||||
public static void main(String args[]) {
|
||||
System.out.println("- Downloader started");
|
||||
File baseDirectory = new File(args[0]);
|
||||
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
|
||||
|
||||
// If the maven-wrapper.properties exists, read it and check if it contains a custom
|
||||
// wrapperUrl parameter.
|
||||
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
|
||||
String url = DEFAULT_DOWNLOAD_URL;
|
||||
if(mavenWrapperPropertyFile.exists()) {
|
||||
FileInputStream mavenWrapperPropertyFileInputStream = null;
|
||||
try {
|
||||
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
|
||||
Properties mavenWrapperProperties = new Properties();
|
||||
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
|
||||
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
|
||||
} catch (IOException e) {
|
||||
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
|
||||
} finally {
|
||||
try {
|
||||
if(mavenWrapperPropertyFileInputStream != null) {
|
||||
mavenWrapperPropertyFileInputStream.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Ignore ...
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading from: : " + url);
|
||||
|
||||
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
|
||||
if(!outputFile.getParentFile().exists()) {
|
||||
if(!outputFile.getParentFile().mkdirs()) {
|
||||
System.out.println(
|
||||
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
|
||||
try {
|
||||
downloadFileFromURL(url, outputFile);
|
||||
System.out.println("Done");
|
||||
System.exit(0);
|
||||
} catch (Throwable e) {
|
||||
System.out.println("- Error downloading");
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
|
||||
URL website = new URL(urlString);
|
||||
ReadableByteChannel rbc;
|
||||
rbc = Channels.newChannel(website.openStream());
|
||||
FileOutputStream fos = new FileOutputStream(destination);
|
||||
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
|
||||
fos.close();
|
||||
rbc.close();
|
||||
}
|
||||
|
||||
}
|
Binary file not shown.
|
@ -0,0 +1 @@
|
|||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
|
|
@ -0,0 +1,286 @@
|
|||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven2 Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -x "/usr/libexec/java_home" ]; then
|
||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
||||
else
|
||||
export JAVA_HOME="/Library/Java/Home"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Mingw, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
# TODO classpath?
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
|
||||
if [ -z "$1" ]
|
||||
then
|
||||
echo "Path not specified to find_maven_basedir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
basedir="$1"
|
||||
wdir="$1"
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||
if [ -d "${wdir}" ]; then
|
||||
wdir=`cd "$wdir/.."; pwd`
|
||||
fi
|
||||
# end of workaround
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_DIR=`find_maven_basedir "$(pwd)"`
|
||||
if [ -z "$BASE_DIR" ]; then
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
##########################################################################################
|
||||
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
# This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
##########################################################################################
|
||||
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found .mvn/wrapper/maven-wrapper.jar"
|
||||
fi
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
|
||||
fi
|
||||
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
|
||||
while IFS="=" read key value; do
|
||||
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
|
||||
esac
|
||||
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Downloading from: $jarUrl"
|
||||
fi
|
||||
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
|
||||
|
||||
if command -v wget > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found wget ... using wget"
|
||||
fi
|
||||
wget "$jarUrl" -O "$wrapperJarPath"
|
||||
elif command -v curl > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found curl ... using curl"
|
||||
fi
|
||||
curl -o "$wrapperJarPath" "$jarUrl"
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Falling back to using Java to download"
|
||||
fi
|
||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||
if [ -e "$javaClass" ]; then
|
||||
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Compiling MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
# Compiling the Java class
|
||||
("$JAVA_HOME/bin/javac" "$javaClass")
|
||||
fi
|
||||
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
# Running the downloader
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Running MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
##########################################################################################
|
||||
# End of extension
|
||||
##########################################################################################
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo $MAVEN_PROJECTBASEDIR
|
||||
fi
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
|
||||
fi
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
|
@ -0,0 +1,161 @@
|
|||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM https://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven2 Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM set title of command window
|
||||
title %0
|
||||
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
|
||||
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
|
||||
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
|
||||
)
|
||||
|
||||
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
if exist %WRAPPER_JAR% (
|
||||
echo Found %WRAPPER_JAR%
|
||||
) else (
|
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||
echo Downloading from: %DOWNLOAD_URL%
|
||||
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
|
||||
echo Finished downloading %WRAPPER_JAR%
|
||||
)
|
||||
@REM End of extension
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
|
@ -0,0 +1,107 @@
|
|||
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.boot.jdbi</groupId>
|
||||
<artifactId>spring-boot-jdbi</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>spring-boot-jdbi</name>
|
||||
<description>Sample SpringBoot JDBI Project</description>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<jdbi.version>3.9.1</jdbi.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>2.1.7.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jdbi</groupId>
|
||||
<artifactId>jdbi3-spring4</artifactId>
|
||||
<version>${jdbi.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jdbi</groupId>
|
||||
<artifactId>jdbi3-sqlobject</artifactId>
|
||||
<version>${jdbi.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jdbi</groupId>
|
||||
<artifactId>jdbi3-spring4</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jdbi</groupId>
|
||||
<artifactId>jdbi3-sqlobject</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<scope>runtime</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.boot.jdbi;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.jdbi.v3.core.Jdbi;
|
||||
import org.jdbi.v3.core.mapper.RowMapper;
|
||||
import org.jdbi.v3.core.spi.JdbiPlugin;
|
||||
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import com.baeldung.boot.jdbi.dao.CarMakerDao;
|
||||
import com.baeldung.boot.jdbi.dao.CarModelDao;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
@Configuration
|
||||
@Slf4j
|
||||
public class JdbiConfiguration {
|
||||
@Bean
|
||||
public Jdbi jdbi(DataSource ds,List<JdbiPlugin> jdbiPlugins, List<RowMapper<?>> rowMappers) {
|
||||
TransactionAwareDataSourceProxy proxy = new TransactionAwareDataSourceProxy(ds);
|
||||
Jdbi jdbi = Jdbi.create(proxy);
|
||||
|
||||
// Register all available plugins
|
||||
log.info("[I27] Installing plugins... ({} found)", jdbiPlugins.size());
|
||||
jdbiPlugins.forEach(plugin -> jdbi.installPlugin(plugin));
|
||||
|
||||
// Register all available rowMappers
|
||||
log.info("[I31] Installing rowMappers... ({} found)", rowMappers.size());
|
||||
rowMappers.forEach(mapper -> jdbi.registerRowMapper(mapper));
|
||||
|
||||
return jdbi;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JdbiPlugin sqlObjectPlugin() {
|
||||
return new SqlObjectPlugin();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CarMakerDao carMakerDao(Jdbi jdbi) {
|
||||
return jdbi.onDemand(CarMakerDao.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CarModelDao carModelDao(Jdbi jdbi) {
|
||||
return jdbi.onDemand(CarModelDao.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.boot.jdbi;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableTransactionManagement
|
||||
public class SpringBootJdbiApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringBootJdbiApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.boot.jdbi.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.jdbi.v3.sqlobject.customizer.Bind;
|
||||
import org.jdbi.v3.sqlobject.customizer.BindBean;
|
||||
import org.jdbi.v3.sqlobject.locator.UseClasspathSqlLocator;
|
||||
import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys;
|
||||
import org.jdbi.v3.sqlobject.statement.SqlBatch;
|
||||
import org.jdbi.v3.sqlobject.statement.SqlQuery;
|
||||
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
|
||||
|
||||
import com.baeldung.boot.jdbi.domain.CarMaker;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
@UseClasspathSqlLocator
|
||||
public interface CarMakerDao {
|
||||
|
||||
@SqlUpdate
|
||||
@GetGeneratedKeys
|
||||
Long insert(@BindBean CarMaker carMaker);
|
||||
|
||||
@SqlBatch("insert")
|
||||
@GetGeneratedKeys
|
||||
List<Long> bulkInsert(@BindBean List<CarMaker> carMakers);
|
||||
|
||||
@SqlQuery
|
||||
CarMaker findById(@Bind("id") Long id);
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.boot.jdbi.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.jdbi.v3.sqlobject.customizer.Bind;
|
||||
import org.jdbi.v3.sqlobject.customizer.BindBean;
|
||||
import org.jdbi.v3.sqlobject.locator.UseClasspathSqlLocator;
|
||||
import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys;
|
||||
import org.jdbi.v3.sqlobject.statement.SqlBatch;
|
||||
import org.jdbi.v3.sqlobject.statement.SqlQuery;
|
||||
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
|
||||
|
||||
import com.baeldung.boot.jdbi.domain.CarModel;
|
||||
|
||||
@UseClasspathSqlLocator
|
||||
public interface CarModelDao {
|
||||
|
||||
@SqlUpdate("insert")
|
||||
@GetGeneratedKeys
|
||||
Long insert(@BindBean CarModel carModel);
|
||||
|
||||
@SqlBatch("insert")
|
||||
@GetGeneratedKeys
|
||||
List<Long> bulkInsert(@BindBean List<CarModel> models);
|
||||
|
||||
@SqlQuery
|
||||
CarModel findByMakerIdAndSku(@Bind("makerId") Long makerId, @Bind("sku") String sku );
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.boot.jdbi.domain;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class CarMaker {
|
||||
private Long id;
|
||||
private String name;
|
||||
private List<CarModel> models;
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.boot.jdbi.domain;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
public class CarModel {
|
||||
private Long id;
|
||||
private String name;
|
||||
private Integer year;
|
||||
private String sku;
|
||||
private Long makerId;
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.boot.jdbi.mapper;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import org.jdbi.v3.core.mapper.RowMapper;
|
||||
import org.jdbi.v3.core.statement.StatementContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.boot.jdbi.domain.CarMaker;
|
||||
import com.baeldung.boot.jdbi.domain.CarModel;
|
||||
|
||||
@Component
|
||||
public class CarMakerMapper implements RowMapper<CarMaker> {
|
||||
|
||||
@Override
|
||||
public CarMaker map(ResultSet rs, StatementContext ctx) throws SQLException {
|
||||
CarMaker maker = CarMaker.builder()
|
||||
.id(rs.getLong("id"))
|
||||
.name(rs.getString("name"))
|
||||
.models(new ArrayList<CarModel>())
|
||||
.build();
|
||||
|
||||
return maker;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.boot.jdbi.mapper;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.jdbi.v3.core.mapper.RowMapper;
|
||||
import org.jdbi.v3.core.statement.StatementContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.boot.jdbi.domain.CarModel;
|
||||
|
||||
@Component
|
||||
public class CarModelMapper implements RowMapper<CarModel>{
|
||||
|
||||
@Override
|
||||
public CarModel map(ResultSet rs, StatementContext ctx) throws SQLException {
|
||||
return CarModel.builder()
|
||||
.id(rs.getLong("id"))
|
||||
.name(rs.getString("name"))
|
||||
.sku(rs.getString("sku"))
|
||||
.year(rs.getInt("year"))
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.boot.jdbi.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.boot.jdbi.dao.CarMakerDao;
|
||||
import com.baeldung.boot.jdbi.dao.CarModelDao;
|
||||
import com.baeldung.boot.jdbi.domain.CarMaker;
|
||||
import com.baeldung.boot.jdbi.domain.CarModel;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
@Service
|
||||
public class CarMakerService {
|
||||
|
||||
private CarMakerDao carMakerDao;
|
||||
private CarModelDao carModelDao;
|
||||
|
||||
public CarMakerService(CarMakerDao carMakerDao,CarModelDao carModelDao) {
|
||||
|
||||
this.carMakerDao = carMakerDao;
|
||||
this.carModelDao = carModelDao;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public int bulkInsert(CarMaker carMaker) {
|
||||
Long carMakerId;
|
||||
if (carMaker.getId() == null ) {
|
||||
carMakerId = carMakerDao.insert(carMaker);
|
||||
carMaker.setId(carMakerId);
|
||||
}
|
||||
|
||||
// Make sure all models belong to the same maker
|
||||
carMaker.getModels().forEach(m -> {
|
||||
m.setMakerId(carMaker.getId());
|
||||
carModelDao.insert(m);
|
||||
});
|
||||
|
||||
return carMaker.getModels().size();
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
|
|
@ -0,0 +1,11 @@
|
|||
--
|
||||
-- findById
|
||||
--
|
||||
select
|
||||
id,
|
||||
name
|
||||
from
|
||||
car_maker
|
||||
where
|
||||
id = :id
|
||||
;
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue