This commit is contained in:
Chirag Dewan 2019-05-04 13:47:06 +05:30
commit e800767a96
218 changed files with 2822 additions and 491 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>

25
core-java-8-2/.gitignore vendored Normal file
View File

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

View File

@ -21,9 +21,16 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<icu.version>64.2</icu.version>
</properties>
<dependencies>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>${icu.version}</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,18 @@
package com.baeldung.jarArguments;
public class JarExample {
public static void main(String[] args) {
System.out.println("Hello Baeldung Reader in JarExample!");
if(args == null) {
System.out.println("You have not provided any arguments!");
}else {
System.out.println("There are "+args.length+" argument(s)!");
for(int i=0; i<args.length; i++) {
System.out.println("Argument("+(i+1)+"):" + args[i]);
}
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.localization;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class App {
/**
* Runs all available formatter
* @throws ParseException
*/
public static void main(String[] args) {
List<Locale> locales = Arrays.asList(new Locale[] { Locale.UK, Locale.ITALY, Locale.FRANCE, Locale.forLanguageTag("pl-PL") });
Localization.run(locales);
JavaSEFormat.run(locales);
ICUFormat.run(locales);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.localization;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import com.ibm.icu.text.MessageFormat;
public class ICUFormat {
public static String getLabel(Locale locale, Object[] data) {
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
String format = bundle.getString("label-icu");
MessageFormat formatter = new MessageFormat(format, locale);
return formatter.format(data);
}
public static void run(List<Locale> locales) {
System.out.println("ICU formatter");
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 0 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 1 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 2 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 3 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 0 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 1 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 2 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 3 })));
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.localization;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class JavaSEFormat {
public static String getLabel(Locale locale, Object[] data) {
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
final String pattern = bundle.getString("label");
final MessageFormat formatter = new MessageFormat(pattern, locale);
return formatter.format(data);
}
public static void run(List<Locale> locales) {
System.out.println("Java formatter");
final Date date = new Date(System.currentTimeMillis());
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 0 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 2 })));
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.localization;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class Localization {
public static String getLabel(Locale locale) {
final ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
return bundle.getString("label");
}
public static void run(List<Locale> locales) {
locales.forEach(locale -> System.out.println(getLabel(locale)));
}
}

View File

@ -0,0 +1 @@
Main-Class: com.baeldung.jarArguments.JarExample

View File

@ -0,0 +1,2 @@
label=On {0, date, short} {1} has sent you {2, choice, 0#no messages|1#a message|2#two messages|2<{2,number,integer} messages}.
label-icu={0} has sent you {2, plural, =0 {no messages} =1 {a message} other {{2, number, integer} messages}}.

View File

@ -0,0 +1,2 @@
label={0, date, short}, {1}{2, choice, 0# ne|0<} vous a envoyé {2, choice, 0#aucun message|1#un message|2#deux messages|2<{2,number,integer} messages}.
label-icu={0} {2, plural, =0 {ne } other {}}vous a envoyé {2, plural, =0 {aucun message} =1 {un message} other {{2, number, integer} messages}}.

View File

@ -0,0 +1,2 @@
label={0, date, short} {1} ti ha inviato {2, choice, 0#nessun messagio|1#un messaggio|2#due messaggi|2<{2, number, integer} messaggi}.
label-icu={0} {2, plural, =0 {non } other {}}ti ha inviato {2, plural, =0 {nessun messaggio} =1 {un messaggio} other {{2, number, integer} messaggi}}.

View File

@ -0,0 +1,2 @@
label=W {0, date, short} {1}{2, choice, 0# nie|0<} wys\u0142a\u0142a ci {2, choice, 0#\u017Cadnych wiadomo\u015Bci|1#wiadomo\u015B\u0107|2#dwie wiadomo\u015Bci|2<{2, number, integer} wiadomo\u015Bci}.
label-icu={0} {2, plural, =0 {nie } other {}}{1, select, male {wys\u0142a\u0142} female {wys\u0142a\u0142a} other {wys\u0142a\u0142o}} ci {2, plural, =0 {\u017Cadnej wiadomo\u015Bci} =1 {wiadomo\u015B\u0107} other {{2, number, integer} wiadomo\u015Bci}}.

View File

@ -0,0 +1 @@
label=Alice has sent you a message.

View File

@ -0,0 +1 @@
label=Alice vous a envoyé un message.

View File

@ -0,0 +1 @@
label=Alice ti ha inviato un messaggio.

View File

@ -0,0 +1 @@
label=Alice wys\u0142a\u0142a ci wiadomo\u015B\u0107.

View File

@ -0,0 +1,74 @@
package com.baeldung.localization;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import org.junit.Test;
import com.baeldung.localization.ICUFormat;
public class ICUFormatUnitTest {
@Test
public void givenInUK_whenAliceSendsNothing_thenCorrectMessage() {
assertEquals("Alice has sent you no messages.", ICUFormat.getLabel(Locale.UK, new Object[] { "Alice", "female", 0 }));
}
@Test
public void givenInUK_whenAliceSendsOneMessage_thenCorrectMessage() {
assertEquals("Alice has sent you a message.", ICUFormat.getLabel(Locale.UK, new Object[] { "Alice", "female", 1 }));
}
@Test
public void givenInUK_whenBobSendsSixMessages_thenCorrectMessage() {
assertEquals("Bob has sent you 6 messages.", ICUFormat.getLabel(Locale.UK, new Object[] { "Bob", "male", 6 }));
}
@Test
public void givenInItaly_whenAliceSendsNothing_thenCorrectMessage() {
assertEquals("Alice non ti ha inviato nessun messaggio.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Alice", "female", 0 }));
}
@Test
public void givenInItaly_whenAliceSendsOneMessage_thenCorrectMessage() {
assertEquals("Alice ti ha inviato un messaggio.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Alice", "female", 1 }));
}
@Test
public void givenInItaly_whenBobSendsSixMessages_thenCorrectMessage() {
assertEquals("Bob ti ha inviato 6 messaggi.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Bob", "male", 6 }));
}
@Test
public void givenInFrance_whenAliceSendsNothing_thenCorrectMessage() {
assertEquals("Alice ne vous a envoyé aucun message.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Alice", "female", 0 }));
}
@Test
public void givenInFrance_whenAliceSendsOneMessage_thenCorrectMessage() {
assertEquals("Alice vous a envoyé un message.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Alice", "female", 1 }));
}
@Test
public void givenInFrance_whenBobSendsSixMessages_thenCorrectMessage() {
assertEquals("Bob vous a envoyé 6 messages.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Bob", "male", 6 }));
}
@Test
public void givenInPoland_whenAliceSendsNothing_thenCorrectMessage() {
assertEquals("Alice nie wysłała ci żadnej wiadomości.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Alice", "female", 0 }));
}
@Test
public void givenInPoland_whenAliceSendsOneMessage_thenCorrectMessage() {
assertEquals("Alice wysłała ci wiadomość.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Alice", "female", 1 }));
}
@Test
public void givenInPoland_whenBobSendsSixMessages_thenCorrectMessage() {
assertEquals("Bob wysłał ci 6 wiadomości.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Bob", "male", 6 }));
}
}

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,27 @@
<?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>
<parent>
<groupId>com.baeldung.multimodulemavenproject</groupId>
<artifactId>multimodulemavenproject</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>9</maven.compiler.source>
<maven.compiler.target>9</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.daomodule;
import java.util.List;
import java.util.Optional;
public interface Dao<T> {
Optional<T> findById(int id);
List<T> findAll();
}

View File

@ -0,0 +1,3 @@
module com.baeldung.daomodule {
exports com.baeldung.daomodule;
}

View File

@ -0,0 +1,28 @@
<?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>
<parent>
<groupId>com.baeldung.multimodulemavenproject</groupId>
<artifactId>multimodulemavenproject</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>9</maven.compiler.source>
<maven.compiler.target>9</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,19 @@
package com.baeldung.entitymodule;
public class User {
private final String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" + "name=" + name + '}';
}
}

View File

@ -0,0 +1,3 @@
module com.baeldung.entitymodule {
exports com.baeldung.entitymodule;
}

View File

@ -0,0 +1,45 @@
<?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>
<parent>
<groupId>com.baeldung.multimodulemavenproject</groupId>
<artifactId>multimodulemavenproject</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.mainappmodule</groupId>
<artifactId>mainappmodule</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.baeldung.userdaomodule</groupId>
<artifactId>userdaomodule</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>9</maven.compiler.source>
<maven.compiler.target>9</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,19 @@
package com.baeldung.mainappmodule;
import com.baeldung.daomodule.Dao;
import com.baeldung.entitymodule.User;
import com.baeldung.userdaomodule.UserDao;
import java.util.HashMap;
import java.util.Map;
public class Application {
public static void main(String args[]) {
Map<Integer, User> users = new HashMap<>();
users.put(1, new User("Julie"));
users.put(2, new User("David"));
Dao userDao = new UserDao(users);
userDao.findAll().forEach(System.out::println);
}
}

View File

@ -0,0 +1,8 @@
module com.baeldung.mainppmodule {
requires com.baeldung.entitymodule;
requires com.baeldung.daomodule;
requires com.baeldung.userdaomodule;
uses com.baeldung.userdaomodule.UserDao;
}

View File

@ -0,0 +1,62 @@
<?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.multimodulemavenproject</groupId>
<artifactId>multimodulemavenproject</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<name>multimodulemavenproject</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.12.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<configuration>
<source>1.9</source>
<target>1.9</target>
</configuration>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>entitymodule</module>
<module>daomodule</module>
<module>userdaomodule</module>
<module>mainappmodule</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,41 @@
<?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>
<parent>
<groupId>com.baeldung.multimodulemavenproject</groupId>
<artifactId>multimodulemavenproject</artifactId>
<version>1.0</version>
</parent>
<groupId>com.baeldung.userdaomodule</groupId>
<artifactId>userdaomodule</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>9</maven.compiler.source>
<maven.compiler.target>9</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.userdaomodule;
import com.baeldung.daomodule.Dao;
import com.baeldung.entitymodule.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class UserDao implements Dao<User> {
private final Map<Integer, User> users;
public UserDao() {
users = new HashMap<>();
}
public UserDao(Map<Integer, User> users) {
this.users = users;
}
@Override
public List<User> findAll() {
return new ArrayList<>(users.values());
}
@Override
public Optional<User> findById(int id) {
return Optional.ofNullable(users.get(id));
}
}

View File

@ -0,0 +1,6 @@
module com.baeldung.userdaomodule {
requires com.baeldung.entitymodule;
requires com.baeldung.daomodule;
provides com.baeldung.daomodule.Dao with com.baeldung.userdaomodule.UserDao;
exports com.baeldung.userdaomodule;
}

View File

@ -2,6 +2,7 @@
<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.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<name>core-java-modules</name>
<packaging>pom</packaging>
@ -15,5 +16,5 @@
<modules>
<module>pre-jpms</module>
</modules>
</project>
</project>

View File

@ -59,18 +59,43 @@ public class Graph {
Vertex(String label) {
this.label = label;
}
@Override
public boolean equals(Object obj) {
Vertex vertex = (Vertex) obj;
return vertex.label == label;
}
@Override
public int hashCode() {
return label.hashCode();
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((label == null) ? 0 : label.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vertex other = (Vertex) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (label == null) {
if (other.label != null)
return false;
} else if (!label.equals(other.label))
return false;
return true;
}
@Override
public String toString() {
return label;
}
private Graph getOuterType() {
return Graph.this;
}
}
}

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

@ -17,4 +17,8 @@ class FileReader {
File(fileName).inputStream().readBytes().toString(Charsets.UTF_8)
fun readFileDirectlyAsText(fileName: String): String = File(fileName).readText(Charsets.UTF_8)
fun readFileUsingGetResource(fileName: String) = this::class.java.getResource(fileName).readText(Charsets.UTF_8)
fun readFileAsLinesUsingGetResourceAsStream(fileName: String) = this::class.java.getResourceAsStream(fileName).bufferedReader().readLines()
}

View File

@ -48,4 +48,20 @@ internal class FileReaderTest {
assertTrue { text.contains("Hello to Kotlin") }
}
@Test
fun whenReadFileAsTextUsingGetResource_thenCorrect() {
val text = fileReader.readFileUsingGetResource("/Kotlin.in")
assertTrue { text.contains("1. Concise") }
}
@Test
fun whenReadFileUsingGetResourceAsStream_thenCorrect() {
val lines = fileReader.readFileAsLinesUsingGetResourceAsStream("/Kotlin.in")
assertTrue { lines.contains("3. Interoperable") }
}
}

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;
@ -81,5 +100,28 @@ public class HttpClientTimeoutLiveTest {
final HttpGet request = new HttpGet("http://www.google.com:81");
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,14 @@
package com.baeldung.jpadefaultvalues.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application {
private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.jpadefaultvalues.application;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
@Column(columnDefinition = "varchar(255) default 'John Snow'")
private String name = "John Snow";
@Column(columnDefinition = "integer default 25")
private Integer age = 25;
@Column(columnDefinition = "boolean default false")
private Boolean locked = false;
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
}

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