yncing upstream with fork
Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
7609927f1b
33
README.md
33
README.md
|
@ -2,41 +2,22 @@
|
|||
The "REST with Spring" Classes
|
||||
==============================
|
||||
|
||||
Here's the Master Class of REST With Spring (price changes permanently next Friday): <br/>
|
||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material): <br/>
|
||||
**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
|
||||
And here's the Master Class of Learn Spring Security: <br/>
|
||||
**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||
**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||
|
||||
|
||||
|
||||
Spring Tutorials
|
||||
Java and Spring Tutorials
|
||||
================
|
||||
|
||||
This project is **a collection of small and focused tutorials** each covering a single and well defined area of development.
|
||||
Most of the tutorial projects are focused on the `Spring Framework` (and `Spring Security`).
|
||||
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
||||
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Securiyt.
|
||||
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
||||
|
||||
|
||||
Building the project
|
||||
====================
|
||||
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
||||
|
||||
|
||||
Working with the code in Eclipse
|
||||
================================
|
||||
Any IDE can be used to work with the projects, but if you're using Eclipse, consider the following.
|
||||
|
||||
- import the included **formatter** in Eclipse:
|
||||
`https://github.com/eugenp/tutorials/tree/master/eclipse`
|
||||
|
||||
|
||||
CI - Jenkins
|
||||
================================
|
||||
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**
|
||||
|
||||
### Relevant Articles:
|
||||
================================
|
||||
|
||||
- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
|
||||
- [Apache Maven Tutorial](http://www.baeldung.com/maven)
|
||||
- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)
|
||||
|
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.algorithms.mergesort;
|
||||
|
||||
public class MergeSort {
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] a = { 5, 1, 6, 2, 3, 4 };
|
||||
mergeSort(a, a.length);
|
||||
for (int i = 0; i < a.length; i++)
|
||||
System.out.println(a[i]);
|
||||
}
|
||||
|
||||
public static void mergeSort(int[] a, int n) {
|
||||
if (n < 2)
|
||||
return;
|
||||
int mid = n / 2;
|
||||
int[] l = new int[mid];
|
||||
int[] r = new int[n - mid];
|
||||
|
||||
for (int i = 0; i < mid; i++) {
|
||||
l[i] = a[i];
|
||||
}
|
||||
for (int i = mid; i < n; i++) {
|
||||
r[i - mid] = a[i];
|
||||
}
|
||||
mergeSort(l, mid);
|
||||
mergeSort(r, n - mid);
|
||||
|
||||
merge(a, l, r, mid, n - mid);
|
||||
}
|
||||
|
||||
public static void merge(int[] a, int[] l, int[] r, int left, int right) {
|
||||
|
||||
int i = 0, j = 0, k = 0;
|
||||
|
||||
while (i < left && j < right) {
|
||||
|
||||
if (l[i] < r[j])
|
||||
a[k++] = l[i++];
|
||||
else
|
||||
a[k++] = r[j++];
|
||||
|
||||
}
|
||||
|
||||
while (i < left)
|
||||
a[k++] = l[i++];
|
||||
|
||||
while (j < right)
|
||||
a[k++] = r[j++];
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.algorithms.quicksort;
|
||||
|
||||
public class QuickSort {
|
||||
|
||||
public static void quickSort(int arr[], int begin, int end)
|
||||
{
|
||||
if (begin < end) {
|
||||
int partitionIndex = partition(arr, begin, end);
|
||||
|
||||
// Recursively sort elements of the 2 sub-arrays
|
||||
quickSort(arr, begin, partitionIndex-1);
|
||||
quickSort(arr, partitionIndex+1, end);
|
||||
}
|
||||
}
|
||||
|
||||
private static int partition(int arr[], int begin, int end)
|
||||
{
|
||||
int pivot = arr[end];
|
||||
int i = (begin-1);
|
||||
|
||||
for (int j=begin; j<end; j++)
|
||||
{
|
||||
if (arr[j] <= pivot) {
|
||||
i++;
|
||||
|
||||
int swapTemp = arr[i];
|
||||
arr[i] = arr[j];
|
||||
arr[j] = swapTemp;
|
||||
}
|
||||
}
|
||||
|
||||
int swapTemp = arr[i+1];
|
||||
arr[i+1] = arr[end];
|
||||
arr[end] = swapTemp;
|
||||
|
||||
return i+1;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.algorithms.quicksort;
|
||||
|
||||
public class ThreeWayQuickSort {
|
||||
|
||||
public static void threeWayQuickSort(int[] a, int begin, int end)
|
||||
{
|
||||
if (end <= begin) return;
|
||||
|
||||
// partition
|
||||
int i = begin;
|
||||
int less = begin;
|
||||
int greater = end;
|
||||
|
||||
while (i <= greater){
|
||||
if (a[i] < a[less]) {
|
||||
int tmp = a[i];
|
||||
a[i] = a[less];
|
||||
a[less] = tmp;
|
||||
|
||||
i++;
|
||||
less++;
|
||||
}
|
||||
else if (a[less] < a[i]) {
|
||||
int tmp = a[i];
|
||||
a[i] = a[greater];
|
||||
a[greater] = tmp;
|
||||
|
||||
greater--;
|
||||
}
|
||||
else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
threeWayQuickSort(a, begin, less - 1);
|
||||
threeWayQuickSort(a, greater + 1, end);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.algorithms.mergesort;
|
||||
|
||||
import org.junit.Assert;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MergeSortUnitTest {
|
||||
|
||||
@Test
|
||||
public void positiveTest() {
|
||||
int[] actual = { 5, 1, 6, 2, 3, 4 };
|
||||
int[] expected = { 1, 2, 3, 4, 5, 6 };
|
||||
MergeSort.mergeSort(actual, actual.length);
|
||||
Assert.assertArrayEquals(expected, actual);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.algorithms.quicksort;
|
||||
|
||||
import com.baeldung.algorithms.quicksort.QuickSort;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class QuickSortUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() {
|
||||
int[] actual = { 9, 5, 1, 0, 6, 2, 3, 4, 7, 8 };
|
||||
int[] expected = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
|
||||
QuickSort.quickSort(actual, 0, actual.length-1);
|
||||
Assert.assertArrayEquals(expected, actual);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.algorithms.quicksort;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ThreeWayQuickSortUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() {
|
||||
int[] actual = { 3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3 };
|
||||
int[] expected = { 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7 };
|
||||
ThreeWayQuickSort.threeWayQuickSort(actual, 0, actual.length-1);
|
||||
Assert.assertArrayEquals(expected, actual);
|
||||
}
|
||||
}
|
|
@ -7,7 +7,7 @@ import junit.framework.TestSuite;
|
|||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
public class AppUnitTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
|
@ -15,7 +15,7 @@ public class AppTest
|
|||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
public AppUnitTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
@ -25,7 +25,7 @@ public class AppTest
|
|||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
return new TestSuite( AppUnitTest.class );
|
||||
}
|
||||
|
||||
/**
|
|
@ -6,7 +6,7 @@
|
|||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-avro</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>Apache Avro</version>
|
||||
<name>Apache Avro</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
|
|
@ -13,7 +13,7 @@ import java.util.Objects;
|
|||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class AvroSerealizerDeSerealizerTest {
|
||||
public class AvroSerealizerDeSerealizerUnitTest {
|
||||
|
||||
AvroSerealizer serealizer;
|
||||
AvroDeSerealizer deSerealizer;
|
|
@ -0,0 +1,46 @@
|
|||
<?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>apache-geode</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<geode.core>1.6.0</geode.core>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.geode</groupId>
|
||||
<artifactId>geode-core</artifactId>
|
||||
<version>${geode.core}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>RELEASE</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,78 @@
|
|||
package com.baeldung.geode;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
public class Customer implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = -7482516011038799900L;
|
||||
|
||||
private CustomerKey key;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Integer age;
|
||||
|
||||
public Customer() {
|
||||
}
|
||||
|
||||
public Customer(String firstName, String lastName, int age) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public Customer(CustomerKey key, String firstName, String lastName, int age) {
|
||||
this(firstName, lastName, age);
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
// setters and getters
|
||||
|
||||
public static long getSerialVersionUID() {
|
||||
return serialVersionUID;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Customer customer = (Customer) o;
|
||||
return Objects.equals(firstName, customer.firstName) && Objects.equals(lastName, customer.lastName) && Objects.equals(age, customer.age);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(firstName, lastName, age);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.geode;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class CustomerKey implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = -3529253035303792458L;
|
||||
private long id;
|
||||
private String country;
|
||||
|
||||
public CustomerKey(long id) {
|
||||
this.id = id;
|
||||
this.country = "USA";
|
||||
}
|
||||
|
||||
public CustomerKey(long id, String country) {
|
||||
this.id = id;
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
CustomerKey that = (CustomerKey) o;
|
||||
|
||||
if (id != that.id)
|
||||
return false;
|
||||
return country != null ? country.equals(that.country) : that.country == null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = (int) (id ^ (id >>> 32));
|
||||
result = 31 * result + (country != null ? country.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.geode.functions;
|
||||
|
||||
import com.baeldung.geode.Customer;
|
||||
import com.baeldung.geode.CustomerKey;
|
||||
import org.apache.geode.cache.Region;
|
||||
import org.apache.geode.cache.execute.Function;
|
||||
import org.apache.geode.cache.execute.FunctionContext;
|
||||
import org.apache.geode.cache.execute.RegionFunctionContext;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class UpperCaseNames implements Function<Boolean> {
|
||||
private static final long serialVersionUID = -8946294032165677602L;
|
||||
|
||||
@Override
|
||||
public void execute(FunctionContext<Boolean> context) {
|
||||
RegionFunctionContext regionContext = (RegionFunctionContext) context;
|
||||
Region<CustomerKey, Customer> region = regionContext.getDataSet();
|
||||
|
||||
for (Map.Entry<CustomerKey, Customer> entry : region.entrySet()) {
|
||||
Customer customer = entry.getValue();
|
||||
customer.setFirstName(customer.getFirstName()
|
||||
.toUpperCase());
|
||||
}
|
||||
|
||||
context.getResultSender()
|
||||
.lastResult(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return getClass().getName();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
package com.baeldung.geode;
|
||||
|
||||
import com.baeldung.geode.functions.UpperCaseNames;
|
||||
import org.apache.geode.cache.Region;
|
||||
import org.apache.geode.cache.client.ClientCache;
|
||||
import org.apache.geode.cache.client.ClientCacheFactory;
|
||||
import org.apache.geode.cache.client.ClientRegionShortcut;
|
||||
import org.apache.geode.cache.execute.Execution;
|
||||
import org.apache.geode.cache.execute.FunctionService;
|
||||
import org.apache.geode.cache.query.*;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class GeodeSamplesIntegrationTest {
|
||||
|
||||
ClientCache cache = null;
|
||||
Region<String, String> region = null;
|
||||
Region<Integer, Customer> queryRegion = null;
|
||||
Region<CustomerKey, Customer> customerRegion = null;
|
||||
|
||||
@Before
|
||||
public void connect() {
|
||||
this.cache = new ClientCacheFactory().addPoolLocator("localhost", 10334)
|
||||
.create();
|
||||
this.region = this.cache.<String, String> createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
|
||||
.create("baeldung");
|
||||
this.customerRegion = this.cache.<CustomerKey, Customer> createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
|
||||
.create("baeldung-customers");
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
this.cache.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMessageToRegion_thenMessageSavedSuccessfully() {
|
||||
|
||||
this.region.put("1", "Hello");
|
||||
this.region.put("2", "Baeldung");
|
||||
|
||||
assertEquals("Hello", region.get("1"));
|
||||
assertEquals("Baeldung", region.get("2"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPutMultipleValuesAtOnce_thenValuesSavedSuccessfully() {
|
||||
|
||||
Supplier<Stream<String>> keys = () -> Stream.of("A", "B", "C", "D", "E");
|
||||
Map<String, String> values = keys.get()
|
||||
.collect(Collectors.toMap(Function.identity(), String::toLowerCase));
|
||||
|
||||
this.region.putAll(values);
|
||||
|
||||
keys.get()
|
||||
.forEach(k -> assertEquals(k.toLowerCase(), this.region.get(k)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPutCustomKey_thenValuesSavedSuccessfully() {
|
||||
CustomerKey key = new CustomerKey(123);
|
||||
Customer customer = new Customer(key, "William", "Russell", 35);
|
||||
|
||||
Map<CustomerKey, Customer> customerInfo = new HashMap<>();
|
||||
customerInfo.put(key, customer);
|
||||
|
||||
this.customerRegion.putAll(customerInfo);
|
||||
|
||||
Customer storedCustomer = this.customerRegion.get(key);
|
||||
assertEquals("William", storedCustomer.getFirstName());
|
||||
assertEquals("Russell", storedCustomer.getLastName());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindACustomerUsingOQL_thenCorrectCustomerObject() throws NameResolutionException, TypeMismatchException, QueryInvocationTargetException, FunctionDomainException {
|
||||
|
||||
Map<CustomerKey, Customer> data = new HashMap<>();
|
||||
data.put(new CustomerKey(1), new Customer("Gheorge", "Manuc", 36));
|
||||
data.put(new CustomerKey(2), new Customer("Allan", "McDowell", 43));
|
||||
this.customerRegion.putAll(data);
|
||||
|
||||
QueryService queryService = this.cache.getQueryService();
|
||||
String query = "select * from /baeldung-customers c where c.firstName = 'Allan'";
|
||||
SelectResults<Customer> queryResults = (SelectResults<Customer>) queryService.newQuery(query)
|
||||
.execute();
|
||||
assertEquals(1, queryResults.size());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExecuteUppercaseNames_thenCustomerNamesAreUppercased() {
|
||||
Execution execution = FunctionService.onRegion(this.customerRegion);
|
||||
execution.execute(UpperCaseNames.class.getName());
|
||||
Customer customer = this.customerRegion.get(new CustomerKey(1));
|
||||
assertEquals("GHEORGE", customer.getFirstName());
|
||||
}
|
||||
}
|
|
@ -1,16 +1,18 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java8.entity.Human;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.primitives.Ints;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.java8.entity.Human;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.primitives.Ints;
|
||||
|
||||
public class Java8SortUnitTest {
|
||||
|
||||
|
@ -111,5 +113,22 @@ public class Java8SortUnitTest {
|
|||
humans.sort(Comparator.comparing(Human::getName));
|
||||
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
final List<String> letters = Lists.newArrayList("B", "A", "C");
|
||||
|
||||
final List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
|
||||
Assert.assertThat(sortedLetters.get(0), equalTo("A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
|
||||
|
||||
final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
|
||||
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.stream.conditional;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamForEachIfElseUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenIntegerStream_whenCheckingIntegerParityWithIfElse_thenEnsureCorrectParity() {
|
||||
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
|
||||
ints.stream()
|
||||
.forEach(i -> {
|
||||
if (i.intValue() % 2 == 0) {
|
||||
Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0);
|
||||
} else {
|
||||
Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenIntegerStream_whenCheckingIntegerParityWithStreamFilter_thenEnsureCorrectParity() {
|
||||
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
|
||||
Stream<Integer> evenIntegers = ints.stream()
|
||||
.filter(i -> i.intValue() % 2 == 0);
|
||||
Stream<Integer> oddIntegers = ints.stream()
|
||||
.filter(i -> i.intValue() % 2 != 0);
|
||||
|
||||
evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0));
|
||||
oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0));
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -18,6 +18,7 @@ import java.net.URLConnection;
|
|||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
@ -50,7 +51,7 @@ public class FileOperationsManualTest {
|
|||
|
||||
@Test
|
||||
public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
|
||||
String expectedData = "BSD License";
|
||||
String expectedData = "MIT License";
|
||||
|
||||
Class clazz = Matchers.class;
|
||||
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
|
||||
|
@ -79,7 +80,7 @@ public class FileOperationsManualTest {
|
|||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
String data = FileUtils.readFileToString(file);
|
||||
String data = FileUtils.readFileToString(file, "UTF-8");
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
@ -102,12 +103,11 @@ public class FileOperationsManualTest {
|
|||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||
|
||||
StringBuilder data = new StringBuilder();
|
||||
Stream<String> lines = Files.lines(path);
|
||||
lines.forEach(line -> data.append(line).append("\n"));
|
||||
String data = lines.collect(Collectors.joining("\n"));
|
||||
lines.close();
|
||||
|
||||
assertEquals(expectedData, data.toString().trim());
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
private String readFromInputStream(InputStream inputStream) throws IOException {
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
Hello World from fileTest.txt!!!
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.memoryleaks.equalshashcode;
|
||||
|
||||
public class Person {
|
||||
public String name;
|
||||
|
||||
public Person(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.memoryleaks.equalshashcode;
|
||||
|
||||
public class PersonOptimized {
|
||||
public String name;
|
||||
|
||||
public PersonOptimized(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this) return true;
|
||||
if (!(o instanceof PersonOptimized)) {
|
||||
return false;
|
||||
}
|
||||
PersonOptimized person = (PersonOptimized) o;
|
||||
return person.name.equals(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = 17;
|
||||
result = 31 * result + name.hashCode();
|
||||
return result;
|
||||
}}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.memoryleaks.finalize;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
public class BulkyObject {
|
||||
private String data[];
|
||||
|
||||
public BulkyObject() {
|
||||
data = new String[1000000];
|
||||
|
||||
for(int i=0; i<1000000; i++) {
|
||||
data[i] = getRandomString();
|
||||
}
|
||||
}
|
||||
|
||||
private String getRandomString() {
|
||||
byte[] array = new byte[1000];
|
||||
new Random().nextBytes(array);
|
||||
return new String(array, Charset.forName("UTF-8"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finalize() {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("Finalizer called");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.memoryleaks.finalize;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
public class BulkyObjectOptimized {
|
||||
private String data[];
|
||||
|
||||
public BulkyObjectOptimized() {
|
||||
data = new String[1000000];
|
||||
|
||||
for(int i=0; i<1000000; i++) {
|
||||
data[i] = getRandomString();
|
||||
}
|
||||
}
|
||||
|
||||
private String getRandomString() {
|
||||
byte[] array = new byte[1000];
|
||||
new Random().nextBytes(array);
|
||||
return new String(array, Charset.forName("UTF-8"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.memoryleaks.innerclass;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
public class BulkyObject {
|
||||
private String data[];
|
||||
|
||||
public BulkyObject() {
|
||||
data = new String[1000000];
|
||||
|
||||
for(int i=0; i<1000000; i++) {
|
||||
data[i] = getRandomString();
|
||||
}
|
||||
}
|
||||
|
||||
private String getRandomString() {
|
||||
byte[] array = new byte[1000];
|
||||
new Random().nextBytes(array);
|
||||
return new String(array, Charset.forName("UTF-8"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.memoryleaks.innerclass;
|
||||
|
||||
public class InnerClassDriver {
|
||||
public static InnerClassWrapper.SimpleInnerClass getSimpleInnerClassObj() {
|
||||
return new InnerClassWrapper().new SimpleInnerClass();
|
||||
}
|
||||
|
||||
public static void main2(String[] args) {
|
||||
InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = getSimpleInnerClassObj();
|
||||
System.out.println("Debug point");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
StaticNestedClassWrapper.StaticNestedClass simpleInnerClassObj = new StaticNestedClassWrapper.StaticNestedClass();
|
||||
System.out.println("Debug point");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.memoryleaks.innerclass;
|
||||
|
||||
|
||||
public class InnerClassWrapper {
|
||||
private BulkyObject bulkyObject = new BulkyObject();
|
||||
|
||||
public class SimpleInnerClass {
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.memoryleaks.innerclass;
|
||||
|
||||
|
||||
public class StaticNestedClassWrapper {
|
||||
private BulkyObject bulkyObject = new BulkyObject();
|
||||
|
||||
public static class StaticNestedClass {
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.memoryleaks.internedstrings;
|
||||
|
||||
public class InternedString {
|
||||
private static final String FILEPATH = "C:\\bigstring.txt";
|
||||
|
||||
public void readString() {
|
||||
String s1 = ReadStringFromFileUtil.read(FILEPATH).intern();
|
||||
String s2 = ReadStringFromFileUtil.read(FILEPATH).intern();
|
||||
|
||||
if (s1 == s2) {
|
||||
System.out.println("Both the strings objects are same");
|
||||
}
|
||||
else {
|
||||
System.out.println("Both the strings objects are different");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.memoryleaks.internedstrings;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
public class ReadStringFromFileUtil {
|
||||
|
||||
public static String read(String fileName) {
|
||||
BufferedReader br = null;
|
||||
try {
|
||||
br = new BufferedReader(new FileReader(fileName));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String line = br.readLine();
|
||||
|
||||
while (line != null) {
|
||||
sb.append(line);
|
||||
sb.append("\n");
|
||||
line = br.readLine();
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.memoryleaks.internedstrings;
|
||||
|
||||
public class StringObject {
|
||||
private static final String FILEPATH = "C:\\bigstring.txt";
|
||||
|
||||
public void readString() {
|
||||
String s1 = ReadStringFromFileUtil.read(FILEPATH);
|
||||
String s2 = ReadStringFromFileUtil.read(FILEPATH);
|
||||
|
||||
if (s1 == s2) {
|
||||
System.out.println("Both the strings objects are same");
|
||||
}
|
||||
else {
|
||||
System.out.println("Both the strings objects are different");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.memoryleaks.staticfields;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class NonStaticFieldsDemo {
|
||||
public List<Double> list = new ArrayList<>();
|
||||
|
||||
public void populateList() {
|
||||
for (int i = 0; i < 10000000; i++) {
|
||||
list.add(Math.random());
|
||||
}
|
||||
System.out.println("Debug Point 2");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Debug Point 1");
|
||||
new NonStaticFieldsDemo().populateList();
|
||||
System.out.println("Debug Point 3");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.memoryleaks.staticfields;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class StaticFieldsDemo {
|
||||
public static List<Double> list = new ArrayList<>();
|
||||
|
||||
public void populateList() {
|
||||
for (int i = 0; i < 10000000; i++) {
|
||||
list.add(Math.random());
|
||||
}
|
||||
System.out.println("Debug Point 2");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Debug Point 1");
|
||||
new StaticFieldsDemo().populateList();
|
||||
System.out.println("Debug Point 3");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.nth.root.calculator;
|
||||
|
||||
public class NthRootCalculator
|
||||
{
|
||||
public Double calculate(Double base, Double n) {
|
||||
return Math.pow(Math.E, Math.log(base)/n);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.nth.root.main;
|
||||
|
||||
import com.baeldung.nth.root.calculator.NthRootCalculator;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
NthRootCalculator calculator = new NthRootCalculator();
|
||||
Double base = Double.parseDouble(args[0]);
|
||||
Double n = Double.parseDouble(args[1]);
|
||||
Double result = calculator.calculate(base, n);
|
||||
System.out.println("The " + n + " root of " + base + " equals to " + result + ".");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.memoryleaks.equalshashcode;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PersonMemoryLeakUnitTest {
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenMap_whenEqualsAndHashCodeNotOverridden_thenMemoryLeak() {
|
||||
Map<Person, Integer> map = new HashMap<Person, Integer>();
|
||||
for(int i=0; i<10000000; i++) {
|
||||
map.put(new Person("jon"), 1);
|
||||
}
|
||||
assertTrue(map.size() > 1);
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenMap_whenEqualsAndHashCodeOverridden_thenNoMemoryLeak() {
|
||||
Map<PersonOptimized, Integer> map = new HashMap<PersonOptimized, Integer>();
|
||||
for(int i=0; i<10000; i++) {
|
||||
map.put(new PersonOptimized("jon"), 1);
|
||||
}
|
||||
assertTrue(map.size() == 1);
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.memoryleaks.finalize;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FinalizeMemoryLeakUnitTest {
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenObjectWithFinalizer_whenCreatingAndDestroyingThisObject_thenMemoryLeak() {
|
||||
BulkyObject[] stock = new BulkyObject[100000];
|
||||
|
||||
for(int i=0; i<100000; i++) {
|
||||
stock[i] = new BulkyObject();
|
||||
}
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenObjectWithoutFinalizer_whenCreatingAndDestroyingThisObject_thenNoMemoryLeak() {
|
||||
BulkyObjectOptimized[] stock = new BulkyObjectOptimized[100000];
|
||||
|
||||
for(int i=0; i<100000; i++) {
|
||||
stock[i] = new BulkyObjectOptimized();
|
||||
}
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.memoryleaks.innerclass;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StaticInnerClassMemoryLeakUnitTest {
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenUsingInnerClass_whenInitializingInnerClass_thenInnerClassHoldsReferenceOfOuterObject() {
|
||||
InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = new InnerClassWrapper().new SimpleInnerClass();
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenUsingStaticNestedClass_whenInitializingInnerClass_thenStaticNestedClassDoesntReferenceOuterObject() {
|
||||
StaticNestedClassWrapper.StaticNestedClass staticNestedClassObj = new StaticNestedClassWrapper.StaticNestedClass();
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.memoryleaks.internedstrings;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringInternMemoryLeakUnitTest {
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenJava6OrBelow_whenInterningLargeStrings_thenPermgenIncreases() {
|
||||
new InternedString().readString();
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenJava6OrBelow_whenNotInterningLargeStrings_thenPermgenDoesntIncrease() {
|
||||
new StringObject().readString();
|
||||
System.out.print("Debug Point - VisuaLVM");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.memoryleaks.staticfields;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NonStaticFieldsMemoryLeakUnitTest {
|
||||
public List<Double> list = new ArrayList<>();
|
||||
|
||||
public void populateList() {
|
||||
for (int i = 0; i < 10000000; i++) {
|
||||
list.add(Math.random());
|
||||
}
|
||||
System.out.println("Debug Point 2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenNonStaticLargeList_whenPopulatingList_thenListGarbageCollected() {
|
||||
System.out.println("Debug Point 1");
|
||||
new NonStaticFieldsMemoryLeakUnitTest().populateList();
|
||||
System.out.println("Debug Point 3");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.memoryleaks.staticfields;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StaticFieldsMemoryLeakUnitTest {
|
||||
public static List<Double> list = new ArrayList<>();
|
||||
|
||||
public void populateList() {
|
||||
for (int i = 0; i < 10000000; i++) {
|
||||
list.add(Math.random());
|
||||
}
|
||||
System.out.println("Debug Point 2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
|
||||
public void givenStaticLargeList_whenPopulatingList_thenListIsNotGarbageCollected() {
|
||||
System.out.println("Debug Point 1");
|
||||
new StaticFieldsDemo().populateList();
|
||||
System.out.println("Debug Point 3");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.nth.root.calculator;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class NthRootCalculatorUnitTest {
|
||||
|
||||
@InjectMocks
|
||||
private NthRootCalculator nthRootCalculator;
|
||||
|
||||
@Test
|
||||
public void giventThatTheBaseIs125_andTheExpIs3_whenCalculateIsCalled_thenTheResultIsTheCorrectOne() {
|
||||
Double result = nthRootCalculator.calculate(125.0, 3.0);
|
||||
assertEquals(result, (Double) 5.0d);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.nth.root.main;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MainUnitTest {
|
||||
@InjectMocks
|
||||
private Main main;
|
||||
|
||||
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
|
||||
private final PrintStream originalOut = System.out;
|
||||
|
||||
@Before
|
||||
public void setUpStreams() {
|
||||
System.setOut(new PrintStream(outContent));
|
||||
}
|
||||
|
||||
@After
|
||||
public void restoreStreams() {
|
||||
System.setOut(originalOut);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThatTheBaseIs125_andTheExpIs3_whenMainIsCalled_thenTheCorrectResultIsPrinted() {
|
||||
main.main(new String[]{"125.0", "3.0"});
|
||||
assertEquals("The 3.0 root of 125.0 equals to 5.0.\n", outContent.toString().replaceAll("\r", ""));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.ternaryoperator;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TernaryOperatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() {
|
||||
int number = 10;
|
||||
String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10";
|
||||
|
||||
assertThat(msg).isEqualTo("Number is less than or equal to 10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() {
|
||||
int exp1 = 0, exp2 = 0;
|
||||
int result = 12 > 10 ? ++exp1 : ++exp2;
|
||||
|
||||
assertThat(exp1).isEqualTo(1);
|
||||
assertThat(exp2).isEqualTo(0);
|
||||
assertThat(result).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() {
|
||||
int exp1 = 0, exp2 = 0;
|
||||
int result = 8 > 10 ? ++exp1 : ++exp2;
|
||||
|
||||
assertThat(exp1).isEqualTo(0);
|
||||
assertThat(exp2).isEqualTo(1);
|
||||
assertThat(result).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANestedCondition_whenUsingTernaryOperator_thenCorrectValueIsReturned() {
|
||||
int number = 6;
|
||||
String msg = number > 10 ? "Number is greater than 10" : number > 5 ? "Number is greater than 5" : "Number is less than or equal to 5";
|
||||
|
||||
assertThat(msg).isEqualTo("Number is greater than 5");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,121 @@
|
|||
package com.baeldung.kotlin
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
|
||||
class StructuralJumpUnitTest {
|
||||
|
||||
@Test
|
||||
fun givenLoop_whenBreak_thenComplete() {
|
||||
var value = ""
|
||||
for (i in "hello_world") {
|
||||
if (i == '_')
|
||||
break
|
||||
value += i.toString()
|
||||
}
|
||||
assertEquals("hello", value)
|
||||
}
|
||||
@Test
|
||||
fun givenLoop_whenBreakWithLabel_thenComplete() {
|
||||
var value = ""
|
||||
outer_loop@ for (i in 'a'..'d') {
|
||||
for (j in 1..3) {
|
||||
value += "" + i + j
|
||||
if (i == 'b' && j == 1)
|
||||
break@outer_loop
|
||||
}
|
||||
}
|
||||
assertEquals("a1a2a3b1", value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenLoop_whenContinue_thenComplete() {
|
||||
var result = ""
|
||||
for (i in "hello_world") {
|
||||
if (i == '_')
|
||||
continue
|
||||
result += i
|
||||
}
|
||||
assertEquals("helloworld", result)
|
||||
}
|
||||
@Test
|
||||
fun givenLoop_whenContinueWithLabel_thenComplete() {
|
||||
var result = ""
|
||||
outer_loop@ for (i in 'a'..'c') {
|
||||
for (j in 1..3) {
|
||||
if (i == 'b')
|
||||
continue@outer_loop
|
||||
result += "" + i + j
|
||||
}
|
||||
}
|
||||
assertEquals("a1a2a3c1c2c3", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenLambda_whenReturn_thenComplete() {
|
||||
var result = returnInLambda();
|
||||
assertEquals("hello", result)
|
||||
}
|
||||
|
||||
private fun returnInLambda(): String {
|
||||
var result = ""
|
||||
"hello_world".forEach {
|
||||
// non-local return directly to the caller
|
||||
if (it == '_') return result
|
||||
result += it.toString()
|
||||
}
|
||||
//this line won't be reached
|
||||
return result;
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenLambda_whenReturnWithExplicitLabel_thenComplete() {
|
||||
var result = ""
|
||||
"hello_world".forEach lit@{
|
||||
if (it == '_') {
|
||||
// local return to the caller of the lambda, i.e. the forEach loop
|
||||
return@lit
|
||||
}
|
||||
result += it.toString()
|
||||
}
|
||||
assertEquals("helloworld", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenLambda_whenReturnWithImplicitLabel_thenComplete() {
|
||||
var result = ""
|
||||
"hello_world".forEach {
|
||||
if (it == '_') {
|
||||
// local return to the caller of the lambda, i.e. the forEach loop
|
||||
return@forEach
|
||||
}
|
||||
result += it.toString()
|
||||
}
|
||||
assertEquals("helloworld", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenAnonymousFunction_return_thenComplete() {
|
||||
var result = ""
|
||||
"hello_world".forEach(fun(element) {
|
||||
// local return to the caller of the anonymous fun, i.e. the forEach loop
|
||||
if (element == '_') return
|
||||
result += element.toString()
|
||||
})
|
||||
assertEquals("helloworld", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenAnonymousFunction_returnToLabel_thenComplete() {
|
||||
var result = ""
|
||||
run loop@{
|
||||
"hello_world".forEach {
|
||||
// non-local return from the lambda passed to run
|
||||
if (it == '_') return@loop
|
||||
result += it.toString()
|
||||
}
|
||||
}
|
||||
assertEquals("hello", result)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
<?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>flyway-cdi-extension</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0.SP1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jboss.weld.se</groupId>
|
||||
<artifactId>weld-se-core</artifactId>
|
||||
<version>3.0.5.Final</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
<version>5.1.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-jdbc</artifactId>
|
||||
<version>8.5.33</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>1.3.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.197</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,74 @@
|
|||
package com.baeldung.cdi.extension;
|
||||
|
||||
import org.apache.tomcat.jdbc.pool.DataSource;
|
||||
import org.flywaydb.core.Flyway;
|
||||
|
||||
import javax.annotation.sql.DataSourceDefinition;
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import javax.enterprise.event.Observes;
|
||||
import javax.enterprise.inject.Any;
|
||||
import javax.enterprise.inject.Default;
|
||||
import javax.enterprise.inject.literal.InjectLiteral;
|
||||
import javax.enterprise.inject.spi.*;
|
||||
import javax.enterprise.util.AnnotationLiteral;
|
||||
|
||||
|
||||
/**
|
||||
* Flyway is now under CDI container like:
|
||||
*
|
||||
* @ApplicationScoped
|
||||
* @FlywayType public class Flyway{
|
||||
* @Inject setDataSource(DataSource dataSource){
|
||||
* //...
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
|
||||
public class FlywayExtension implements Extension {
|
||||
|
||||
DataSourceDefinition dataSourceDefinition = null;
|
||||
|
||||
public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) {
|
||||
bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName());
|
||||
}
|
||||
|
||||
public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType<?> patEvent) {
|
||||
AnnotatedType at = patEvent.getAnnotatedType();
|
||||
dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class);
|
||||
}
|
||||
|
||||
public void processAnnotatedType(@Observes ProcessAnnotatedType<Flyway> patEvent) {
|
||||
patEvent.configureAnnotatedType()
|
||||
//Add Scope
|
||||
.add(ApplicationScoped.Literal.INSTANCE)
|
||||
//Add Qualifier
|
||||
.add(new AnnotationLiteral<FlywayType>() {
|
||||
})
|
||||
//Decorate setDataSource(DataSource dataSource){} with @Inject
|
||||
.filterMethods(annotatedMethod -> {
|
||||
return annotatedMethod.getParameters().size() == 1 &&
|
||||
annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class);
|
||||
})
|
||||
.findFirst().get().add(InjectLiteral.INSTANCE);
|
||||
}
|
||||
|
||||
void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) {
|
||||
abdEvent.addBean()
|
||||
.types(javax.sql.DataSource.class, DataSource.class)
|
||||
.qualifiers(new AnnotationLiteral<Default>() {}, new AnnotationLiteral<Any>() {})
|
||||
.scope(ApplicationScoped.class)
|
||||
.name(DataSource.class.getName())
|
||||
.beanClass(DataSource.class)
|
||||
.createWith(creationalContext -> {
|
||||
DataSource instance = new DataSource();
|
||||
instance.setUrl(dataSourceDefinition.url());
|
||||
instance.setDriverClassName(dataSourceDefinition.className());
|
||||
return instance;
|
||||
});
|
||||
}
|
||||
|
||||
void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) {
|
||||
Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral<FlywayType>() {}).get();
|
||||
flyway.migrate();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.cdi.extension;
|
||||
|
||||
import javax.inject.Qualifier;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.*;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({FIELD, METHOD, PARAMETER, TYPE})
|
||||
@Qualifier
|
||||
public @interface FlywayType {
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.cdi.extension;
|
||||
|
||||
import javax.annotation.sql.DataSourceDefinition;
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import javax.enterprise.inject.se.SeContainer;
|
||||
import javax.enterprise.inject.se.SeContainerInitializer;
|
||||
|
||||
@ApplicationScoped
|
||||
@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb")
|
||||
public class MainApp {
|
||||
public static void main(String[] args) {
|
||||
SeContainerInitializer initializer = SeContainerInitializer.newInstance();
|
||||
try (SeContainer container = initializer.initialize()) {
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
<beans version="2.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||
bean-discovery-mode="annotated">
|
||||
</beans>
|
|
@ -0,0 +1,2 @@
|
|||
com.baeldung.cdi.extension.FlywayExtension
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
create table PERSON (
|
||||
ID int not null,
|
||||
NAME varchar(100) not null
|
||||
);
|
|
@ -0,0 +1,3 @@
|
|||
insert into PERSON (ID, NAME) values (1, 'Axel');
|
||||
insert into PERSON (ID, NAME) values (2, 'Mr. Foo');
|
||||
insert into PERSON (ID, NAME) values (3, 'Ms. Bar');
|
|
@ -65,6 +65,7 @@
|
|||
<properties>
|
||||
<flyway-core.version>5.0.2</flyway-core.version>
|
||||
<flyway-maven-plugin.version>5.0.2</flyway-maven-plugin.version>
|
||||
<h2.version>1.4.195</h2.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -16,7 +16,7 @@ import org.springframework.test.context.junit4.SpringRunner;
|
|||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
|
||||
@ContextConfiguration(classes = FlywayCallbackTestConfig.class)
|
||||
public class FlywayApplicationTest {
|
||||
public class FlywayApplicationUnitTest {
|
||||
|
||||
private Log log = LogFactory.getLog(getClass());
|
||||
|
130
gson/pom.xml
130
gson/pom.xml
|
@ -1,73 +1,73 @@
|
|||
<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>gson</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>gson</name>
|
||||
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>gson</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>gson</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<!-- marshalling -->
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<!-- marshalling -->
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>gson</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
<build>
|
||||
<finalName>gson</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- marshalling -->
|
||||
<gson.version>2.8.0</gson.version>
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<joda-time.version>2.9.6</joda-time.version>
|
||||
<properties>
|
||||
<!-- marshalling -->
|
||||
<gson.version>2.8.0</gson.version>
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<joda-time.version>2.9.6</joda-time.version>
|
||||
<lombok.version>1.16.10</lombok.version>
|
||||
</properties>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,36 @@
|
|||
package org.baeldung.gson.entities;
|
||||
|
||||
public class Employee {
|
||||
private int id;
|
||||
private String name;
|
||||
private String address;
|
||||
|
||||
public Employee(int id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
package org.baeldung.gson.serialization;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.baeldung.gson.entities.Employee;
|
||||
|
||||
import com.google.gson.*;
|
||||
|
||||
public class HashMapDeserializer implements JsonDeserializer<HashMap<String, Object>> {
|
||||
|
||||
@Override
|
||||
public HashMap<String, Object> deserialize(JsonElement elem, Type type, JsonDeserializationContext context) throws JsonParseException {
|
||||
HashMap<String, Object> map = new HashMap<>();
|
||||
for (Map.Entry<String, JsonElement> entry : elem.getAsJsonObject().entrySet()) {
|
||||
JsonElement jsonValue = entry.getValue();
|
||||
Object value = null;
|
||||
if (jsonValue.isJsonPrimitive()) {
|
||||
value = toPrimitive(jsonValue.getAsJsonPrimitive(), context);
|
||||
} else {
|
||||
value = context.deserialize(jsonValue, Employee.class);
|
||||
}
|
||||
map.put(entry.getKey(), value);
|
||||
}
|
||||
return map;
|
||||
|
||||
}
|
||||
|
||||
private Object toPrimitive(JsonPrimitive jsonValue, JsonDeserializationContext context) {
|
||||
if (jsonValue.isBoolean())
|
||||
return jsonValue.getAsBoolean();
|
||||
else if (jsonValue.isString())
|
||||
return jsonValue.getAsString();
|
||||
else {
|
||||
BigDecimal bigDec = jsonValue.getAsBigDecimal();
|
||||
Long l;
|
||||
Integer i;
|
||||
if ((i = toInteger(bigDec)) != null) {
|
||||
return i;
|
||||
} else if ((l = toLong(bigDec)) != null) {
|
||||
return l;
|
||||
} else {
|
||||
return bigDec.doubleValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Long toLong(BigDecimal val) {
|
||||
try {
|
||||
return val.toBigIntegerExact().longValue();
|
||||
} catch (ArithmeticException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Integer toInteger(BigDecimal val) {
|
||||
try {
|
||||
return val.intValueExact();
|
||||
} catch (ArithmeticException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -7,13 +7,13 @@
|
|||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
<logger name="org.springframework" level="WARN"/>
|
||||
<logger name="org.springframework.transaction" level="WARN"/>
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN"/>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,86 @@
|
|||
package org.baeldung.gson.deserialization;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.baeldung.gson.entities.Employee;
|
||||
import org.baeldung.gson.serialization.HashMapDeserializer;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.google.gson.internal.LinkedTreeMap;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
|
||||
public class HashMapDeserializationUnitTest {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(HashMapDeserializationUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void whenUsingHashMapClass_thenShouldReturnMapWithDefaultClasses() {
|
||||
|
||||
String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, "
|
||||
+ "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
|
||||
|
||||
Gson gson = new Gson();
|
||||
HashMap map = gson.fromJson(jsonString, HashMap.class);
|
||||
|
||||
logger.info("The converted map: {}", map);
|
||||
Assert.assertEquals(4, map.size());
|
||||
Assert.assertEquals(Double.class, map.get("employee.salary").getClass());
|
||||
Assert.assertEquals(LinkedTreeMap.class, map.get("employee").getClass());
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = JsonSyntaxException.class)
|
||||
public void whenUsingJsonStringWithDuplicateKey_thenShouldThrowJsonSyntaxException() {
|
||||
|
||||
String jsonString = "{'employee.name':'Bob', 'employee.name':'Jenny','employee.salary':10000, "
|
||||
+ "'employee.active':true, " + "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
|
||||
|
||||
Gson gson = new Gson();
|
||||
HashMap map = gson.fromJson(jsonString, HashMap.class);
|
||||
|
||||
logger.info("The converted map: {}", map);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingTypeToken_thenShouldReturnMapWithProperClass() {
|
||||
|
||||
String jsonString = "{'Bob':{'id':10, 'name': 'Bob Willis', 'address':'UK'},"
|
||||
+ "'Jenny':{'id':10, 'name': 'Jenny McCarthy', 'address':'USA'}, "
|
||||
+ "'Steve':{'id':10, 'name': 'Steven Waugh', 'address':'Australia'}}";
|
||||
|
||||
Gson gson = new Gson();
|
||||
Type empMapType = new TypeToken<HashMap<String, Employee>>(){}.getType();
|
||||
HashMap<String, Employee> nameEmployeeMap = gson.fromJson(jsonString, empMapType);
|
||||
|
||||
logger.info("The converted map: {}", nameEmployeeMap);
|
||||
Assert.assertEquals(3, nameEmployeeMap.size());
|
||||
Assert.assertEquals(Employee.class, nameEmployeeMap.get("Bob").getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCustomDeserializer_thenShouldReturnMapWithProperClass() {
|
||||
|
||||
String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, "
|
||||
+ "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
|
||||
|
||||
Type type = new TypeToken<HashMap<String, Object>>(){}.getType();
|
||||
Gson gson = new GsonBuilder()
|
||||
.registerTypeAdapter(type, new HashMapDeserializer())
|
||||
.create();
|
||||
HashMap<String, Object> blendedMap = gson.fromJson(jsonString, type);
|
||||
|
||||
logger.info("The converted map: {}", blendedMap);
|
||||
Assert.assertEquals(4, blendedMap.size());
|
||||
Assert.assertEquals(Integer.class, blendedMap.get("employee.salary").getClass());
|
||||
Assert.assertEquals(Employee.class, blendedMap.get("employee").getClass());
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN"/>
|
||||
<logger name="org.springframework.transaction" level="WARN"/>
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN"/>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
</configuration>
|
|
@ -18,9 +18,9 @@ import org.junit.Test;
|
|||
import com.stackify.models.User;
|
||||
import com.stackify.services.MyService;
|
||||
|
||||
public class MyServiceTest {
|
||||
public class MyServiceUnitTest {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(MyServiceTest.class);
|
||||
private static final Logger logger = LogManager.getLogger(MyServiceUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void testService() {
|
|
@ -9,7 +9,7 @@ import com.stackify.models.Employee;
|
|||
|
||||
import ch.qos.logback.classic.Level;
|
||||
|
||||
public class EmployeeServiceTest {
|
||||
public class EmployeeServiceUnitTest {
|
||||
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
|
||||
private EmployeeService employeeService = new EmployeeService();
|
|
@ -12,7 +12,7 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.M5</version>
|
||||
<version>2.0.0.RELEASE</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
|
|
|
@ -11,7 +11,7 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.M6</version>
|
||||
<version>2.0.0.RELEASE</version>
|
||||
<relativePath />
|
||||
</parent>
|
||||
|
||||
|
|
|
@ -6,7 +6,7 @@ import io.restassured.RestAssured;
|
|||
import static io.restassured.RestAssured.*;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
|
||||
public class UserServiceTest {
|
||||
public class UserServiceLiveTest {
|
||||
@Test
|
||||
public void whenAddUser_thenGetUserOk() {
|
||||
RestAssured.baseURI = "http://localhost:8080/rest-server";
|
|
@ -1,56 +0,0 @@
|
|||
package com.baeldung.hibernate.proxy;
|
||||
|
||||
import org.hibernate.annotations.BatchSize;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
|
||||
@Entity
|
||||
@BatchSize(size = 5)
|
||||
public class BatchEmployee implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue (strategy = GenerationType.SEQUENCE)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
private Boss boss;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@Column(name = "surname")
|
||||
private String surname;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Boss getBoss() {
|
||||
return boss;
|
||||
}
|
||||
|
||||
public void setBoss(Boss boss) {
|
||||
this.boss = boss;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getSurname() {
|
||||
return surname;
|
||||
}
|
||||
|
||||
public void setSurname(String surname) {
|
||||
this.surname = surname;
|
||||
}
|
||||
}
|
|
@ -1,49 +0,0 @@
|
|||
package com.baeldung.hibernate.proxy;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
|
||||
@Entity
|
||||
public class Boss implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@Column(name = "surname")
|
||||
private String surname;
|
||||
|
||||
public Boss() { }
|
||||
|
||||
public Boss(String name, String surname) {
|
||||
this.name = name;
|
||||
this.surname = surname;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getSurname() {
|
||||
return surname;
|
||||
}
|
||||
|
||||
public void setSurname(String surname) {
|
||||
this.surname = surname;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
package com.baeldung.hibernate.proxy;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
public class Company implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@OneToMany
|
||||
@JoinColumn(name = "workplace_id")
|
||||
private Set<Employee> employees = new HashSet<>();
|
||||
|
||||
public Company() { }
|
||||
|
||||
public Company(String name) {
|
||||
this.name = 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;
|
||||
}
|
||||
|
||||
public Set<Employee> getEmployees() {
|
||||
return this.employees;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Company company = (Company) o;
|
||||
return Objects.equals(id, company.id) &&
|
||||
Objects.equals(name, company.name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, name);
|
||||
}
|
||||
}
|
|
@ -1,9 +1,13 @@
|
|||
package com.baeldung.hibernate.proxy;
|
||||
|
||||
import org.hibernate.annotations.BatchSize;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@BatchSize(size = 5)
|
||||
public class Employee implements Serializable {
|
||||
|
||||
@Id
|
||||
|
@ -11,13 +15,18 @@ public class Employee implements Serializable {
|
|||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
private Boss boss;
|
||||
@JoinColumn(name = "workplace_id")
|
||||
private Company workplace;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
@Column(name = "first_name")
|
||||
private String firstName;
|
||||
|
||||
@Column(name = "surname")
|
||||
private String surname;
|
||||
public Employee() { }
|
||||
|
||||
public Employee(Company workplace, String firstName) {
|
||||
this.workplace = workplace;
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
|
@ -27,27 +36,34 @@ public class Employee implements Serializable {
|
|||
this.id = id;
|
||||
}
|
||||
|
||||
public Boss getBoss() {
|
||||
return boss;
|
||||
public Company getWorkplace() {
|
||||
return workplace;
|
||||
}
|
||||
|
||||
public void setBoss(Boss boss) {
|
||||
this.boss = boss;
|
||||
public void setWorkplace(Company workplace) {
|
||||
this.workplace = workplace;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getSurname() {
|
||||
return surname;
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Employee employee = (Employee) o;
|
||||
return Objects.equals(id, employee.id) &&
|
||||
Objects.equals(workplace, employee.workplace) &&
|
||||
Objects.equals(firstName, employee.firstName);
|
||||
}
|
||||
|
||||
public void setSurname(String surname) {
|
||||
this.surname = surname;
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, workplace, firstName);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -30,7 +30,7 @@ public class HibernateUtil {
|
|||
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
metadataSources.addPackage("com.baeldung.hibernate.proxy");
|
||||
metadataSources.addAnnotatedClass(Boss.class);
|
||||
metadataSources.addAnnotatedClass(Company.class);
|
||||
metadataSources.addAnnotatedClass(Employee.class);
|
||||
|
||||
Metadata metadata = metadataSources.buildMetadata();
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package com.baeldung.hibernate.proxy;
|
||||
|
||||
import org.hibernate.*;
|
||||
import org.hibernate.proxy.HibernateProxy;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
@ -8,25 +9,31 @@ import org.junit.Test;
|
|||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class HibernateProxyUnitTest {
|
||||
|
||||
private SessionFactory factory;
|
||||
|
||||
private Session session;
|
||||
|
||||
private Company workplace;
|
||||
|
||||
private Employee albert;
|
||||
|
||||
private Employee bob;
|
||||
|
||||
private Employee charlotte;
|
||||
|
||||
@Before
|
||||
public void init(){
|
||||
try {
|
||||
session = HibernateUtil.getSessionFactory("hibernate.properties")
|
||||
.openSession();
|
||||
factory = HibernateUtil.getSessionFactory("hibernate.properties");
|
||||
session = factory.openSession();
|
||||
} catch (HibernateException | IOException e) {
|
||||
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
|
||||
}
|
||||
|
||||
Boss boss = new Boss("Eduard", "Freud");
|
||||
session.save(boss);
|
||||
}
|
||||
|
||||
@After
|
||||
|
@ -36,40 +43,114 @@ public class HibernateProxyUnitTest {
|
|||
}
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
@Test
|
||||
public void givenAnInexistentEmployeeId_whenUseGetMethod_thenReturnNull() {
|
||||
Employee employee = session.get(Employee.class, new Long(14));
|
||||
Employee employee = session.get(Employee.class, 14L);
|
||||
assertNull(employee);
|
||||
employee.getId();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnInexistentEmployeeId_whenUseLoadMethod_thenReturnAProxy() {
|
||||
Employee employee = session.load(Employee.class, new Long(14));
|
||||
@Test(expected = ObjectNotFoundException.class)
|
||||
public void givenAnNonExistentEmployeeId_whenUseLoadMethod_thenThrowObjectNotFoundException() {
|
||||
Employee employee = session.load(Employee.class, 999L);
|
||||
assertNotNull(employee);
|
||||
employee.getFirstName();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABatchEmployeeList_whenSaveOne_thenSaveTheWholeBatch() {
|
||||
Transaction transaction = session.beginTransaction();
|
||||
public void givenAnNonExistentEmployeeId_whenUseLoadMethod_thenReturnAProxy() {
|
||||
Employee employee = session.load(Employee.class, 14L);
|
||||
assertNotNull(employee);
|
||||
assertTrue(employee instanceof HibernateProxy);
|
||||
}
|
||||
|
||||
for (long i = 1; i <= 5; i++) {
|
||||
Employee employee = new Employee();
|
||||
employee.setName("Employee " + i);
|
||||
session.save(employee);
|
||||
}
|
||||
@Test
|
||||
public void givenAnEmployeeFromACompany_whenUseLoadMethod_thenCompanyIsAProxy() {
|
||||
Transaction tx = session.beginTransaction();
|
||||
|
||||
this.workplace = new Company("Bizco");
|
||||
session.save(workplace);
|
||||
|
||||
this.albert = new Employee(workplace, "Albert");
|
||||
session.save(albert);
|
||||
|
||||
//After this line is possible to see all the insertions in the logs
|
||||
session.flush();
|
||||
session.clear();
|
||||
transaction.commit();
|
||||
|
||||
transaction = session.beginTransaction();
|
||||
tx.commit();
|
||||
this.session = factory.openSession();
|
||||
|
||||
List<Employee> employeeList = session.createQuery("from Employee")
|
||||
.setCacheMode(CacheMode.IGNORE).getResultList();
|
||||
Employee proxyAlbert = session.load(Employee.class, albert.getId());
|
||||
assertTrue(proxyAlbert instanceof HibernateProxy);
|
||||
|
||||
assertEquals(employeeList.size(), 5);
|
||||
transaction.commit();
|
||||
// with many-to-one lazy-loading, associations remain proxies
|
||||
assertTrue(proxyAlbert.getWorkplace() instanceof HibernateProxy);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACompanyWithEmployees_whenUseLoadMethod_thenEmployeesAreProxies() {
|
||||
Transaction tx = session.beginTransaction();
|
||||
|
||||
this.workplace = new Company("Bizco");
|
||||
session.save(workplace);
|
||||
|
||||
this.albert = new Employee(workplace, "Albert");
|
||||
session.save(albert);
|
||||
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
tx.commit();
|
||||
this.session = factory.openSession();
|
||||
|
||||
Company proxyBizco = session.load(Company.class, workplace.getId());
|
||||
assertTrue(proxyBizco instanceof HibernateProxy);
|
||||
|
||||
// with one-to-many, associations aren't proxies
|
||||
assertFalse(proxyBizco.getEmployees().iterator().next() instanceof HibernateProxy);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThreeEmployees_whenLoadThemWithBatch_thenReturnAllOfThemWithOneQuery() {
|
||||
Transaction tx = session.beginTransaction();
|
||||
|
||||
//We are saving 3 entities with one flush
|
||||
|
||||
this.workplace = new Company("Bizco");
|
||||
session.save(workplace);
|
||||
|
||||
this.albert = new Employee(workplace, "Albert");
|
||||
session.save(albert);
|
||||
|
||||
this.bob = new Employee(workplace, "Bob");
|
||||
session.save(bob);
|
||||
|
||||
this.charlotte = new Employee(workplace, "Charlotte");
|
||||
session.save(charlotte);
|
||||
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
tx.commit();
|
||||
session = factory.openSession();
|
||||
|
||||
Employee proxyAlbert = session.load(Employee.class, this.albert.getId());
|
||||
assertNotNull(proxyAlbert);
|
||||
assertTrue(proxyAlbert instanceof HibernateProxy);
|
||||
|
||||
Employee proxyBob = session.load(Employee.class, this.bob.getId());
|
||||
assertNotNull(proxyBob);
|
||||
assertTrue(proxyBob instanceof HibernateProxy);
|
||||
|
||||
Employee proxyCharlotte = session.load(Employee.class, this.charlotte.getId());
|
||||
assertNotNull(proxyCharlotte);
|
||||
assertTrue(proxyCharlotte instanceof HibernateProxy);
|
||||
|
||||
//Fetching from database 3 entities with one call
|
||||
//Select from log: where employee0_.id in (?, ?, ?)
|
||||
proxyAlbert.getFirstName();
|
||||
|
||||
assertEquals(proxyAlbert, this.albert);
|
||||
assertEquals(proxyBob, this.bob);
|
||||
assertEquals(proxyCharlotte, this.charlotte);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.date;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
import java.util.Date;
|
||||
import org.joda.time.Years;
|
||||
|
||||
public class AgeCalculator {
|
||||
|
||||
public int calculateAge(LocalDate birthDate, LocalDate currentDate) {
|
||||
// validate inputs ...
|
||||
return Period.between(birthDate, currentDate)
|
||||
.getYears();
|
||||
}
|
||||
|
||||
public int calculateAgeWithJodaTime(org.joda.time.LocalDate birthDate, org.joda.time.LocalDate currentDate) {
|
||||
// validate inputs ...
|
||||
Years age = Years.yearsBetween(birthDate, currentDate);
|
||||
return age.getYears();
|
||||
}
|
||||
|
||||
public int calculateAgeWithJava7(Date birthDate, Date currentDate) {
|
||||
// validate inputs ...
|
||||
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
|
||||
int d1 = Integer.parseInt(formatter.format(birthDate));
|
||||
int d2 = Integer.parseInt(formatter.format(currentDate));
|
||||
int age = (d2 - d1) / 10000;
|
||||
return age;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.date;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Date;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class AgeCalculatorUnitTest {
|
||||
AgeCalculator ageCalculator = new AgeCalculator();
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_whenCalculateAge_thenOk() {
|
||||
assertEquals(10, ageCalculator.calculateAge(LocalDate.of(2008, 5, 20), LocalDate.of(2018, 9, 20)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJodaTime_whenCalculateAge_thenOk() {
|
||||
assertEquals(10, ageCalculator.calculateAgeWithJodaTime(new org.joda.time.LocalDate(2008, 5, 20), new org.joda.time.LocalDate(2018, 9, 20)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenCalculateAge_thenOk() throws ParseException {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
|
||||
Date birthDate = sdf.parse("2008-05-20");
|
||||
Date currentDate = sdf.parse("2018-09-20");
|
||||
assertEquals(10, ageCalculator.calculateAgeWithJava7(birthDate, currentDate));
|
||||
}
|
||||
|
||||
}
|
|
@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit;
|
|||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DateDiffTest {
|
||||
public class DateDiffUnitTest {
|
||||
@Test
|
||||
public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.percentage;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class PercentageCalculator {
|
||||
|
||||
public double calculatePercentage(double obtained,double total){
|
||||
return obtained*100/total;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
PercentageCalculator pc = new PercentageCalculator();
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Enter obtained marks:");
|
||||
double obtained = in.nextDouble();
|
||||
System.out.println("Enter total marks:");
|
||||
double total =in.nextDouble();
|
||||
System.out.println("Percentage obtained :"+pc.calculatePercentage(obtained,total));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.maths;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class MathSinUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAnAngleInDegrees_whenUsingToRadians_thenResultIsInRadians() {
|
||||
double angleInDegrees = 30;
|
||||
double sinForDegrees = Math.sin(Math.toRadians(angleInDegrees)); // 0.5
|
||||
|
||||
double thirtyDegreesInRadians = 1/6 * Math.PI;
|
||||
double sinForRadians = Math.sin(thirtyDegreesInRadians); // 0.5
|
||||
|
||||
assertTrue(sinForDegrees == sinForRadians);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.percentage;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PercentageCalculatorUnitTest {
|
||||
private PercentageCalculator pc = new PercentageCalculator();
|
||||
|
||||
@Test
|
||||
public void whenPass2Integers_thenShouldCalculatePercentage(){
|
||||
Assert.assertEquals("Result not as expected",
|
||||
50.0,pc.calculatePercentage(50,100),0.1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPassObtainedMarksAsDouble_thenShouldCalculatePercentage(){
|
||||
Assert.assertEquals("Result not as expected",5.05,
|
||||
pc.calculatePercentage(50.5,1000),0.1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPassTotalMarksAsDouble_thenShouldCalculatePercentage(){
|
||||
Assert.assertEquals("Result not as expected",19.6,
|
||||
pc.calculatePercentage(5,25.5),0.1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPass2DoubleNumbers_thenShouldCalculatePercentage(){
|
||||
Assert.assertEquals("Result not as expected",20,
|
||||
pc.calculatePercentage(5.5,27.5),0.1);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.collection;
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
126
javaxval/pom.xml
126
javaxval/pom.xml
|
@ -1,55 +1,73 @@
|
|||
<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>javaxval</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator-annotation-processor</artifactId>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>javax.el-api</artifactId>
|
||||
<version>${javax.el-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.web</groupId>
|
||||
<artifactId>javax.el</artifactId>
|
||||
<version>${javax.el.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<validation-api.version>2.0.1.Final</validation-api.version>
|
||||
<hibernate-validator.version>6.0.7.Final</hibernate-validator.version>
|
||||
<javax.el-api.version>3.0.0</javax.el-api.version>
|
||||
<javax.el.version>2.2.6</javax.el.version>
|
||||
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
|
||||
</properties>
|
||||
|
||||
<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>javaxval</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>${validation-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator-annotation-processor</artifactId>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>javax.el-api</artifactId>
|
||||
<version>${javax.el-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.web</groupId>
|
||||
<artifactId>javax.el</artifactId>
|
||||
<version>${javax.el.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<validation-api.version>2.0.1.Final</validation-api.version>
|
||||
<hibernate-validator.version>6.0.7.Final</hibernate-validator.version>
|
||||
<javax.el-api.version>3.0.0</javax.el-api.version>
|
||||
<javax.el.version>2.2.6</javax.el.version>
|
||||
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,14 @@
|
|||
package org.baeldung.javabeanconstraints.appplication;
|
||||
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import org.baeldung.javabeanconstraints.entities.UserNotBlank;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
UserNotBlank user = new UserNotBlank(" ");
|
||||
validator.validate(user).stream().forEach(violation -> System.out.println(violation.getMessage()));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package org.baeldung.javabeanconstraints.entities;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
public class UserNotBlank {
|
||||
|
||||
@NotBlank(message = "Name is mandatory")
|
||||
private final String name;
|
||||
|
||||
public UserNotBlank(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "name=" + name + "}";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package org.baeldung.javabeanconstraints.entities;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
public class UserNotEmpty {
|
||||
|
||||
@NotEmpty(message = "Name is mandatory")
|
||||
private final String name;
|
||||
|
||||
public UserNotEmpty(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "name=" + name + "}";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package org.baeldung.javabeanconstraints.entities;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class UserNotNull {
|
||||
|
||||
@NotNull(message = "Name is mandatory")
|
||||
private final String name;
|
||||
|
||||
public UserNotNull(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "name=" + name + "}";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
package org.baeldung.javabeanconstraints.test;
|
||||
|
||||
import java.util.Set;
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.baeldung.javabeanconstraints.entities.UserNotBlank;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UserNotBlankUnitTest {
|
||||
|
||||
private static Validator validator;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupValidatorInstance() {
|
||||
validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotBlankName_thenNoConstraintViolations() {
|
||||
UserNotBlank user = new UserNotBlank("John");
|
||||
|
||||
Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);
|
||||
|
||||
assertThat(violations.size()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBlankName_thenOneConstraintViolation() {
|
||||
UserNotBlank user = new UserNotBlank(" ");
|
||||
|
||||
Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);
|
||||
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEmptyName_thenOneConstraintViolation() {
|
||||
UserNotBlank user = new UserNotBlank("");
|
||||
|
||||
Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);
|
||||
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullName_thenOneConstraintViolation() {
|
||||
UserNotBlank user = new UserNotBlank(null);
|
||||
|
||||
Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);
|
||||
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenToString_thenCorrect() {
|
||||
UserNotBlank user = new UserNotBlank("John");
|
||||
|
||||
assertThat(user.toString()).isEqualTo("User{name=John}");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package org.baeldung.javabeanconstraints.test;
|
||||
|
||||
import java.util.Set;
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.baeldung.javabeanconstraints.entities.UserNotEmpty;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UserNotEmptyUnitTest {
|
||||
|
||||
private static Validator validator;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupValidatorInstance() {
|
||||
validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotEmptyName_thenNoConstraintViolations() {
|
||||
UserNotEmpty user = new UserNotEmpty("John");
|
||||
|
||||
Set<ConstraintViolation<UserNotEmpty>> violations = validator.validate(user);
|
||||
|
||||
assertThat(violations.size()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEmptyName_thenOneConstraintViolation() {
|
||||
UserNotEmpty user = new UserNotEmpty("");
|
||||
|
||||
Set<ConstraintViolation<UserNotEmpty>> violations = validator.validate(user);
|
||||
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullName_thenOneConstraintViolation() {
|
||||
UserNotEmpty user = new UserNotEmpty(null);
|
||||
|
||||
Set<ConstraintViolation<UserNotEmpty>> violations = validator.validate(user);
|
||||
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenToString_thenCorrect() {
|
||||
UserNotEmpty user = new UserNotEmpty("John");
|
||||
|
||||
assertThat(user.toString()).isEqualTo("User{name=John}");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package org.baeldung.javabeanconstraints.test;
|
||||
|
||||
import java.util.Set;
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.baeldung.javabeanconstraints.entities.UserNotNull;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UserNotNullUnitTest {
|
||||
|
||||
private static Validator validator;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupValidatorInstance() {
|
||||
validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotNullName_thenNoConstraintViolations() {
|
||||
UserNotNull user = new UserNotNull("John");
|
||||
|
||||
Set<ConstraintViolation<UserNotNull>> violations = validator.validate(user);
|
||||
|
||||
assertThat(violations.size()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullName_thenOneConstraintViolation() {
|
||||
UserNotNull user = new UserNotNull(null);
|
||||
|
||||
Set<ConstraintViolation<UserNotNull>> violations = validator.validate(user);
|
||||
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEmptyName_thenNoConstraintViolations() {
|
||||
UserNotNull user = new UserNotNull("");
|
||||
|
||||
Set<ConstraintViolation<UserNotNull>> violations = validator.validate(user);
|
||||
|
||||
assertThat(violations.size()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenToString_thenCorrect() {
|
||||
UserNotNull user = new UserNotNull("John");
|
||||
|
||||
assertThat(user.toString()).isEqualTo("User{name=John}");
|
||||
}
|
||||
}
|
|
@ -6,3 +6,4 @@
|
|||
- [A Guide to Java EE Web-Related Annotations](http://www.baeldung.com/javaee-web-annotations)
|
||||
- [Introduction to Testing with Arquillian](http://www.baeldung.com/arquillian)
|
||||
- [Securing Java EE with Spring Security](http://www.baeldung.com/java-ee-spring-security)
|
||||
- [A Guide to Java EE Web-Related Annotations](https://www.baeldung.com/javaee-web-annotations)
|
|
@ -130,7 +130,7 @@
|
|||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
<configuration>
|
||||
<warSourceDirectory>webapp</warSourceDirectory>
|
||||
<warSourceDirectory>src/main/webapp</warSourceDirectory>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations;
|
||||
package com.baeldung.javaeeannotations;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations;
|
||||
package com.baeldung.javaeeannotations;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
|
@ -1,76 +0,0 @@
|
|||
About the application
|
||||
---------------------
|
||||
This application demonstrates the usage of JavaEE Web Annotations.
|
||||
|
||||
|
||||
Contents of the application
|
||||
---------------------------
|
||||
1. AccountServlet.java - Demonstrates the @WebServlet and @ServletSecurity annotation.
|
||||
|
||||
NOTES: @WebServlet annotation designates the AccountServlet class as a Servlet component.
|
||||
The usage of its parameters 'urlPatterns' & 'initParams' can be observed.
|
||||
An initialization parameter 'type' is being set to denote the type of the bank account.
|
||||
|
||||
@ServletSecurity annotation imposes security constraints on the AccountServlet based on
|
||||
the tomcat-users.xml.
|
||||
|
||||
This code assumes that your tomcat-users.xml looks as follows:
|
||||
|
||||
<role rolename="Admin"/>
|
||||
<role rolename="Member"/>
|
||||
<role rolename="Guest"/>
|
||||
<user username="Annie" password="admin" roles="Admin, Member, Guest" />
|
||||
<user username="Diane" password="coder" roles="Member, Guest" />
|
||||
<user username="Ted" password="newbie" roles="Guest" />
|
||||
|
||||
N.B : To see @ServletSecurity annotation in action, please uncomment the annotation code
|
||||
for @ServletSecurity.
|
||||
|
||||
|
||||
2. BankAppServletContextListener.java - Demonstrates the @WebListener annotation for denoting a class as a ServletContextListener.
|
||||
|
||||
NOTES: Sets a Servlet context attribute ATTR_DEFAULT_LANGUAGE to 'english' on web application start up,
|
||||
which can then be used throughout the application.
|
||||
|
||||
|
||||
3. LogInFilter.java - Demonstrates the @WebFilter annotation.
|
||||
|
||||
NOTES: @WebFilter annotation designates the LogInFilter class as a Filter component.
|
||||
It filters all requests to the bank account servlet and redirects them to
|
||||
the login page.
|
||||
|
||||
N.B : To see @WebFilter annotation in action, please uncomment the annotation code for @WebFilter.
|
||||
|
||||
|
||||
4. UploadCustomerDocumentsServlet.java - Demonstrates the @MultipartConfig annotation.
|
||||
|
||||
NOTES: @MultipartConfig anotation designates the UploadCustomerDocumentsServlet Servlet component,
|
||||
to handle multipart/form-data requests.
|
||||
To see it in action, deploy the web application an access the url: http://<your host>:<your port>/JavaEEAnnotationsSample/upload.jsp
|
||||
Once you upload a file from here, it will get uploaded to D:/custDocs (assuming such a folder exists).
|
||||
|
||||
|
||||
5. index.jsp - This is the welcome page.
|
||||
|
||||
NOTES: You can enter a deposit amount here and click on the 'Deposit' button to see the AccountServlet in action.
|
||||
|
||||
6. login.jsp - All requests to the AccountServlet are redirected to this page, if the LogInFilter is imposed.
|
||||
|
||||
7. upload.jsp - Demonstrates the usage of handling multipart/form-data requests by the UploadCustomerDocumentsServlet.
|
||||
|
||||
|
||||
Building and Running the application
|
||||
------------------------------------
|
||||
To build the application:
|
||||
|
||||
1. Open the project in eclipse
|
||||
2. Right click on it in eclispe and choose Run As > Maven build
|
||||
3. Give 'clean install' under Goals
|
||||
4. This should build the WAR file of the application
|
||||
|
||||
To run the application:
|
||||
|
||||
1. Right click on the project
|
||||
2. Run as > Run on Server
|
||||
3. This will start you Tomcat server and deploy the application (Provided that you have configured Tomcat in your eclipse)
|
||||
4. You should now be able to access the url : http://<your host>:<your port>/JavaEEAnnotationsSample
|
|
@ -1,52 +0,0 @@
|
|||
<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.javaeeannotations</groupId>
|
||||
<artifactId>JavaEEAnnotationsSample</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<name>JavaEEAnnotationsSample</name>
|
||||
<description>JavaEEAnnotationsSample</description>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>1.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet.jsp</groupId>
|
||||
<artifactId>jsp-api</artifactId>
|
||||
<version>2.1</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.4</version>
|
||||
<configuration>
|
||||
<warSourceDirectory>src/main/webapp</warSourceDirectory>
|
||||
<warName>SpringFieldConstructorInjection</warName>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
<finalName>JavaEEAnnotationsSample</finalName>
|
||||
</build>
|
||||
</project>
|
|
@ -1,10 +0,0 @@
|
|||
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
|
||||
|
||||
<login-config>
|
||||
<auth-method>BASIC</auth-method>
|
||||
<realm-name>default</realm-name>
|
||||
</login-config>
|
||||
</web-app>
|
|
@ -1,12 +0,0 @@
|
|||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Login</title>
|
||||
</head>
|
||||
<body>
|
||||
Login Here...
|
||||
</body>
|
||||
</html>
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations;
|
||||
package com.baeldung.javaeeannotations;
|
||||
|
||||
import java.io.IOException;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations;
|
||||
package com.baeldung.javaeeannotations;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
|
@ -38,6 +38,16 @@
|
|||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.passay</groupId>
|
||||
<artifactId>passay</artifactId>
|
||||
<version>1.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.cryptacular</groupId>
|
||||
<artifactId>cryptacular</artifactId>
|
||||
<version>1.2.2</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
|
|
@ -0,0 +1,149 @@
|
|||
package com.baeldung.passay;
|
||||
|
||||
import org.cryptacular.bean.EncodingHashBean;
|
||||
import org.cryptacular.spec.CodecSpec;
|
||||
import org.cryptacular.spec.DigestSpec;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.passay.DictionaryRule;
|
||||
import org.passay.DictionarySubstringRule;
|
||||
import org.passay.DigestHistoryRule;
|
||||
import org.passay.EnglishSequenceData;
|
||||
import org.passay.HistoryRule;
|
||||
import org.passay.IllegalCharacterRule;
|
||||
import org.passay.IllegalRegexRule;
|
||||
import org.passay.IllegalSequenceRule;
|
||||
import org.passay.NumberRangeRule;
|
||||
import org.passay.PasswordData;
|
||||
import org.passay.PasswordValidator;
|
||||
import org.passay.RepeatCharacterRegexRule;
|
||||
import org.passay.RuleResult;
|
||||
import org.passay.SourceRule;
|
||||
import org.passay.UsernameRule;
|
||||
import org.passay.WhitespaceRule;
|
||||
import org.passay.dictionary.ArrayWordList;
|
||||
import org.passay.dictionary.WordListDictionary;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class NegativeMatchingRulesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDictionaryRules_whenValidatePassword_thenFoundIllegalWordsFromDictionary() {
|
||||
ArrayWordList arrayWordList = new ArrayWordList(new String[] { "bar", "foobar" });
|
||||
|
||||
WordListDictionary wordListDictionary = new WordListDictionary(arrayWordList);
|
||||
|
||||
DictionaryRule dictionaryRule = new DictionaryRule(wordListDictionary);
|
||||
DictionarySubstringRule dictionarySubstringRule = new DictionarySubstringRule(wordListDictionary);
|
||||
|
||||
PasswordValidator passwordValidator = new PasswordValidator(dictionaryRule, dictionarySubstringRule);
|
||||
RuleResult validate = passwordValidator.validate(new PasswordData("foobar"));
|
||||
|
||||
assertFalse(validate.isValid());
|
||||
assertEquals("ILLEGAL_WORD:{matchingWord=foobar}", getDetail(validate, 0));
|
||||
assertEquals("ILLEGAL_WORD:{matchingWord=bar}", getDetail(validate, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHistoryRule_whenValidatePassword_thenFoundIllegalWordsFromHistory() {
|
||||
HistoryRule historyRule = new HistoryRule();
|
||||
|
||||
PasswordData passwordData = new PasswordData("123");
|
||||
passwordData.setPasswordReferences(new PasswordData.HistoricalReference("12345"), new PasswordData.HistoricalReference("1234"), new PasswordData.HistoricalReference("123"));
|
||||
|
||||
PasswordValidator passwordValidator = new PasswordValidator(historyRule);
|
||||
|
||||
RuleResult validate = passwordValidator.validate(passwordData);
|
||||
|
||||
assertFalse(validate.isValid());
|
||||
assertEquals("HISTORY_VIOLATION:{historySize=3}", getDetail(validate, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSeveralIllegalRules_whenValidatePassword_thenFoundSeveralIllegalPatterns() {
|
||||
IllegalCharacterRule illegalCharacterRule = new IllegalCharacterRule(new char[] { 'a' });
|
||||
IllegalRegexRule illegalRegexRule = new IllegalRegexRule("\\w{2}\\d{2}");
|
||||
IllegalSequenceRule illegalSequenceRule = new IllegalSequenceRule(EnglishSequenceData.Alphabetical, 3, true);
|
||||
NumberRangeRule numberRangeRule = new NumberRangeRule(1, 10);
|
||||
WhitespaceRule whitespaceRule = new WhitespaceRule();
|
||||
|
||||
PasswordValidator passwordValidator = new PasswordValidator(illegalCharacterRule, illegalRegexRule, illegalSequenceRule, numberRangeRule, whitespaceRule);
|
||||
|
||||
RuleResult validate = passwordValidator.validate(new PasswordData("abcd22 "));
|
||||
|
||||
assertFalse(validate.isValid());
|
||||
assertEquals("ILLEGAL_CHAR:{illegalCharacter=a, matchBehavior=contains}", getDetail(validate, 0));
|
||||
assertEquals("ILLEGAL_MATCH:{match=cd22, pattern=\\w{2}\\d{2}}", getDetail(validate, 1));
|
||||
assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=abc}", getDetail(validate, 2));
|
||||
assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=bcd}", getDetail(validate, 3));
|
||||
assertEquals("ILLEGAL_NUMBER_RANGE:{number=2, matchBehavior=contains}", getDetail(validate, 4));
|
||||
assertEquals("ILLEGAL_WHITESPACE:{whitespaceCharacter= , matchBehavior=contains}", getDetail(validate, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSourceRule_whenValidatePassword_thenFoundIllegalWordsFromSource() {
|
||||
SourceRule sourceRule = new SourceRule();
|
||||
|
||||
PasswordData passwordData = new PasswordData("password");
|
||||
passwordData.setPasswordReferences(new PasswordData.SourceReference("source", "password"));
|
||||
|
||||
PasswordValidator passwordValidator = new PasswordValidator(sourceRule);
|
||||
RuleResult validate = passwordValidator.validate(passwordData);
|
||||
|
||||
assertFalse(validate.isValid());
|
||||
assertEquals("SOURCE_VIOLATION:{source=source}", getDetail(validate, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRepeatCharacterRegexRuleRule_whenValidatePassword_thenFoundIllegalPatternMatches() {
|
||||
RepeatCharacterRegexRule repeatCharacterRegexRule = new RepeatCharacterRegexRule(3);
|
||||
|
||||
PasswordValidator passwordValidator = new PasswordValidator(repeatCharacterRegexRule);
|
||||
|
||||
RuleResult validate = passwordValidator.validate(new PasswordData("aaabbb"));
|
||||
|
||||
assertFalse(validate.isValid());
|
||||
assertEquals("ILLEGAL_MATCH:{match=aaa, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 0));
|
||||
assertEquals("ILLEGAL_MATCH:{match=bbb, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserNameRule_whenValidatePassword_thenFoundUserNameInPassword() {
|
||||
PasswordValidator passwordValidator = new PasswordValidator(new UsernameRule());
|
||||
|
||||
PasswordData passwordData = new PasswordData("testuser1234");
|
||||
passwordData.setUsername("testuser");
|
||||
|
||||
RuleResult validate = passwordValidator.validate(passwordData);
|
||||
|
||||
assertFalse(validate.isValid());
|
||||
assertEquals("ILLEGAL_USERNAME:{username=testuser, matchBehavior=contains}", getDetail(validate, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPasswordAndHashBeanAndEncryptedReferences_whenValidate_thenPasswordValidationShouldPass() {
|
||||
List<PasswordData.Reference> historicalReferences = Arrays.asList(new PasswordData.HistoricalReference("SHA256", "2e4551de804e27aacf20f9df5be3e8cd384ed64488b21ab079fb58e8c90068ab"));
|
||||
PasswordData passwordData = new PasswordData("example!");
|
||||
passwordData.setPasswordReferences(historicalReferences);
|
||||
|
||||
EncodingHashBean encodingHashBean = new EncodingHashBean(new CodecSpec("Base64"), new DigestSpec("SHA256"), 1, false);
|
||||
|
||||
PasswordValidator passwordValidator = new PasswordValidator(new DigestHistoryRule(encodingHashBean));
|
||||
|
||||
RuleResult validate = passwordValidator.validate(passwordData);
|
||||
|
||||
Assert.assertTrue(validate.isValid());
|
||||
}
|
||||
|
||||
private String getDetail(RuleResult validate, int i) {
|
||||
return validate.getDetails()
|
||||
.get(i)
|
||||
.toString();
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue