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

This commit is contained in:
Dhawal Kapil 2018-08-16 14:34:19 +05:30
commit 6019d03fbf
67 changed files with 1588 additions and 601 deletions

View File

@ -0,0 +1,78 @@
package com.baeldung.collection;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StreamOperateAndRemoveUnitTest {
private List<Item> itemList;
@Before
public void setup() {
itemList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
itemList.add(new Item(i));
}
}
@Test
public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() {
final List<Item> filteredList = itemList.stream().filter(item -> item.isQualified())
.collect(Collectors.toList());
Assert.assertEquals(5, filteredList.size());
}
@Test
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
itemList.stream().filter(item -> item.isQualified()).forEach(item -> item.operate());
itemList.removeIf(item -> item.isQualified());
Assert.assertEquals(5, itemList.size());
}
@Test
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() {
final List<Item> operatedList = new ArrayList<>();
itemList.stream().filter(item -> item.isQualified()).forEach(item -> {
item.operate();
operatedList.add(item);
});
itemList.removeAll(operatedList);
Assert.assertEquals(5, itemList.size());
}
class Item {
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
private final int value;
public Item(final int value) {
this.value = value;
}
public boolean isQualified() {
return value % 2 == 0;
}
public void operate() {
logger.info("Even Number: " + this.value);
}
}
}

View File

@ -18,7 +18,7 @@ public class FilenameFilterManualTest {
@BeforeClass
public static void setupClass() {
directory = new File(FilenameFilterManualTest.class.getClassLoader()
.getResource("testFolder")
.getResource("fileNameFilterManualTestFolder")
.getFile());
}

View File

@ -39,6 +39,16 @@
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.spring-web.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${springframework.boot.spring-boot-starter.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-persistence</finalName>
@ -55,5 +65,7 @@
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
<HikariCP.version>3.2.0</HikariCP.version>
<c3p0.version>0.9.5.2</c3p0.version>
<springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version>
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
</properties>
</project>

View File

@ -127,11 +127,6 @@
<artifactId>spring-web</artifactId>
<version>${springframework.spring-web.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${springframework.boot.spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
@ -532,7 +527,6 @@
<!-- maven plugins -->
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
<springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<h2database.version>1.4.197</h2database.version>

View File

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

View File

@ -0,0 +1,18 @@
package com.baeldung.keywords.finalize;
public class FinalizeObject {
@Override
protected void finalize() throws Throwable {
System.out.println("Execute finalize method");
super.finalize();
}
public static void main(String[] args) throws Exception {
FinalizeObject object = new FinalizeObject();
object = null;
System.gc();
Thread.sleep(1000);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.keywords.finalkeyword;
public final class Child extends Parent {
@Override
void method1(int arg1, final int arg2) {
// OK
}
/* @Override
void method2() {
// Compilation error
}*/
}

View File

@ -0,0 +1,5 @@
package com.baeldung.keywords.finalkeyword;
/*public class GrandChild extends Child {
// Compilation error
}*/

View File

@ -0,0 +1,23 @@
package com.baeldung.keywords.finalkeyword;
public class Parent {
int field1 = 1;
final int field2 = 2;
Parent() {
field1 = 2; // OK
// field2 = 3; // Compilation error
}
void method1(int arg1, final int arg2) {
arg1 = 2; // OK
// arg2 = 3; // Compilation error
}
final void method2() {
final int localVar = 2; // OK
// localVar = 3; // Compilation error
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.keywords.finallykeyword;
public class FinallyExample {
public static void main(String args[]) throws Exception {
try {
System.out.println("Execute try block");
throw new Exception();
} catch (Exception e) {
System.out.println("Execute catch block");
} finally {
System.out.println("Execute finally block");
}
try {
System.out.println("Execute try block");
} finally {
System.out.println("Execute finally block");
}
try {
System.out.println("Execute try block");
throw new Exception();
} finally {
System.out.println("Execute finally block");
}
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.regexp.datepattern.optmization;
public class OptimizedMatcher {
}

View File

@ -16,8 +16,11 @@ import org.slf4j.LoggerFactory;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.List;
/**
* Created by madhumita.g on 01-08-2018.
*/
@ -66,20 +69,18 @@ public class AnimalUnitTest {
int testValue = 3;
animal.makeNoise(testValue);
verify(mockAppender).doAppend(captorLoggingEvent.capture());
verify(mockAppender,times(3)).doAppend(captorLoggingEvent.capture());
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
final List<LoggingEvent> loggingEvents = captorLoggingEvent.getAllValues();
while (testValue != 0) {
for(LoggingEvent loggingEvent : loggingEvents)
{
assertThat(loggingEvent.getLevel(), is(Level.INFO));
assertThat(loggingEvent.getFormattedMessage(),
is("generic animal noise countdown 3\n"
+ "generic animal noise countdown 2\n"
+ "generic animal noise countdown 1\n"));
testValue-=1;
is("generic animal noise countdown "+testValue));
testValue--;
}
}

View File

@ -9,28 +9,15 @@ import java.util.stream.Stream;
import lombok.extern.java.Log;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@Log
public class ListInitializationUnitTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void givenAnonymousInnerClass_thenInitialiseList() {
List<String> cities = new ArrayList() {
// Inside declaration of the subclass
// You can have multiple initializer block
{
log.info("Inside the first initializer block.");
}
{
log.info("Inside the second initializer block.");
add("New York");
add("Rio");
add("Tokyo");
@ -47,11 +34,10 @@ public class ListInitializationUnitTest {
Assert.assertTrue(list.contains("foo"));
}
@Test
@Test(expected = UnsupportedOperationException.class)
public void givenArraysAsList_whenAdd_thenUnsupportedException() {
List<String> list = Arrays.asList("foo", "bar");
exception.expect(UnsupportedOperationException.class);
list.add("baz");
}

View File

@ -0,0 +1,109 @@
package com.baeldung.regexp.optmization;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertTrue;
public class OptimizedMatcherUnitTest {
private long time;
private long mstimePreCompiled;
private long mstimeNotPreCompiled;
private String action;
private List<String> items;
@Before
public void setup() {
Random random = new Random();
items = new ArrayList<String>();
long average = 0;
for (int i = 0; i < 100000; ++i) {
StringBuilder s = new StringBuilder();
int characters = random.nextInt(7) + 1;
for (int k = 0; k < characters; ++ k) {
char c = (char)(random.nextInt('Z' - 'A') + 'A');
int rep = random.nextInt(95) + 5;
for (int j = 0; j < rep; ++ j)
s.append(c);
average += rep;
}
items.add(s.toString());
}
average /= 100000;
System.out.println("generated data, average length: " + average);
}
@Test
public void givenANotPreCompiledAndAPreCompiledPatternA_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
testPatterns("A*");
assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
}
@Test
public void givenANotPreCompiledAndAPreCompiledPatternABC_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
testPatterns("A*B*C*");
assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
}
@Test
public void givenANotPreCompiledAndAPreCompiledPatternECWF_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
testPatterns("E*C*W*F*");
assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
}
private void testPatterns(String regex) {
time = System.nanoTime();
int matched = 0;
int unmatched = 0;
for (String item : this.items) {
if (item.matches(regex)) {
++matched;
}
else {
++unmatched;
}
}
this.action = "uncompiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
this.mstimeNotPreCompiled = (System.nanoTime() - time) / 1000000;
System.out.println(this.action + ": " + mstimeNotPreCompiled + "ms");
time = System.nanoTime();
Matcher matcher = Pattern.compile(regex).matcher("");
matched = 0;
unmatched = 0;
for (String item : this.items) {
if (matcher.reset(item).matches()) {
++matched;
}
else {
++unmatched;
}
}
this.action = "compiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
this.mstimePreCompiled = (System.nanoTime() - time) / 1000000;
System.out.println(this.action + ": " + mstimePreCompiled + "ms");
}
}

View File

@ -1,297 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<profiles version="12">
<profile kind="CodeFormatterProfile" name="newsx" version="12">
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="8"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="260"/>
<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_lambda_body" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.compiler.source" value="1.8"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.8"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.8"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="260"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
</profile>
<profile kind="CodeFormatterProfile" name="updated-formatter" version="12">
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>

View File

@ -0,0 +1,26 @@
package com.baeldung.hibernate.lifecycle;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class DirtyDataInspector extends EmptyInterceptor {
private static final ArrayList<FootballPlayer> dirtyEntities = new ArrayList<>();
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
dirtyEntities.add((FootballPlayer) entity);
return true;
}
public static List<FootballPlayer> getDirtyEntities() {
return dirtyEntities;
}
public static void clearDirtyEntitites() {
dirtyEntities.clear();
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.hibernate.lifecycle;
import javax.persistence.*;
@Entity
@Table(name = "Football_Player")
public class FootballPlayer {
@Id
@GeneratedValue
private long id;
@Column
private String name;
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;
}
@Override
public String toString() {
return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}

View File

@ -0,0 +1,96 @@
package com.baeldung.hibernate.lifecycle;
import org.h2.tools.RunScript;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.service.ServiceRegistry;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
public class HibernateLifecycleUtil {
private static SessionFactory sessionFactory;
private static Connection connection;
public static void init() throws Exception {
Properties hbConfigProp = getHibernateProperties();
Class.forName(hbConfigProp.getProperty("hibernate.connection.driver_class"));
connection = DriverManager.getConnection(hbConfigProp.getProperty("hibernate.connection.url"), hbConfigProp.getProperty("hibernate.connection.username"), hbConfigProp.getProperty("hibernate.connection.password"));
try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lifecycle-init.sql");
InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) {
RunScript.execute(connection, h2InitReader);
}
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(new DirtyDataInspector()).build();
}
public static void tearDown() throws Exception {
sessionFactory.close();
connection.close();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(FootballPlayer.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getHibernateProperties();
return new StandardServiceRegistryBuilder().applySettings(properties).build();
}
private static Properties getHibernateProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties");
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
public static List<EntityEntry> getManagedEntities(Session session) {
Map.Entry<Object, EntityEntry>[] entries = ((SessionImplementor) session).getPersistenceContext().reentrantSafeEntityEntries();
return Arrays.stream(entries).map(e -> e.getValue()).collect(Collectors.toList());
}
public static Transaction startTransaction(Session s) {
Transaction tx = s.getTransaction();
tx.begin();
return tx;
}
public static int queryCount(String query) throws Exception {
try (ResultSet rs = connection.createStatement().executeQuery(query)) {
rs.next();
return rs.getInt(1);
}
}
}

View File

@ -58,5 +58,4 @@ public class HibernateInterceptorUnitTest {
transaction.commit();
session.close();
}
}

View File

@ -0,0 +1,164 @@
package com.baeldung.hibernate.lifecycle;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.engine.spi.Status;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
import static com.baeldung.hibernate.lifecycle.DirtyDataInspector.getDirtyEntities;
import static com.baeldung.hibernate.lifecycle.HibernateLifecycleUtil.*;
import static org.assertj.core.api.Assertions.assertThat;
public class HibernateLifecycleUnitTest {
@BeforeClass
public static void setup() throws Exception {
HibernateLifecycleUtil.init();
}
@AfterClass
public static void tearDown() throws Exception {
HibernateLifecycleUtil.tearDown();
}
@Before
public void beforeMethod() {
DirtyDataInspector.clearDirtyEntitites();
}
@Test
public void whenEntityLoaded_thenEntityManaged() throws Exception {
SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session);
assertThat(getManagedEntities(session)).isEmpty();
List<FootballPlayer> players = session.createQuery("from FootballPlayer").getResultList();
assertThat(getManagedEntities(session)).size().isEqualTo(3);
assertThat(getDirtyEntities()).isEmpty();
FootballPlayer gigiBuffon = players.stream().filter(p -> p.getId() == 3).findFirst().get();
gigiBuffon.setName("Gianluigi Buffon");
transaction.commit();
assertThat(getDirtyEntities()).size().isEqualTo(1);
assertThat(getDirtyEntities().get(0).getId()).isEqualTo(3);
assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Gianluigi Buffon");
}
}
@Test
public void whenDetached_thenNotTracked() throws Exception {
SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session);
FootballPlayer cr7 = session.get(FootballPlayer.class, 1L);
assertThat(getManagedEntities(session)).size().isEqualTo(1);
assertThat(getManagedEntities(session).get(0).getId()).isEqualTo(cr7.getId());
session.evict(cr7);
assertThat(getManagedEntities(session)).size().isEqualTo(0);
cr7.setName("CR7");
transaction.commit();
assertThat(getDirtyEntities()).isEmpty();
}
}
@Test
public void whenReattached_thenTrackedAgain() throws Exception {
SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session);
FootballPlayer messi = session.get(FootballPlayer.class, 2L);
session.evict(messi);
messi.setName("Leo Messi");
transaction.commit();
assertThat(getDirtyEntities()).isEmpty();
transaction = startTransaction(session);
session.update(messi);
transaction.commit();
assertThat(getDirtyEntities()).size().isEqualTo(1);
assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Leo Messi");
}
}
@Test
public void givenNewEntityWithID_whenReattached_thenManaged() throws Exception {
SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session);
FootballPlayer gigi = new FootballPlayer();
gigi.setId(3);
gigi.setName("Gigi the Legend");
session.update(gigi);
assertThat(getManagedEntities(session)).size().isEqualTo(1);
transaction.commit();
assertThat(getDirtyEntities()).size().isEqualTo(1);
}
}
@Test
public void givenTransientEntity_whenSave_thenManaged() throws Exception {
SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session);
FootballPlayer neymar = new FootballPlayer();
neymar.setName("Neymar");
session.save(neymar);
assertThat(getManagedEntities(session)).size().isEqualTo(1);
assertThat(neymar.getId()).isNotNull();
int count = queryCount("select count(*) from Football_Player where name='Neymar'");
assertThat(count).isEqualTo(0);
transaction.commit();
count = queryCount("select count(*) from Football_Player where name='Neymar'");
assertThat(count).isEqualTo(1);
transaction = startTransaction(session);
session.delete(neymar);
transaction.commit();
}
}
@Test()
public void whenDelete_thenMarkDeleted() throws Exception {
SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session);
FootballPlayer neymar = new FootballPlayer();
neymar.setName("Neymar");
session.save(neymar);
transaction.commit();
transaction = startTransaction(session);
session.delete(neymar);
assertThat(getManagedEntities(session).get(0).getStatus()).isEqualTo(Status.DELETED);
transaction.commit();
}
}
}

View File

@ -0,0 +1,9 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:lifecycledb;DB_CLOSE_DELAY=-1;
hibernate.connection.username=sa
hibernate.connection.password=
hibernate.connection.autocommit=true
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=validate

View File

@ -0,0 +1,25 @@
create sequence hibernate_sequence start with 1 increment by 1;
create table Football_Player (
id bigint not null,
name varchar(255),
primary key (id)
);
insert into
Football_Player
(name, id)
values
('Cristiano Ronaldo', next value for hibernate_sequence);
insert into
Football_Player
(name, id)
values
('Lionel Messi', next value for hibernate_sequence);
insert into
Football_Player
(name, id)
values
('Gigi Buffon', next value for hibernate_sequence);

View File

@ -1,127 +1,151 @@
<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>maven</artifactId>
<version>0.0.1-SNAPSHOT</version>
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>maven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven.resources.version}</version>
<configuration>
<outputDirectory>output-resources</outputDirectory>
<resources>
<resource>
<directory>input-resources</directory>
<excludes>
<exclude>*.png</exclude>
</excludes>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerArgs>
<arg>-Xlint:unchecked</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>DataTest.java</exclude>
</excludes>
<includes>
<include>TestFail.java</include>
<include>DataCheck.java</include>
</includes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven.failsafe.version}</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<!-- configuration similar to surefire -->
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-verifier-plugin</artifactId>
<version>${maven.verifier.version}</version>
<configuration>
<verificationFile>input-resources/verifications.xml</verificationFile>
</configuration>
<executions>
<execution>
<goals>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>${maven.clean.version}</version>
<configuration>
<filesets>
<fileset>
<directory>output-resources</directory>
</fileset>
</filesets>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>${maven.build.helper.version}</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/another-src</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven.resources.version}</version>
<configuration>
<outputDirectory>output-resources</outputDirectory>
<resources>
<resource>
<directory>input-resources</directory>
<excludes>
<exclude>*.png</exclude>
</excludes>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerArgs>
<arg>-Xlint:unchecked</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>DataTest.java</exclude>
</excludes>
<includes>
<include>TestFail.java</include>
<include>DataCheck.java</include>
</includes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven.failsafe.version}</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<!-- configuration similar to surefire -->
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-verifier-plugin</artifactId>
<version>${maven.verifier.version}</version>
<configuration>
<verificationFile>input-resources/verifications.xml</verificationFile>
</configuration>
<executions>
<execution>
<goals>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>${maven.clean.version}</version>
<configuration>
<filesets>
<fileset>
<directory>output-resources</directory>
</fileset>
</filesets>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>${maven.build.helper.version}</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/another-src</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<maven.resources.version>3.0.2</maven.resources.version>
<maven.failsafe.version>2.21.0</maven.failsafe.version>
<maven.verifier.version>1.1</maven.verifier.version>
<maven.clean.version>3.0.0</maven.clean.version>
<maven.build.helper.version>3.0.0</maven.build.helper.version>
<resources.name>Baeldung</resources.name>
</properties>
<profiles>
<profile>
<id>default</id>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>DataTest.java</exclude>
</excludes>
<includes>
<include>TestFail.java</include>
<include>DataCheck.java</include>
</includes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<maven.resources.version>3.0.2</maven.resources.version>
<maven.failsafe.version>2.21.0</maven.failsafe.version>
<maven.verifier.version>1.1</maven.verifier.version>
<maven.clean.version>3.0.0</maven.clean.version>
<maven.build.helper.version>3.0.0</maven.build.helper.version>
<resources.name>Baeldung</resources.name>
</properties>
</project>

View File

@ -31,6 +31,7 @@
<module>spring-cloud-zuul-eureka-integration</module>
<module>spring-cloud-contract</module>
<module>spring-cloud-kubernetes</module>
<module>spring-cloud-archaius</module>
</modules>
<build>

View File

@ -0,0 +1,14 @@
# Spring Cloud Archaius
#### Basic Config
This service has the basic, out-of-the-box Spring Cloud Netflix Archaius configuration.
#### Extra Configs
This service customizes some properties supported by Archaius.
These properties are set up on the main method, since Archaius uses System properties, but they could be added as command line arguments when launching the app.
#### Additional Sources
In this service we create a new AbstractConfiguration bean, setting up a new Configuration Properties source.
These properties have precedence over all the other properties in the Archaius Composite Configuration.

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>additional-sources-simple</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>additional-sources-simple</name>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-archaius</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung.spring.cloud.archaius.additionalsources;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AdditionalSourcesSimpleApplication {
public static void main(String[] args) {
SpringApplication.run(AdditionalSourcesSimpleApplication.class, args);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.spring.cloud.archaius.additionalsources.config;
import org.apache.commons.configuration.AbstractConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.config.DynamicConfiguration;
import com.netflix.config.FixedDelayPollingScheduler;
import com.netflix.config.PolledConfigurationSource;
import com.netflix.config.sources.URLConfigurationSource;
@Configuration
public class ApplicationPropertiesConfigurations {
@Bean
public AbstractConfiguration addApplicationPropertiesSource() {
PolledConfigurationSource source = new URLConfigurationSource("classpath:other-config.properties");
return new DynamicConfiguration(source, new FixedDelayPollingScheduler());
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.spring.cloud.archaius.additionalsources.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
@RestController
public class ConfigPropertiesController {
private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.one", "not found!");
private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.two", "not found!");
private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.three", "not found!");
private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.four", "not found!");
@GetMapping("/properties-from-dynamic")
public Map<String, String> getPropertiesFromDynamic() {
Map<String, String> properties = new HashMap<>();
properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get());
properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get());
properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get());
properties.put(propertyFourWithDynamic.getName(), propertyFourWithDynamic.get());
return properties;
}
}

View File

@ -0,0 +1,3 @@
server.port=8082
baeldung.archaius.properties.one=one FROM:application.properties
baeldung.archaius.properties.two=two FROM:application.properties

View File

@ -0,0 +1,2 @@
baeldung.archaius.properties.one=one FROM:config.properties
baeldung.archaius.properties.three=three FROM:config.properties

View File

@ -0,0 +1,2 @@
baeldung.archaius.properties.one=one FROM:other-config.properties
baeldung.archaius.properties.four=four FROM:other-config.properties

View File

@ -0,0 +1,54 @@
package com.baeldung.spring.cloud.archaius.additionalsources;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ArchaiusAdditionalSourcesLiveTest {
private static final String BASE_URL = "http://localhost:8082";
private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic";
private static final Map<String, String> EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties();
private static Map<String, String> createExpectedArchaiusProperties() {
Map<String, String> map = new HashMap<>();
map.put("baeldung.archaius.properties.one", "one FROM:other-config.properties");
map.put("baeldung.archaius.properties.two", "two FROM:application.properties");
map.put("baeldung.archaius.properties.three", "three FROM:config.properties");
map.put("baeldung.archaius.properties.four", "four FROM:other-config.properties");
return map;
}
@Autowired
ConfigurableApplicationContext context;
@Autowired
private TestRestTemplate template;
private <T> Map<T, T> exchangeAsMap(String uri, ParameterizedTypeReference<Map<T, T>> responseType) {
return template.exchange(uri, HttpMethod.GET, null, responseType)
.getBody();
}
@Test
public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() {
Map<String, String> initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference<Map<String, String>>() {
});
assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES);
}
}

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>basic-config</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>basic-config</name>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-archaius</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung.spring.cloud.archaius.basic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BasicArchaiusApplication {
public static void main(String[] args) {
SpringApplication.run(BasicArchaiusApplication.class, args);
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.spring.cloud.archaius.basic.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
@RestController
public class ConfigPropertiesController {
@Value("${baeldung.archaius.properties.one:not found!}")
private String propertyOneWithValue;
@Value("${baeldung.archaius.properties.two:not found!}")
private String propertyTwoWithValue;
@Value("${baeldung.archaius.properties.three:not found!}")
private String propertyThreeWithValue;
@Value("${baeldung.archaius.properties.four:not found!}")
private String propertyFourWithValue;
private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.one", "not found!");
private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.two", "not found!");
private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.three", "not found!");
private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.four", "not found!");
private DynamicIntProperty intPropertyWithDynamic = DynamicPropertyFactory.getInstance()
.getIntProperty("baeldung.archaius.properties.int", 0);
@GetMapping("/properties-from-value")
public Map<String, String> getPropertiesFromValue() {
Map<String, String> properties = new HashMap<>();
properties.put("baeldung.archaius.properties.one", propertyOneWithValue);
properties.put("baeldung.archaius.properties.two", propertyTwoWithValue);
properties.put("baeldung.archaius.properties.three", propertyThreeWithValue);
properties.put("baeldung.archaius.properties.four", propertyFourWithValue);
return properties;
}
@GetMapping("/properties-from-dynamic")
public Map<String, String> getPropertiesFromDynamic() {
Map<String, String> properties = new HashMap<>();
properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get());
properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get());
properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get());
properties.put(propertyFourWithDynamic.getName(), propertyFourWithDynamic.get());
return properties;
}
@GetMapping("/int-property")
public Map<String, Integer> getIntPropertyFromDynamic() {
Map<String, Integer> properties = new HashMap<>();
properties.put(intPropertyWithDynamic.getName(), intPropertyWithDynamic.get());
return properties;
}
}

View File

@ -0,0 +1,3 @@
server.port=8080
baeldung.archaius.properties.one=one FROM:application.properties
baeldung.archaius.properties.two=two FROM:application.properties

View File

@ -0,0 +1,4 @@
baeldung.archaius.properties.one=one FROM:config.properties
baeldung.archaius.properties.three=three FROM:config.properties
baeldung.archaius.properties.int=1

View File

@ -0,0 +1,2 @@
baeldung.archaius.properties.one=one FROM:other.properties
baeldung.archaius.properties.four=four FROM:other.properties

View File

@ -0,0 +1,45 @@
package com.baeldung.spring.cloud.archaius.basic;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
@RunWith(JUnitPlatform.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class ArchaiusBasicConfigurationIntegrationTest {
@Autowired
ConfigurableApplicationContext context;
private DynamicStringProperty testPropertyWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.test.properties.one", "not found!");
@Test
public void givenIntialPropertyValue_whenPropertyChanges_thenArchaiusRetrievesNewValue() {
String initialValue = testPropertyWithDynamic.get();
TestPropertyValues.of("baeldung.archaius.test.properties.one=new-value")
.applyTo(context);
context.publishEvent(new EnvironmentChangeEvent(Collections.singleton("baeldung.archaius.test.properties.one")));
String finalValue = testPropertyWithDynamic.get();
assertThat(initialValue).isEqualTo("test-one");
assertThat(finalValue).isEqualTo("new-value");
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.spring.cloud.archaius.basic;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ArchaiusBasicConfigurationLiveTest {
private static final String BASE_URL = "http://localhost:8080";
private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic";
private static final Map<String, String> EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties();
private static Map<String, String> createExpectedArchaiusProperties() {
Map<String, String> map = new HashMap<>();
map.put("baeldung.archaius.properties.one", "one FROM:application.properties");
map.put("baeldung.archaius.properties.two", "two FROM:application.properties");
map.put("baeldung.archaius.properties.three", "three FROM:config.properties");
map.put("baeldung.archaius.properties.four", "not found!");
return map;
}
private static final String VALUE_PROPERTIES_URL = "/properties-from-value";
private static final Map<String, String> EXPECTED_VALUE_PROPERTIES = createExpectedValueProperties();
private static Map<String, String> createExpectedValueProperties() {
Map<String, String> map = new HashMap<>();
map.put("baeldung.archaius.properties.one", "one FROM:application.properties");
map.put("baeldung.archaius.properties.two", "two FROM:application.properties");
map.put("baeldung.archaius.properties.three", "not found!");
map.put("baeldung.archaius.properties.four", "not found!");
return map;
}
@Autowired
ConfigurableApplicationContext context;
@Autowired
private TestRestTemplate template;
private <T> Map<T, T> exchangeAsMap(String uri, ParameterizedTypeReference<Map<T, T>> responseType) {
return template.exchange(uri, HttpMethod.GET, null, responseType)
.getBody();
}
@Test
public void givenDefaultConfigurationSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() {
Map<String, String> initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference<Map<String, String>>() {
});
assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES);
}
@Test
public void givenNonDefaultConfigurationFilesSetup_whenRequestSpringVisibleProperties_thenEndpointDoesntRetrieveArchaiusProperties() {
Map<String, String> initialResponse = this.exchangeAsMap(BASE_URL + VALUE_PROPERTIES_URL, new ParameterizedTypeReference<Map<String, String>>() {
});
assertThat(initialResponse).containsAllEntriesOf(EXPECTED_VALUE_PROPERTIES);
}
}

View File

@ -0,0 +1,3 @@
baeldung.archaius.test.properties.one=test-one
baeldung.archaius.test.properties.two=test-two
baeldung.archaius.test.properties.int=1

View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>extra-configs</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>extra-configs</name>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-archaius</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-archaius</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix</artifactId>
<version>${spring-cloud-dependencies.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<spring-cloud-dependencies.version>2.0.1.RELEASE</spring-cloud-dependencies.version>
</properties>
</project>

View File

@ -0,0 +1,16 @@
package com.baeldung.spring.cloud.archaius.extraconfigs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExtraConfigsApplication {
public static void main(String[] args) {
// System properties can be set as command line arguments too
System.setProperty("archaius.configurationSource.additionalUrls", "classpath:other-config-dir/extra.properties");
System.setProperty("archaius.configurationSource.defaultFileName", "other.properties");
SpringApplication.run(ExtraConfigsApplication.class, args);
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.spring.cloud.archaius.extraconfigs.controllers;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
@RestController
public class ConfigPropertiesController {
@Value("${baeldung.archaius.properties.one:not found!}")
private String propertyOneWithValue;
@Value("${baeldung.archaius.properties.two:not found!}")
private String propertyTwoWithValue;
@Value("${baeldung.archaius.properties.three:not found!}")
private String propertyThreeWithValue;
@Value("${baeldung.archaius.properties.four:not found!}")
private String propertyFourWithValue;
private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.one", "not found!");
private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.two", "not found!");
private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.three", "not found!");
private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.four", "not found!");
@GetMapping("/properties-from-value")
public Map<String, String> getPropertiesFromValue() {
Map<String, String> properties = new HashMap<>();
properties.put("baeldung.archaius.properties.one", propertyOneWithValue);
properties.put("baeldung.archaius.properties.two", propertyTwoWithValue);
properties.put("baeldung.archaius.properties.three", propertyThreeWithValue);
properties.put("baeldung.archaius.properties.four", propertyFourWithValue);
return properties;
}
@GetMapping("/properties-from-dynamic")
public Map<String, String> getPropertiesFromDynamic() {
Map<String, String> properties = new HashMap<>();
properties.put("baeldung.archaius.properties.one", propertyOneWithDynamic.get());
properties.put("baeldung.archaius.properties.two", propertyTwoWithDynamic.get());
properties.put("baeldung.archaius.properties.three", propertyThreeWithDynamic.get());
properties.put("baeldung.archaius.properties.four", propertyFourWithDynamic.get());
return properties;
}
}

View File

@ -0,0 +1,3 @@
server.port=8081
baeldung.archaius.properties.one=one FROM:application.properties
baeldung.archaius.properties.two=two FROM:application.properties

View File

@ -0,0 +1,2 @@
baeldung.archaius.properties.one=one FROM:extra.properties
baeldung.archaius.properties.three=three FROM:extra.properties

View File

@ -0,0 +1,2 @@
baeldung.archaius.properties.one=one FROM:other.properties
baeldung.archaius.properties.four=four FROM:other.properties

View File

@ -0,0 +1,54 @@
package com.baeldung.spring.cloud.archaius.extraconfigs;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ArchaiusExtraConfigsLiveTest {
private static final String BASE_URL = "http://localhost:8081";
private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic";
private static final Map<String, String> EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties();
private static Map<String, String> createExpectedArchaiusProperties() {
Map<String, String> map = new HashMap<>();
map.put("baeldung.archaius.properties.one", "one FROM:application.properties");
map.put("baeldung.archaius.properties.two", "two FROM:application.properties");
map.put("baeldung.archaius.properties.three", "three FROM:extra.properties");
map.put("baeldung.archaius.properties.four", "four FROM:other.properties");
return map;
}
@Autowired
ConfigurableApplicationContext context;
@Autowired
private TestRestTemplate template;
private <T> Map<T, T> exchangeAsMap(String uri, ParameterizedTypeReference<Map<T, T>> responseType) {
return template.exchange(uri, HttpMethod.GET, null, responseType)
.getBody();
}
@Test
public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() {
Map<String, String> initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference<Map<String, String>>() {
});
assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES);
}
}

View File

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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.spring.cloud</groupId>
<artifactId>spring-cloud-archaius</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>spring-cloud-archaius</name>
<description>Spring Cloud Archaius Pom parent</description>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<modules>
<module>basic-config</module>
<module>additional-sources-simple</module>
<module>extra-configs</module>
</modules>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-archaius</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix</artifactId>
<version>${spring-cloud-dependencies.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<spring-cloud-dependencies.version>2.0.1.RELEASE</spring-cloud-dependencies.version>
<junit.platform.version>1.2.0</junit.platform.version>
</properties>
</project>

View File

@ -1,29 +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>java-faker</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>0.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,115 +0,0 @@
package com.baeldung;
import com.github.javafaker.Faker;
import com.github.javafaker.service.FakeValuesService;
import com.github.javafaker.service.FakerIDN;
import com.github.javafaker.service.LocaleDoesNotExistException;
import com.github.javafaker.service.RandomService;
import javafx.scene.Parent;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class JavaFakerTest {
private Faker faker;
@Before
public void setUp() throws Exception {
faker = new Faker();
}
@Test
public void givenJavaFaker_whenAddressObjectCalled_checkValidAddressInfoGiven() throws Exception {
Faker faker = new Faker();
String streetName = faker.address().streetName();
String number = faker.address().buildingNumber();
String city = faker.address().city();
String country = faker.address().country();
System.out.println(String.format("%s\n%s\n%s\n%s",
number,
streetName,
city,
country));
}
@Test
public void givenJavaFakersWithSameSeed_whenNameCalled_CheckSameName() throws Exception {
Faker faker1 = new Faker(new Random(24));
Faker faker2 = new Faker(new Random(24));
assertEquals(faker1.name().firstName(), faker2.name().firstName());
}
@Test
public void givenJavaFakersWithDifferentLocals_checkZipCodesMatchRegex() throws Exception {
Faker ukFaker = new Faker(new Locale("en-GB"));
Faker usFaker = new Faker(new Locale("en-US"));
System.out.println(String.format("American zipcode: %s", usFaker.address().zipCode()));
System.out.println(String.format("British postcode: %s", ukFaker.address().zipCode()));
Pattern ukPattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2})");
Matcher ukMatcher = ukPattern.matcher(ukFaker.address().zipCode());
assertTrue(ukMatcher.find());
Matcher usMatcher = Pattern.compile("^\\d{5}(?:[-\\s]\\d{4})?$").matcher(usFaker.address().zipCode());
assertTrue(usMatcher.find());
}
@Test
public void givenJavaFakerService_testFakersCreated() throws Exception {
RandomService randomService = new RandomService();
System.out.println(randomService.nextBoolean());
System.out.println(randomService.nextDouble());
Faker faker = new Faker(new Random(randomService.nextLong()));
System.out.println(faker.address().city());
}
@Test
public void testFakeValuesService() throws Exception {
FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-GB"), new RandomService());
String email = fakeValuesService.bothify("????##@gmail.com");
Matcher emailMatcher = Pattern.compile("\\w{4}\\d{2}@gmail.com").matcher(email);
assertTrue(emailMatcher.find());
String alphaNumericString = fakeValuesService.regexify("[a-z1-9]{10}");
Matcher alphaNumericMatcher = Pattern.compile("[a-z1-9]{10}").matcher(alphaNumericString);
assertTrue(alphaNumericMatcher.find());
}
@Test(expected = LocaleDoesNotExistException.class)
public void givenWrongLocale_whenFakerIsInitialised_testLocaleDoesNotExistExceptionIsThrown() throws Exception {
Faker wrongLocaleFaker = new Faker(new Locale("en-seaWorld"));
}
}

View File

@ -88,6 +88,11 @@
<artifactId>javalite-common</artifactId>
<version>${javalite.version}</version>
</dependency>
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>0.15</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,121 @@
package com.baeldung.javafaker;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Before;
import org.junit.Test;
import com.github.javafaker.Faker;
import com.github.javafaker.service.FakeValuesService;
import com.github.javafaker.service.LocaleDoesNotExistException;
import com.github.javafaker.service.RandomService;
public class JavaFakerUnitTest {
private Faker faker;
@Before
public void setUp() throws Exception {
faker = new Faker();
}
@Test
public void givenJavaFaker_whenAddressObjectCalled_checkValidAddressInfoGiven() throws Exception {
Faker faker = new Faker();
String streetName = faker.address()
.streetName();
String number = faker.address()
.buildingNumber();
String city = faker.address()
.city();
String country = faker.address()
.country();
System.out.println(String.format("%s\n%s\n%s\n%s", number, streetName, city, country));
}
@Test
public void givenJavaFakersWithSameSeed_whenNameCalled_CheckSameName() throws Exception {
Faker faker1 = new Faker(new Random(24));
Faker faker2 = new Faker(new Random(24));
assertEquals(faker1.name()
.firstName(),
faker2.name()
.firstName());
}
@Test
public void givenJavaFakersWithDifferentLocals_checkZipCodesMatchRegex() throws Exception {
Faker ukFaker = new Faker(new Locale("en-GB"));
Faker usFaker = new Faker(new Locale("en-US"));
System.out.println(String.format("American zipcode: %s", usFaker.address()
.zipCode()));
System.out.println(String.format("British postcode: %s", ukFaker.address()
.zipCode()));
Pattern ukPattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2})");
Matcher ukMatcher = ukPattern.matcher(ukFaker.address()
.zipCode());
assertTrue(ukMatcher.find());
Matcher usMatcher = Pattern.compile("^\\d{5}(?:[-\\s]\\d{4})?$")
.matcher(usFaker.address()
.zipCode());
assertTrue(usMatcher.find());
}
@Test
public void givenJavaFakerService_testFakersCreated() throws Exception {
RandomService randomService = new RandomService();
System.out.println(randomService.nextBoolean());
System.out.println(randomService.nextDouble());
Faker faker = new Faker(new Random(randomService.nextLong()));
System.out.println(faker.address()
.city());
}
@Test
public void testFakeValuesService() throws Exception {
FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-GB"), new RandomService());
String email = fakeValuesService.bothify("????##@gmail.com");
Matcher emailMatcher = Pattern.compile("\\w{4}\\d{2}@gmail.com")
.matcher(email);
assertTrue(emailMatcher.find());
String alphaNumericString = fakeValuesService.regexify("[a-z1-9]{10}");
Matcher alphaNumericMatcher = Pattern.compile("[a-z1-9]{10}")
.matcher(alphaNumericString);
assertTrue(alphaNumericMatcher.find());
}
@Test(expected = LocaleDoesNotExistException.class)
public void givenWrongLocale_whenFakerIsInitialised_testLocaleDoesNotExistExceptionIsThrown() throws Exception {
Faker wrongLocaleFaker = new Faker(new Locale("en-seaWorld"));
}
}