Merge branch 'master' into master

This commit is contained in:
dev-chirag 2019-05-02 22:24:56 +05:30 committed by GitHub
commit e224d97114
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
180 changed files with 2102 additions and 483 deletions

View File

@ -14,7 +14,5 @@
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm)

View File

@ -8,9 +8,6 @@
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)

4
algorithms-miscellaneous-3/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/target/
.settings/
.classpath
.project

View File

@ -0,0 +1,7 @@
## Relevant articles:
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)

View File

@ -0,0 +1,39 @@
<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>algorithms-miscellaneous-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>algorithms-miscellaneous-3</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${org.assertj.core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -4,3 +4,8 @@
### Relevant Articles:
- [Set Operations in Java](http://www.baeldung.com/set-operations-in-java)
- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)

View File

@ -4,14 +4,10 @@
### Relevant Articles:
- [Java Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering)
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
@ -23,7 +19,6 @@
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
- [Removing Elements from Java Collections](https://www.baeldung.com/java-collection-remove-elements)
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
- [Sorting in Java](http://www.baeldung.com/java-sorting)

View File

@ -0,0 +1,31 @@
package com.baeldung.jvmannotations
import java.util.*
interface Document {
@JvmDefault
fun getType() = "document"
}
class TextDocument : Document {
override fun getType() = "text"
fun transformList(list : List<Number>) : List<Number> {
return list.filter { n -> n.toInt() > 1 }
}
fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> {
return list.filter { n -> n.toInt() > 1 }
}
var list : List<@JvmWildcard Any> = ArrayList()
}
class XmlDocument(d : Document) : Document by d
fun main() {
val myDocument = TextDocument()
val myTextDocument = XmlDocument(myDocument)
println("${myDocument.getType()} ${myTextDocument.getType()}")
}

View File

@ -0,0 +1,9 @@
package com.baeldung.jvmannotations;
public class HtmlDocument implements Document {
@Override
public String getType() {
return "HTML";
}
}

View File

@ -0,0 +1,66 @@
@file:JvmName("MessageHelper")
@file:JvmMultifileClass //used
package com.baeldung.jvmannotations
import java.util.*
@JvmName("getMyUsername")
fun getMyName() : String {
return "myUserId"
}
object MessageBroker {
@JvmStatic
var totalMessagesSent = 0
const val maxMessageLength = 0
@JvmStatic
fun clearAllMessages() {
}
@JvmStatic
@JvmOverloads
@Throws(Exception::class)
fun findMessages(sender : String, type : String = "text", maxResults : Int = 10) : List<Message> {
if(sender.isEmpty()) {
throw Exception()
}
return ArrayList()
}
}
class Message {
// this would cause a compilation error since sender is immutable
// @set:JvmName("setSender")
val sender = "myself"
// this works as name is overridden
@JvmName("getSenderName")
fun getSender() : String = "from:$sender"
@get:JvmName("getReceiverName")
@set:JvmName("setReceiverName")
var receiver : String = ""
@get:JvmName("getContent")
@set:JvmName("setContent")
var text = ""
// generates a warning
@get:JvmName("getId")
private val id = 0
@get:JvmName("hasAttachment")
var hasAttachment = true
var isEncrypted = true
fun setReceivers(receiverNames : List<String>) {
}
@JvmName("setReceiverIds")
fun setReceivers(receiverNames : List<Int>) {
}
}

View File

@ -0,0 +1,6 @@
@file:JvmMultifileClass
@file:JvmName("MessageHelper") //applies to all top level functions / variables / constants
package com.baeldung.jvmannotations
fun convert(message: Message) {
}

View File

@ -1,3 +1,5 @@
## Relevant articles:
- [InputStream to String in Kotlin](https://www.baeldung.com/kotlin-inputstream-to-string)
- [Console I/O in Kotlin](https://www.baeldung.com/kotlin-console-io)

View File

@ -1,44 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>fastUtil</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/it.unimi.dsi/fastutil -->
<dependency>
<groupId>it.unimi.dsi</groupId>
<artifactId>fastutil</artifactId>
<version>8.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -9,4 +9,8 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [HttpClient 4 Get the Status Code](http://www.baeldung.com/httpclient-status-code)
- [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl)
- [HttpClient Timeout](http://www.baeldung.com/httpclient-timeout)
- [HttpClient 4 Send Custom Cookie](http://www.baeldung.com/httpclient-4-cookies)
- [Custom HTTP Header with the HttpClient](http://www.baeldung.com/httpclient-custom-http-header)
- [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication)
- [Posting with HttpClient](https://www.baeldung.com/httpclient-post-http-request)

View File

@ -46,16 +46,11 @@ public class RestClientLiveManualTest {
// old httpClient will throw UnsupportedOperationException
@Ignore
@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException_1() throws GeneralSecurityException {
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_1() throws GeneralSecurityException {
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
final CloseableHttpClient httpClient = (CloseableHttpClient) requestFactory.getHttpClient();
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
return true;
}
};
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, ALLOW_ALL_HOSTNAME_VERIFIER);
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 8443, sf));
@ -65,7 +60,7 @@ public class RestClientLiveManualTest {
// new httpClient : 4.4 and above
@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException_2() throws GeneralSecurityException {
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();

View File

@ -1,20 +1,27 @@
package org.baeldung.httpclient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.After;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.junit.After;
import org.junit.Test;
public class HttpClientTimeoutLiveTest {
private CloseableHttpResponse response;
@ -25,6 +32,20 @@ public class HttpClientTimeoutLiveTest {
}
// tests
@Test
public final void givenUsingOldApi_whenSettingTimeoutViaParameter_thenCorrect() throws IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
int timeout = 5; // seconds
HttpParams httpParams = httpClient.getParams();
httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout * 1000);
httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout * 1000);
httpParams.setParameter(ClientPNames.CONN_MANAGER_TIMEOUT, new Long(timeout * 1000));
final HttpGet request = new HttpGet("http://www.github.com");
HttpResponse execute = httpClient.execute(request);
assertThat(execute.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws IOException {
@ -33,8 +54,6 @@ public class HttpClientTimeoutLiveTest {
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
final HttpGet request = new HttpGet("http://www.github.com");
// httpParams.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, new Long(timeout * 1000)); // https://issues.apache.org/jira/browse/HTTPCLIENT-1418
response = client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
@ -71,7 +90,7 @@ public class HttpClientTimeoutLiveTest {
/**
* This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP)
*/
@Test(expected = HttpHostConnectException.class)
@Test(expected = ConnectTimeoutException.class)
public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException {
final int timeout = 3;
@ -82,4 +101,27 @@ public class HttpClientTimeoutLiveTest {
client.execute(request);
}
@Test
public void whenSecuredRestApiIsConsumed_then200OK() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
int timeout = 20; // seconds
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000)
.setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
HttpGet getMethod = new HttpGet("http://localhost:8082/httpclient-simple/api/bars/1");
getMethod.setConfig(requestConfig);
int hardTimeout = 5; // seconds
TimerTask task = new TimerTask() {
@Override
public void run() {
getMethod.abort();
}
};
new Timer(true).schedule(task, hardTimeout * 1000);
HttpResponse response = httpClient.execute(getMethod);
System.out.println("HTTP Status of response: " + response.getStatusLine().getStatusCode());
}
}

View File

@ -7,12 +7,10 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [HttpClient 4 Send Custom Cookie](http://www.baeldung.com/httpclient-4-cookies)
- [HttpClient 4 Cancel Request](http://www.baeldung.com/httpclient-cancel-request)
- [HttpClient 4 Cookbook](http://www.baeldung.com/httpclient4)
- [Unshorten URLs with HttpClient](http://www.baeldung.com/unshorten-url-httpclient)
- [HttpClient 4 Follow Redirects for POST](http://www.baeldung.com/httpclient-redirect-on-http-post)
- [Custom HTTP Header with the HttpClient](http://www.baeldung.com/httpclient-custom-http-header)
- [Multipart Upload with HttpClient 4](http://www.baeldung.com/httpclient-multipart-upload)
- [HttpAsyncClient Tutorial](http://www.baeldung.com/httpasyncclient-tutorial)
- [HttpClient 4 Tutorial](http://www.baeldung.com/httpclient-guide)

View File

@ -15,6 +15,12 @@
</parent>
<dependencies>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
@ -49,6 +55,7 @@
<properties>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<joda-time.version>2.10</joda-time.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
</properties>

View File

@ -0,0 +1,59 @@
package com.baeldung.convert;
import org.joda.time.Instant;
import org.junit.Assert;
import org.junit.Test;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
public class ConvertDateTimeUnitTest {
public final long millis = 1556175797428L;
@Test
public void givenLocalDateTime_WhenToEpochMillis_ThenMillis() {
ZoneId id = ZoneId.systemDefault();
LocalDateTime localDateTime =
LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(millis), id);
ZonedDateTime zdt = ZonedDateTime.of(localDateTime, id);
Assert.assertEquals(millis, zdt.toInstant().toEpochMilli());
}
@Test
public void givenJava8Instant_WhenGToEpochMillis_ThenMillis() {
java.time.Instant instant = java.time.Instant.ofEpochMilli(millis);
Assert.assertEquals(millis, instant.toEpochMilli());
}
@Test
public void givenDate_WhenGetTime_ThenMillis() {
Date date = new Date(millis);
Assert.assertEquals(millis, date.getTime());
}
@Test
public void givenCalendar_WhenGetTimeInMillis_ThenMillis() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(millis));
Assert.assertEquals(millis, calendar.getTimeInMillis());
}
@Test
public void givenJodaInstant_WhenGetMillis_ThenMillis() {
Instant jodaInstant = Instant.ofEpochMilli(millis);
Assert.assertEquals(millis, jodaInstant.getMillis());
}
@Test
public void givenJODADateTime_WhenGetMillis_ThenMillis() {
org.joda.time.DateTime jodaDateTime = new org.joda.time.DateTime(millis);
Assert.assertEquals(millis, jodaDateTime.getMillis());
}
}

150
java-strings-2/pom.xml Executable file
View File

@ -0,0 +1,150 @@
<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>java-strings-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>java-strings-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>${icu4j.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.vdurmont</groupId>
<artifactId>emoji-java</artifactId>
<version>${emoji-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter-api.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${hamcrest-library.version}</version>
<scope>test</scope>
</dependency>
<!-- Added for password generation -->
<dependency>
<groupId>org.passay</groupId>
<artifactId>passay</artifactId>
<version>${passay.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>org.ahocorasick</groupId>
<artifactId>ahocorasick</artifactId>
<version>${ahocorasick.version}</version>
</dependency>
</dependencies>
<build>
<finalName>java-strings-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- util -->
<commons-lang3.version>3.8.1</commons-lang3.version>
<commons-codec.version>1.10</commons-codec.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<jmh-core.version>1.19</jmh-core.version>
<icu4j.version>61.1</icu4j.version>
<guava.version>27.0.1-jre</guava.version>
<emoji-java.version>4.0.0</emoji-java.version>
<junit-jupiter-api.version>5.3.1</junit-jupiter-api.version>
<hamcrest-library.version>1.3</hamcrest-library.version>
<passay.version>1.3.1</passay.version>
<commons-text.version>1.4</commons-text.version>
<ahocorasick.version>0.4.0</ahocorasick.version>
</properties>
</project>

View File

@ -0,0 +1,58 @@
package com.baeldung.string.search.performance;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
/**
* Based on https://github.com/tedyoung/indexof-contains-benchmark
*/
@Fork(5)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class SubstringSearchPerformanceComparison {
private String message;
private Pattern pattern;
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@Setup
public void setup() {
message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
pattern = Pattern.compile("(?<!\\S)" + "eiusmod" + "(?!\\S)");
}
@Benchmark
public int indexOf() {
return message.indexOf("eiusmod");
}
@Benchmark
public boolean contains() {
return message.contains("eiusmod");
}
@Benchmark
public boolean containsStringUtilsIgnoreCase() {
return StringUtils.containsIgnoreCase(message, "eiusmod");
}
@Benchmark
public boolean searchWithPattern() {
return pattern.matcher(message).find();
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,70 @@
package com.baeldung.string.search;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
/**
* BAEL-2832: Different ways to check if a Substring could be found in a String.
*/
public class SubstringSearch {
@Test
public void searchSubstringWithIndexOf() {
Assert.assertEquals(9, "Bohemian Rhapsodyan".indexOf("Rhap"));
// indexOf will return -1, because it's case sensitive
Assert.assertEquals(-1, "Bohemian Rhapsodyan".indexOf("rhap"));
// indexOf will return 9, because it's all lowercase
Assert.assertEquals(9, "Bohemian Rhapsodyan".toLowerCase()
.indexOf("rhap"));
// it will return 6, because it's the first occurrence. Sorry Queen for being blasphemic
Assert.assertEquals(6, "Bohemian Rhapsodyan".indexOf("an"));
}
@Test
public void searchSubstringWithContains() {
Assert.assertTrue("Hey Ho, let's go".contains("Hey"));
// contains will return false, because it's case sensitive
Assert.assertFalse("Hey Ho, let's go".contains("hey"));
// contains will return true, because it's all lowercase
Assert.assertTrue("Hey Ho, let's go".toLowerCase().contains("hey"));
// contains will return false, because 'jey' can't be found
Assert.assertFalse("Hey Ho, let's go".contains("jey"));
}
@Test
public void searchSubstringWithStringUtils() {
Assert.assertTrue(StringUtils.containsIgnoreCase("Runaway train", "train"));
// it will also be true, because ignores case ;)
Assert.assertTrue(StringUtils.containsIgnoreCase("Runaway train", "Train"));
}
@Test
public void searchUsingPattern() {
// We create the Pattern first
Pattern pattern = Pattern.compile("(?<!\\S)" + "road" + "(?!\\S)");
// We need to create the Matcher after
Matcher matcher = pattern.matcher("Hit the road Jack");
// find will return true when the first match is found
Assert.assertTrue(matcher.find());
// We will create a different matcher with a different text
matcher = pattern.matcher("and don't you come back no more");
// find will return false, because 'road' can't be find as a substring
Assert.assertFalse(matcher.find());
}
}

View File

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

14
kotlin-libraries-2/.gitignore vendored Normal file
View File

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

View File

@ -0,0 +1 @@
## Relevant articles:

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>kotlin-libraries-2</artifactId>
<name>kotlin-libraries-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-kotlin</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../parent-kotlin</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
</properties>
</project>

View File

@ -0,0 +1,11 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>

View File

@ -0,0 +1,8 @@
package com.baeldung.kotlin.jackson
import com.fasterxml.jackson.annotation.*
@JsonInclude(JsonInclude.Include.NON_EMPTY)
data class Book(var title: String, @JsonProperty("author") var authorName: String) {
var genres: List<String>? = emptyList()
}

View File

@ -0,0 +1,3 @@
package com.baeldung.kotlin.jackson
data class Movie(var name: String, var studio: String, var rating: Float? = 1f)

View File

@ -0,0 +1,114 @@
package com.baeldung.kotlin.jackson
import org.junit.Test
import kotlin.test.assertTrue
import kotlin.test.assertFalse
import kotlin.test.assertEquals
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
class JacksonUnitTest {
//val mapper = jacksonObjectMapper()
val mapper = ObjectMapper().registerModule(KotlinModule())
@Test
fun whenSerializeMovie_thenSuccess() {
val movie = Movie("Endgame", "Marvel", 9.2f)
val serialized = mapper.writeValueAsString(movie)
val json = """{"name":"Endgame","studio":"Marvel","rating":9.2}"""
assertEquals(serialized, json)
}
@Test
fun whenDeserializeMovie_thenSuccess() {
val json = """{"name":"Endgame","studio":"Marvel","rating":9.2}"""
// val movie: Movie = mapper.readValue(json)
val movie = mapper.readValue<Movie>(json)
assertEquals(movie.name, "Endgame")
assertEquals(movie.studio, "Marvel")
assertEquals(movie.rating, 9.2f)
}
@Test
fun whenDeserializeMovieWithMissingValue_thenUseDefaultValue() {
val json = """{"name":"Endgame","studio":"Marvel"}"""
val movie: Movie = mapper.readValue(json)
assertEquals(movie.name, "Endgame")
assertEquals(movie.studio, "Marvel")
assertEquals(movie.rating, 1f)
}
@Test
fun whenSerializeMap_thenSuccess() {
val map = mapOf(1 to "one", 2 to "two")
val serialized = mapper.writeValueAsString(map)
val json = """{"1":"one","2":"two"}"""
assertEquals(serialized, json)
}
@Test
fun whenDeserializeMap_thenSuccess() {
val json = """{"1":"one","2":"two"}"""
val aMap: Map<Int,String> = mapper.readValue(json)
assertEquals(aMap[1], "one")
assertEquals(aMap[2], "two")
}
@Test
fun whenSerializeList_thenSuccess() {
val movie1 = Movie("Endgame", "Marvel", 9.2f)
val movie2 = Movie("Shazam", "Warner Bros", 7.6f)
val movieList = listOf(movie1, movie2)
val serialized = mapper.writeValueAsString(movieList)
val json = """[{"name":"Endgame","studio":"Marvel","rating":9.2},{"name":"Shazam","studio":"Warner Bros","rating":7.6}]"""
assertEquals(serialized, json)
}
@Test
fun whenDeserializeList_thenSuccess() {
val json = """[{"name":"Endgame","studio":"Marvel","rating":9.2},{"name":"Shazam","studio":"Warner Bros","rating":7.6}]"""
val movieList: List<Movie> = mapper.readValue(json)
val movie1 = Movie("Endgame", "Marvel", 9.2f)
val movie2 = Movie("Shazam", "Warner Bros", 7.6f)
assertTrue(movieList.contains(movie1))
assertTrue(movieList.contains(movie2))
}
@Test
fun whenSerializeBook_thenSuccess() {
val book = Book("Oliver Twist", "Charles Dickens")
val serialized = mapper.writeValueAsString(book)
val json = """{"title":"Oliver Twist","author":"Charles Dickens"}"""
assertEquals(serialized, json)
}
@Test
fun whenDeserializeBook_thenSuccess() {
val json = """{"title":"Oliver Twist","author":"Charles Dickens"}"""
val book: Book = mapper.readValue(json)
assertEquals(book.title, "Oliver Twist")
assertEquals(book.authorName, "Charles Dickens")
}
@Test
fun givenJsonInclude_whenSerializeBook_thenEmptyFieldExcluded() {
val book = Book("Oliver Twist", "Charles Dickens")
val serialized = mapper.writeValueAsString(book)
val json = """{"title":"Oliver Twist","author":"Charles Dickens"}"""
assertEquals(serialized, json)
}
}

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>libraries-primitive</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/it.unimi.dsi/fastutil -->
<dependency>
<groupId>it.unimi.dsi</groupId>
<artifactId>fastutil</artifactId>
<version>8.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

88
maven/profiles/pom.xml Normal file
View File

@ -0,0 +1,88 @@
<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>profiles</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>profiles</name>
<profiles>
<profile>
<id>no-tests</id>
<properties>
<maven.test.skip>true</maven.test.skip>
</properties>
</profile>
<profile>
<id>integration-tests</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>mutation-tests</id>
</profile>
<profile>
<id>active-on-jdk-11</id>
<activation>
<jdk>11</jdk>
</activation>
</profile>
<profile>
<id>active-on-windows-10</id>
<activation>
<os>
<name>windows 10</name>
<family>Windows</family>
<arch>amd64</arch>
<version>10.0</version>
</os>
</activation>
</profile>
<profile>
<id>active-on-property-environment</id>
<activation>
<property>
<name>environment</name>
<value>!test</value>
</property>
</activation>
</profile>
<profile>
<id>active-on-missing-file</id>
<activation>
<file>
<missing>target/testreport.html</missing>
</file>
</activation>
</profile>
<profile>
<id>active-on-present-file</id>
<activation>
<file>
<exists>target/artifact.jar</exists>
</file>
</activation>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-help-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>show-profiles</id>
<phase>compile</phase>
<goals>
<goal>active-profiles</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -108,6 +108,9 @@
<sourceDir>${project.basedir}/src/main/java</sourceDir>
</sourceDirs>
<jvmTarget>${java.version}</jvmTarget>
<args>
<arg>-Xjvm-default=enable</arg>
</args>
</configuration>
</execution>
<execution>

View File

@ -31,6 +31,22 @@
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
</dependency>
<!-- validation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>${javax.el-api.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>${org.glassfish.javax.el.version}</version>
</dependency>
</dependencies>
<build>
@ -47,6 +63,9 @@
<hibernate.version>5.3.7.Final</hibernate.version>
<h2database.version>1.4.196</h2database.version>
<assertj-core.version>3.8.0</assertj-core.version>
<hibernate-validator.version>5.3.3.Final</hibernate-validator.version>
<javax.el-api.version>2.2.5</javax.el-api.version>
<org.glassfish.javax.el.version>3.0.1-b08</org.glassfish.javax.el.version>
</properties>
</project>

View File

@ -9,7 +9,7 @@ public enum Strategy {
//See that the classes belongs to different packages
MAP_KEY_COLUMN_BASED(Collections.singletonList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class)),
MAP_KEY_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkey.Item.class,
com.baeldung.hibernate.persistmaps.mapkey.Order.class)),
com.baeldung.hibernate.persistmaps.mapkey.Order.class,com.baeldung.hibernate.persistmaps.mapkey.User.class)),
MAP_KEY_JOIN_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Seller.class,
com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Item.class,
com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Order.class)),

View File

@ -0,0 +1,66 @@
package com.baeldung.hibernate.persistmaps.mapkey;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Length;
@Entity
public class User {
@Id
@Column(length = 3)
private String firstName;
@Size(min = 3, max = 15)
private String middleName;
@Length(min = 3, max = 15)
private String lastName;
@Column(length = 5)
@Size(min = 3, max = 5)
private String city;
public User(String firstName, String middleName, String lastName, String city) {
super();
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.city = city;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middletName) {
this.middleName = middletName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

View File

@ -0,0 +1,81 @@
package com.baeldung.hibernate.validation;
import static org.junit.Assert.assertEquals;
import java.util.Set;
import javax.persistence.PersistenceException;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.Strategy;
import com.baeldung.hibernate.persistmaps.mapkey.User;
public class UserValidationUnitTest {
private static Validator validator;
private static SessionFactory sessionFactory;
private Session session;
private Set<ConstraintViolation<User>> constraintViolations;
@BeforeClass
public static void before() {
ValidatorFactory config = Validation.buildDefaultValidatorFactory();
validator = config.getValidator();
sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_BASED);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void whenValidationWithSizeAndInvalidMiddleName_thenConstraintViolation() {
User user = new User("john", "m", "butler", "japan");
constraintViolations = validator.validateProperty(user, "middleName");
assertEquals(constraintViolations.size(), 1);
}
@Test
public void whenValidationWithSizeAndValidMiddleName_thenNoConstraintViolation() {
User user = new User("john", "mathis", "butler", "japan");
constraintViolations = validator.validateProperty(user, "middleName");
assertEquals(constraintViolations.size(), 0);
}
@Test
public void whenValidationWithLengthAndInvalidLastName_thenConstraintViolation() {
User user = new User("john", "m", "b", "japan");
constraintViolations = validator.validateProperty(user, "lastName");
assertEquals(constraintViolations.size(), 1);
}
@Test
public void whenValidationWithLengthAndValidLastName_thenNoConstraintViolation() {
User user = new User("john", "mathis", "butler", "japan");
constraintViolations = validator.validateProperty(user, "lastName");
assertEquals(constraintViolations.size(), 0);
}
@Test(expected = PersistenceException.class)
public void whenSavingFirstNameWithInvalidFirstName_thenPersistenceException() {
User user = new User("john", "mathis", "butler", "japan");
session.save(user);
session.getTransaction()
.commit();
}
@Test
public void whenValidationWithSizeAndColumnWithValidCity_thenNoConstraintViolation() {
User user = new User("john", "mathis", "butler", "japan");
constraintViolations = validator.validateProperty(user, "city");
assertEquals(constraintViolations.size(), 0);
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.entitygraph.model;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Characteristic {
@Id
private Long id;
private String type;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
private Item item;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.entitygraph.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.OneToMany;
@Entity
@NamedEntityGraph(name = "Item.characteristics",
attributeNodes = @NamedAttributeNode("characteristics")
)
public class Item {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "item")
private List<Characteristic> characteristics = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Characteristic> getCharacteristics() {
return characteristics;
}
public void setCharacteristics(List<Characteristic> characteristics) {
this.characteristics = characteristics;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.entitygraph.repository;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.entitygraph.model.Characteristic;
public interface CharacteristicsRepository extends JpaRepository<Characteristic, Long> {
@EntityGraph(attributePaths = {"item"})
Characteristic findByType(String type);
}

View File

@ -0,0 +1,13 @@
package com.baeldung.entitygraph.repository;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.entitygraph.model.Item;
public interface ItemRepository extends JpaRepository<Item, Long> {
@EntityGraph(value = "Item.characteristics", type = EntityGraphType.FETCH)
Item findByName(String name);
}

View File

@ -0,0 +1,39 @@
package com.baeldung.entitygraph;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.entitygraph.model.Characteristic;
import com.baeldung.entitygraph.model.Item;
import com.baeldung.entitygraph.repository.CharacteristicsRepository;
import com.baeldung.entitygraph.repository.ItemRepository;
@DataJpaTest
@RunWith(SpringRunner.class)
@Sql(scripts = "/entitygraph-data.sql")
public class EntityGraphIntegrationTest {
@Autowired
private ItemRepository itemRepo;
@Autowired
private CharacteristicsRepository characteristicsRepo;
@Test
public void givenEntityGraph_whenCalled_shouldRetrunDefinedFields() {
Item item = itemRepo.findByName("Table");
assertThat(item.getId()).isEqualTo(1L);
}
@Test
public void givenAdhocEntityGraph_whenCalled_shouldRetrunDefinedFields() {
Characteristic characteristic = characteristicsRepo.findByType("Rigid");
assertThat(characteristic.getId()).isEqualTo(1L);
}
}

View File

@ -0,0 +1,7 @@
INSERT INTO Item(id,name) VALUES (1,'Table');
INSERT INTO Item(id,name) VALUES (2,'Bottle');
INSERT INTO Characteristic(id,item_id, type) VALUES (1,1,'Rigid');
INSERT INTO Characteristic(id,item_id,type) VALUES (2,1,'Big');
INSERT INTO Characteristic(id,item_id,type) VALUES (3,2,'Fragile');
INSERT INTO Characteristic(id,item_id,type) VALUES (4,2,'Small');

View File

@ -90,4 +90,8 @@
</dependency>
</dependencies>
<properties>
<start-class>com.baeldung.boot.Application</start-class>
</properties>
</project>

View File

@ -1,10 +1,11 @@
package com.baeldung;
package com.baeldung.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl;
import com.baeldung.boot.daos.impl.ExtendedRepositoryImpl;
import com.baeldung.multipledb.MultipleDbApplication;
@SpringBootApplication
@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class)

View File

@ -0,0 +1,21 @@
package com.baeldung.boot.config;
import com.baeldung.boot.services.IBarService;
import com.baeldung.boot.services.impl.BarSpringDataJpaService;
import org.springframework.context.annotation.*;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@Profile("!tc")
@EnableTransactionManagement
@EnableJpaAuditing
public class PersistenceConfiguration {
@Bean
public IBarService barSpringDataJpaService() {
return new BarSpringDataJpaService();
}
}

View File

@ -1,10 +1,11 @@
package com.baeldung.dao.repositories;
package com.baeldung.boot.daos;
import com.baeldung.domain.Article;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.baeldung.boot.domain.Article;
import java.util.Date;
import java.util.List;

View File

@ -1,8 +1,8 @@
package com.baeldung.dao.repositories;
package com.baeldung.boot.daos;
import org.springframework.stereotype.Repository;
import com.baeldung.domain.Item;
import com.baeldung.boot.domain.Item;
@Repository
public interface CustomItemRepository {

View File

@ -1,8 +1,8 @@
package com.baeldung.dao.repositories;
package com.baeldung.boot.daos;
import org.springframework.stereotype.Repository;
import com.baeldung.domain.ItemType;
import com.baeldung.boot.domain.ItemType;
@Repository
public interface CustomItemTypeRepository {

View File

@ -1,8 +1,8 @@
package com.baeldung.batchinserts.repository;
package com.baeldung.boot.daos;
import org.springframework.data.repository.CrudRepository;
import com.baeldung.batchinserts.model.Customer;
import com.baeldung.boot.domain.Customer;
/**
* JPA CrudRepository interface

View File

@ -1,4 +1,4 @@
package com.baeldung.dao.repositories;
package com.baeldung.boot.daos;
import java.io.Serializable;
import java.util.List;

View File

@ -1,6 +1,6 @@
package com.baeldung.dao.repositories;
package com.baeldung.boot.daos;
import com.baeldung.domain.Student;
import com.baeldung.boot.domain.Student;
public interface ExtendedStudentRepository extends ExtendedRepository<Student, Long> {
}

View File

@ -1,8 +1,9 @@
package com.baeldung.dao.repositories;
package com.baeldung.boot.daos;
import com.baeldung.domain.Bar;
import org.springframework.data.repository.CrudRepository;
import com.baeldung.boot.domain.Bar;
import java.io.Serializable;
public interface IBarCrudRepository extends CrudRepository<Bar, Serializable> {

View File

@ -1,10 +1,11 @@
package com.baeldung.dao;
package com.baeldung.boot.daos;
import com.baeldung.domain.Foo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.baeldung.boot.domain.Foo;
public interface IFooDao extends JpaRepository<Foo, Long> {
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")

View File

@ -1,7 +1,8 @@
package com.baeldung.dao.repositories;
package com.baeldung.boot.daos;
import com.baeldung.domain.MerchandiseEntity;
import org.springframework.data.repository.CrudRepository;
import com.baeldung.boot.domain.MerchandiseEntity;
public interface InventoryRepository extends CrudRepository<MerchandiseEntity, Long> {
}

View File

@ -1,9 +1,9 @@
package com.baeldung.dao.repositories;
package com.baeldung.boot.daos;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.baeldung.domain.ItemType;
import com.baeldung.boot.domain.ItemType;
@Repository
public interface ItemTypeRepository extends JpaRepository<ItemType, Long>, CustomItemTypeRepository, CustomItemRepository {

View File

@ -1,9 +1,9 @@
package com.baeldung.dao.repositories;
package com.baeldung.boot.daos;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.baeldung.domain.Location;
import com.baeldung.boot.domain.Location;
@Repository
public interface LocationRepository extends JpaRepository<Location, Long> {

View File

@ -1,10 +1,10 @@
package com.baeldung.dao.repositories;
package com.baeldung.boot.daos;
import java.util.Optional;
import org.springframework.data.repository.Repository;
import com.baeldung.domain.Location;
import com.baeldung.boot.domain.Location;
@org.springframework.stereotype.Repository
public interface ReadOnlyLocationRepository extends Repository<Location, Long> {

View File

@ -1,11 +1,11 @@
package com.baeldung.dao.repositories;
package com.baeldung.boot.daos;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.baeldung.domain.Store;
import com.baeldung.boot.domain.Store;
@Repository
public interface StoreRepository extends JpaRepository<Store, Long> {

View File

@ -1,12 +1,12 @@
package com.baeldung.dao.repositories.impl;
package com.baeldung.boot.daos.impl;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.baeldung.dao.repositories.CustomItemRepository;
import com.baeldung.domain.Item;
import com.baeldung.boot.daos.CustomItemRepository;
import com.baeldung.boot.domain.Item;
@Repository
public class CustomItemRepositoryImpl implements CustomItemRepository {

View File

@ -1,4 +1,4 @@
package com.baeldung.dao.repositories.impl;
package com.baeldung.boot.daos.impl;
import javax.persistence.EntityManager;
@ -7,8 +7,8 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.baeldung.domain.ItemType;
import com.baeldung.dao.repositories.CustomItemTypeRepository;
import com.baeldung.boot.daos.CustomItemTypeRepository;
import com.baeldung.boot.domain.ItemType;
@Repository
public class CustomItemTypeRepositoryImpl implements CustomItemTypeRepository {

View File

@ -1,4 +1,4 @@
package com.baeldung.dao.repositories.impl;
package com.baeldung.boot.daos.impl;
import java.io.Serializable;
import java.util.List;
@ -10,10 +10,11 @@ import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import com.baeldung.dao.repositories.ExtendedRepository;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import com.baeldung.boot.daos.ExtendedRepository;
public class ExtendedRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements ExtendedRepository<T, ID> {
private EntityManager entityManager;

View File

@ -1,8 +1,9 @@
package com.baeldung.dao.repositories.impl;
package com.baeldung.boot.daos.impl;
import com.baeldung.domain.Person;
import org.springframework.stereotype.Repository;
import com.baeldung.boot.domain.Person;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

View File

@ -1,8 +1,9 @@
package com.baeldung.dao.repositories.user;
package com.baeldung.boot.daos.user;
import com.baeldung.domain.user.Possession;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.boot.domain.Possession;
public interface PossessionRepository extends JpaRepository<Possession, Long> {
}

View File

@ -1,6 +1,5 @@
package com.baeldung.dao.repositories.user;
package com.baeldung.boot.daos.user;
import com.baeldung.domain.user.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@ -9,6 +8,8 @@ import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.baeldung.boot.domain.User;
import java.time.LocalDate;
import java.util.Collection;
import java.util.List;
@ -18,12 +19,12 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
Stream<User> findAllByName(String name);
@Query("select u from User u where u.email like '%@gmail.com'")
List<User> findUsersWithGmailAddress();
@Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();
@Query("select u from User u where u.email like '%@gmail.com'")
List<User> findUsersWithGmailAddress();
@Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
Collection<User> findAllActiveUsersNative();
@ -89,11 +90,10 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from User u where u.active = false")
@Query("delete User u where u.active = false")
int deleteDeactivatedUsers();
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(value = "alter table Users add column deleted int(1) not null default 0", nativeQuery = true)
@Query(value = "alter table USERS.USERS add column deleted int(1) not null default 0", nativeQuery = true)
void addDeletedColumn();
}

View File

@ -1,11 +1,11 @@
package com.baeldung.dao.repositories.user;
package com.baeldung.boot.daos.user;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import com.baeldung.domain.user.User;
import com.baeldung.boot.domain.User;
public interface UserRepositoryCustom {
List<User> findUserByEmails(Set<String> emails);

View File

@ -1,4 +1,4 @@
package com.baeldung.dao.repositories.user;
package com.baeldung.boot.daos.user;
import java.util.ArrayList;
import java.util.Collection;
@ -15,7 +15,7 @@ import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.baeldung.domain.user.User;
import com.baeldung.boot.domain.User;
public class UserRepositoryCustomImpl implements UserRepositoryCustom {

View File

@ -1,7 +1,7 @@
/**
*
*/
package com.baeldung.ddd.event;
package com.baeldung.boot.ddd.event;
import javax.persistence.Entity;
import javax.persistence.Id;

View File

@ -1,7 +1,7 @@
/**
*
*/
package com.baeldung.ddd.event;
package com.baeldung.boot.ddd.event;
import java.util.ArrayList;
import java.util.Collection;

View File

@ -1,7 +1,7 @@
/**
*
*/
package com.baeldung.ddd.event;
package com.baeldung.boot.ddd.event;
import org.springframework.data.repository.CrudRepository;

View File

@ -1,7 +1,7 @@
/**
*
*/
package com.baeldung.ddd.event;
package com.baeldung.boot.ddd.event;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;

View File

@ -1,7 +1,7 @@
/**
*
*/
package com.baeldung.ddd.event;
package com.baeldung.boot.ddd.event;
import org.springframework.data.repository.CrudRepository;

View File

@ -1,7 +1,7 @@
/**
*
*/
package com.baeldung.ddd.event;
package com.baeldung.boot.ddd.event;
import org.springframework.data.repository.CrudRepository;

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