Merge remote-tracking branch 'eugenp/master'
This commit is contained in:
commit
998d02bfbb
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)
|
||||
|
@ -98,7 +98,7 @@ public class FindKthLargest {
|
||||
|
||||
private int randomPartition(Integer arr[], int left, int right) {
|
||||
int n = right - left + 1;
|
||||
int pivot = (int) (Math.random()) % n;
|
||||
int pivot = (int) (Math.random() * n);
|
||||
swap(arr, left + pivot, right);
|
||||
return partition(arr, left, right);
|
||||
}
|
||||
|
@ -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.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);
|
||||
}
|
||||
}
|
46
apache-geode/pom.xml
Normal file
46
apache-geode/pom.xml
Normal file
@ -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>
|
78
apache-geode/src/main/java/com/baeldung/geode/Customer.java
Normal file
78
apache-geode/src/main/java/com/baeldung/geode/Customer.java
Normal file
@ -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));
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -25,7 +25,6 @@
|
||||
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
|
||||
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
|
||||
- [Spring Security – Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers)
|
||||
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
|
||||
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
|
||||
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
|
||||
|
@ -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;
|
||||
}}
|
32
core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java
Executable file
32
core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java
Executable file
@ -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"));
|
||||
}
|
||||
}
|
22
core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java
Executable file
22
core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java
Executable file
@ -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);
|
||||
}
|
||||
}
|
13
core-java/src/main/java/com/baeldung/nth/root/main/Main.java
Normal file
13
core-java/src/main/java/com/baeldung/nth/root/main/Main.java
Normal file
@ -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,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)
|
||||
}
|
||||
}
|
51
flyway-cdi-extension/pom.xml
Normal file
51
flyway-cdi-extension/pom.xml
Normal file
@ -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');
|
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>
|
36
gson/src/main/java/org/baeldung/gson/entities/Employee.java
Normal file
36
gson/src/main/java/org/baeldung/gson/entities/Employee.java
Normal file
@ -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());
|
||||
|
||||
}
|
||||
|
||||
}
|
19
gson/src/test/resources/logback-test.xml
Normal file
19
gson/src/test/resources/logback-test.xml
Normal file
@ -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>
|
@ -0,0 +1,47 @@
|
||||
package com.baeldung.hibernate.namingstrategy;
|
||||
|
||||
import org.hibernate.boot.model.naming.Identifier;
|
||||
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
|
||||
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
|
||||
|
||||
public class CustomPhysicalNamingStrategy implements PhysicalNamingStrategy {
|
||||
|
||||
@Override
|
||||
public Identifier toPhysicalCatalogName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
|
||||
return convertToSnakeCase(identifier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Identifier toPhysicalColumnName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
|
||||
return convertToSnakeCase(identifier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Identifier toPhysicalSchemaName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
|
||||
return convertToSnakeCase(identifier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Identifier toPhysicalSequenceName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
|
||||
return convertToSnakeCase(identifier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
|
||||
return convertToSnakeCase(identifier);
|
||||
}
|
||||
|
||||
private Identifier convertToSnakeCase(final Identifier identifier) {
|
||||
if (identifier == null) {
|
||||
return identifier;
|
||||
}
|
||||
|
||||
final String regex = "([a-z])([A-Z])";
|
||||
final String replacement = "$1_$2";
|
||||
final String newName = identifier.getText()
|
||||
.replaceAll(regex, replacement)
|
||||
.toLowerCase();
|
||||
return Identifier.toIdentifier(newName);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package com.baeldung.hibernate.namingstrategy;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "Customers")
|
||||
public class Customer {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
@Column(name = "email")
|
||||
private String emailAddress;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
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 String getEmailAddress() {
|
||||
return emailAddress;
|
||||
}
|
||||
|
||||
public void setEmailAddress(String emailAddress) {
|
||||
this.emailAddress = emailAddress;
|
||||
}
|
||||
|
||||
}
|
@ -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();
|
||||
|
@ -0,0 +1,75 @@
|
||||
package com.baeldung.hibernate.namingstrategy;
|
||||
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NamingStrategyLiveTest {
|
||||
|
||||
private Session session;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
try {
|
||||
Configuration configuration = new Configuration();
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.load(Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResourceAsStream("hibernate-namingstrategy.properties"));
|
||||
|
||||
configuration.setProperties(properties);
|
||||
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
|
||||
.build();
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
metadataSources.addAnnotatedClass(Customer.class);
|
||||
|
||||
SessionFactory factory = metadataSources.buildMetadata()
|
||||
.buildSessionFactory();
|
||||
|
||||
session = factory.openSession();
|
||||
} catch (HibernateException | IOException e) {
|
||||
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void close() {
|
||||
if (session != null)
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomPhysicalNamingStrategy() {
|
||||
|
||||
Customer customer = new Customer();
|
||||
customer.setFirstName("first name");
|
||||
customer.setLastName("last name");
|
||||
customer.setEmailAddress("customer@example.com");
|
||||
|
||||
session.beginTransaction();
|
||||
|
||||
Long id = (Long) session.save(customer);
|
||||
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
Object[] result = (Object[]) session.createNativeQuery("select c.first_name, c.last_name, c.email from customers c where c.id = :id")
|
||||
.setParameter("id", id)
|
||||
.getSingleResult();
|
||||
|
||||
}
|
||||
}
|
@ -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,10 @@
|
||||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
|
||||
hibernate.connection.username=sa
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
|
||||
hibernate.physical_naming_strategy=com.baeldung.hibernate.namingstrategy.CustomPhysicalNamingStrategy
|
||||
hibernate.implicit_naming_strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
3
maven-polyglot/README.md
Normal file
3
maven-polyglot/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
To run the maven-polyglot-json-app successfully, you first have to build the maven-polyglot-json-extension module using: mvn clean install.
|
||||
|
||||
Related Articles:
|
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<extensions>
|
||||
<extension>
|
||||
<groupId>com.baeldung.maven.polyglot</groupId>
|
||||
<artifactId>maven-polyglot-json-extension</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</extension>
|
||||
</extensions>
|
34
maven-polyglot/maven-polyglot-json-app/pom.json
Normal file
34
maven-polyglot/maven-polyglot-json-app/pom.json
Normal file
@ -0,0 +1,34 @@
|
||||
{
|
||||
"modelVersion": "4.0.0",
|
||||
"groupId": "com.baeldung.maven.polyglot",
|
||||
"artifactId": "maven-polyglot-json-app",
|
||||
"version": "1.0-SNAPSHOT",
|
||||
"name": "Json Maven Polyglot",
|
||||
"parent": {
|
||||
"groupId": "org.springframework.boot",
|
||||
"artifactId": "spring-boot-starter-parent",
|
||||
"version": "2.0.5.RELEASE",
|
||||
"relativePath": null
|
||||
},
|
||||
"properties": {
|
||||
"project.build.sourceEncoding": "UTF-8",
|
||||
"project.reporting.outputEncoding": "UTF-8",
|
||||
"maven.compiler.source": "1.8",
|
||||
"maven.compiler.target": "1.8",
|
||||
"java.version": "1.8"
|
||||
},
|
||||
"dependencies": [
|
||||
{
|
||||
"groupId": "org.springframework.boot",
|
||||
"artifactId": "spring-boot-starter-web"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"plugins": [
|
||||
{
|
||||
"groupId": "org.springframework.boot",
|
||||
"artifactId": "spring-boot-maven-plugin"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung.maven.polyglot;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@RestController
|
||||
@SpringBootApplication
|
||||
public class MavenPolyglotApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MavenPolyglotApplication.class, args);
|
||||
}
|
||||
|
||||
@GetMapping("/")
|
||||
public String home(){
|
||||
return "Hello JSON Maven Model !";
|
||||
}
|
||||
}
|
@ -0,0 +1,109 @@
|
||||
{
|
||||
"modules": [],
|
||||
"distributionManagement": null,
|
||||
"properties": {
|
||||
"project.reporting.outputEncoding": "UTF-8",
|
||||
"java.version": "1.8",
|
||||
"maven.compiler.source": "1.8",
|
||||
"project.build.sourceEncoding": "UTF-8",
|
||||
"maven.compiler.target": "1.8"
|
||||
},
|
||||
"dependencyManagement": null,
|
||||
"dependencies": [
|
||||
{
|
||||
"groupId": "org.springframework.boot",
|
||||
"artifactId": "spring-boot-starter-web",
|
||||
"version": null,
|
||||
"type": "jar",
|
||||
"classifier": null,
|
||||
"scope": null,
|
||||
"systemPath": null,
|
||||
"exclusions": [],
|
||||
"optional": null,
|
||||
"managementKey": "org.springframework.boot:spring-boot-starter-web:jar"
|
||||
}
|
||||
],
|
||||
"repositories": [],
|
||||
"pluginRepositories": [],
|
||||
"reports": null,
|
||||
"reporting": null,
|
||||
"modelVersion": "4.0.0",
|
||||
"parent": {
|
||||
"groupId": "org.springframework.boot",
|
||||
"artifactId": "spring-boot-starter-parent",
|
||||
"version": "2.0.5.RELEASE",
|
||||
"relativePath": "",
|
||||
"id": "org.springframework.boot:spring-boot-starter-parent:pom:2.0.5.RELEASE"
|
||||
},
|
||||
"groupId": "com.demo.polyglot",
|
||||
"artifactId": "maven-polyglot-app",
|
||||
"version": "1.0.1",
|
||||
"packaging": "jar",
|
||||
"name": "Json Maven Polyglot",
|
||||
"description": null,
|
||||
"url": null,
|
||||
"inceptionYear": null,
|
||||
"organization": null,
|
||||
"licenses": [],
|
||||
"developers": [],
|
||||
"contributors": [],
|
||||
"mailingLists": [],
|
||||
"prerequisites": null,
|
||||
"scm": null,
|
||||
"issueManagement": null,
|
||||
"ciManagement": null,
|
||||
"build": {
|
||||
"plugins": [
|
||||
{
|
||||
"inherited": null,
|
||||
"configuration": null,
|
||||
"inheritanceApplied": true,
|
||||
"groupId": "org.liquibase",
|
||||
"artifactId": "liquibase-maven-plugin",
|
||||
"version": "3.0.5",
|
||||
"extensions": null,
|
||||
"executions": [],
|
||||
"dependencies": [],
|
||||
"goals": null,
|
||||
"key": "org.liquibase:liquibase-maven-plugin",
|
||||
"id": "org.liquibase:liquibase-maven-plugin:3.0.5",
|
||||
"executionsAsMap": {}
|
||||
}
|
||||
],
|
||||
"pluginManagement": null,
|
||||
"defaultGoal": null,
|
||||
"resources": [],
|
||||
"testResources": [],
|
||||
"directory": null,
|
||||
"finalName": null,
|
||||
"filters": [],
|
||||
"sourceDirectory": null,
|
||||
"scriptSourceDirectory": null,
|
||||
"testSourceDirectory": null,
|
||||
"outputDirectory": null,
|
||||
"testOutputDirectory": null,
|
||||
"extensions": [],
|
||||
"pluginsAsMap": {
|
||||
"org.liquibase:liquibase-maven-plugin": {
|
||||
"inherited": null,
|
||||
"configuration": null,
|
||||
"inheritanceApplied": true,
|
||||
"groupId": "org.liquibase",
|
||||
"artifactId": "liquibase-maven-plugin",
|
||||
"version": "3.0.5",
|
||||
"extensions": null,
|
||||
"executions": [],
|
||||
"dependencies": [],
|
||||
"goals": null,
|
||||
"key": "org.liquibase:liquibase-maven-plugin",
|
||||
"id": "org.liquibase:liquibase-maven-plugin:3.0.5",
|
||||
"executionsAsMap": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"profiles": [],
|
||||
"modelEncoding": "UTF-8",
|
||||
"pomFile": null,
|
||||
"id": "com.demo.polyglot:maven-polyglot-app:jar:1.0.1",
|
||||
"projectDirectory": null
|
||||
}
|
47
maven-polyglot/maven-polyglot-json-extension/pom.xml
Normal file
47
maven-polyglot/maven-polyglot-json-extension/pom.xml
Normal file
@ -0,0 +1,47 @@
|
||||
<?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.maven.polyglot</groupId>
|
||||
<artifactId>maven-polyglot-json-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>org.apache.maven</groupId>
|
||||
<artifactId>maven-core</artifactId>
|
||||
<version>3.5.4</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.9.6</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.plexus</groupId>
|
||||
<artifactId>plexus-component-metadata</artifactId>
|
||||
<version>1.7.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>generate-metadata</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -0,0 +1,62 @@
|
||||
package com.demo.polyglot;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.maven.model.Model;
|
||||
import org.apache.maven.model.building.FileModelSource;
|
||||
import org.apache.maven.model.building.ModelProcessor;
|
||||
import org.apache.maven.model.io.ModelParseException;
|
||||
import org.apache.maven.model.io.ModelReader;
|
||||
import org.codehaus.plexus.component.annotations.Component;
|
||||
import org.codehaus.plexus.component.annotations.Requirement;
|
||||
import org.codehaus.plexus.util.ReaderFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
import java.util.Map;
|
||||
|
||||
@Component(role = ModelProcessor.class)
|
||||
public class CustomModelProcessor implements ModelProcessor {
|
||||
|
||||
private static final String XML_POM = "pom.xml";
|
||||
private static final String JSON_POM = "pom.json";
|
||||
private static final String JSON_EXT = ".json";
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Requirement
|
||||
private ModelReader modelReader;
|
||||
|
||||
@Override
|
||||
public File locatePom(File projectDirectory) {
|
||||
File pomFile = new File(projectDirectory, JSON_POM);
|
||||
if (!pomFile.exists()) {
|
||||
pomFile = new File(projectDirectory, XML_POM);
|
||||
}
|
||||
return pomFile;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Model read(InputStream input, Map<String, ?> options) throws IOException, ModelParseException {
|
||||
try (final Reader in = ReaderFactory.newPlatformReader(input)) {
|
||||
return read(in, options);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Model read(Reader reader, Map<String, ?> options) throws IOException, ModelParseException {
|
||||
FileModelSource source = (options != null) ? (FileModelSource) options.get(SOURCE) : null;
|
||||
if (source != null && source.getLocation().endsWith(JSON_EXT)) {
|
||||
Model model = objectMapper.readValue(reader, Model.class);
|
||||
return model;
|
||||
}
|
||||
//It's a normal maven project with a pom.xml file
|
||||
return modelReader.read(reader, options);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Model read(File input, Map<String, ?> options) throws IOException, ModelParseException {
|
||||
return null;
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<extensions>
|
||||
<extension>
|
||||
<groupId>io.takari.polyglot</groupId>
|
||||
<artifactId>polyglot-yaml</artifactId>
|
||||
<version>0.3.1</version>
|
||||
</extension>
|
||||
</extensions>
|
7
maven-polyglot/maven-polyglot-yml-app/pom.yml
Normal file
7
maven-polyglot/maven-polyglot-yml-app/pom.yml
Normal file
@ -0,0 +1,7 @@
|
||||
modelVersion: 4.0.0
|
||||
groupId: com.baeldung.maven.polyglot
|
||||
artifactId: maven-polyglot-yml-app
|
||||
version: 1.0-SNAPSHOT
|
||||
name: 'YAML Demo'
|
||||
|
||||
properties: {maven.compiler.source: 1.8, maven.compiler.target: 1.8}
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.maven.polyglot;
|
||||
|
||||
public class YamlDemoApplication {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Hello Maven Polyglot YAML !");
|
||||
}
|
||||
}
|
@ -0,0 +1,109 @@
|
||||
{
|
||||
"modules": [],
|
||||
"distributionManagement": null,
|
||||
"properties": {
|
||||
"project.reporting.outputEncoding": "UTF-8",
|
||||
"java.version": "1.8",
|
||||
"maven.compiler.source": "1.8",
|
||||
"project.build.sourceEncoding": "UTF-8",
|
||||
"maven.compiler.target": "1.8"
|
||||
},
|
||||
"dependencyManagement": null,
|
||||
"dependencies": [
|
||||
{
|
||||
"groupId": "org.springframework.boot",
|
||||
"artifactId": "spring-boot-starter-web",
|
||||
"version": null,
|
||||
"type": "jar",
|
||||
"classifier": null,
|
||||
"scope": null,
|
||||
"systemPath": null,
|
||||
"exclusions": [],
|
||||
"optional": null,
|
||||
"managementKey": "org.springframework.boot:spring-boot-starter-web:jar"
|
||||
}
|
||||
],
|
||||
"repositories": [],
|
||||
"pluginRepositories": [],
|
||||
"reports": null,
|
||||
"reporting": null,
|
||||
"modelVersion": "4.0.0",
|
||||
"parent": {
|
||||
"groupId": "org.springframework.boot",
|
||||
"artifactId": "spring-boot-starter-parent",
|
||||
"version": "2.0.5.RELEASE",
|
||||
"relativePath": "",
|
||||
"id": "org.springframework.boot:spring-boot-starter-parent:pom:2.0.5.RELEASE"
|
||||
},
|
||||
"groupId": "com.demo.polyglot",
|
||||
"artifactId": "maven-polyglot-app",
|
||||
"version": "1.0.1",
|
||||
"packaging": "jar",
|
||||
"name": "Json Maven Polyglot",
|
||||
"description": null,
|
||||
"url": null,
|
||||
"inceptionYear": null,
|
||||
"organization": null,
|
||||
"licenses": [],
|
||||
"developers": [],
|
||||
"contributors": [],
|
||||
"mailingLists": [],
|
||||
"prerequisites": null,
|
||||
"scm": null,
|
||||
"issueManagement": null,
|
||||
"ciManagement": null,
|
||||
"build": {
|
||||
"plugins": [
|
||||
{
|
||||
"inherited": null,
|
||||
"configuration": null,
|
||||
"inheritanceApplied": true,
|
||||
"groupId": "org.liquibase",
|
||||
"artifactId": "liquibase-maven-plugin",
|
||||
"version": "3.0.5",
|
||||
"extensions": null,
|
||||
"executions": [],
|
||||
"dependencies": [],
|
||||
"goals": null,
|
||||
"key": "org.liquibase:liquibase-maven-plugin",
|
||||
"id": "org.liquibase:liquibase-maven-plugin:3.0.5",
|
||||
"executionsAsMap": {}
|
||||
}
|
||||
],
|
||||
"pluginManagement": null,
|
||||
"defaultGoal": null,
|
||||
"resources": [],
|
||||
"testResources": [],
|
||||
"directory": null,
|
||||
"finalName": null,
|
||||
"filters": [],
|
||||
"sourceDirectory": null,
|
||||
"scriptSourceDirectory": null,
|
||||
"testSourceDirectory": null,
|
||||
"outputDirectory": null,
|
||||
"testOutputDirectory": null,
|
||||
"extensions": [],
|
||||
"pluginsAsMap": {
|
||||
"org.liquibase:liquibase-maven-plugin": {
|
||||
"inherited": null,
|
||||
"configuration": null,
|
||||
"inheritanceApplied": true,
|
||||
"groupId": "org.liquibase",
|
||||
"artifactId": "liquibase-maven-plugin",
|
||||
"version": "3.0.5",
|
||||
"extensions": null,
|
||||
"executions": [],
|
||||
"dependencies": [],
|
||||
"goals": null,
|
||||
"key": "org.liquibase:liquibase-maven-plugin",
|
||||
"id": "org.liquibase:liquibase-maven-plugin:3.0.5",
|
||||
"executionsAsMap": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"profiles": [],
|
||||
"modelEncoding": "UTF-8",
|
||||
"pomFile": null,
|
||||
"id": "com.demo.polyglot:maven-polyglot-app:jar:1.0.1",
|
||||
"projectDirectory": null
|
||||
}
|
311
pom.xml
311
pom.xml
@ -290,7 +290,7 @@
|
||||
<profiles>
|
||||
|
||||
<profile>
|
||||
<id>default</id>
|
||||
<id>default-first</id>
|
||||
<build>
|
||||
<plugins>
|
||||
|
||||
@ -332,6 +332,7 @@
|
||||
<module>annotations</module>
|
||||
<module>apache-cxf</module>
|
||||
<module>apache-fop</module>
|
||||
<module>apache-geode</module>
|
||||
<module>apache-poi</module>
|
||||
<module>apache-tika</module>
|
||||
<module>apache-thrift</module>
|
||||
@ -522,9 +523,9 @@
|
||||
<module>spring-rest-angular</module>
|
||||
<module>spring-rest-full</module>
|
||||
<module>spring-rest-query-language</module>
|
||||
<module>spring-rest</module>
|
||||
<!-- <module>spring-rest</module> --> <!-- temporarily disabled -->
|
||||
<!-- <module>spring-rest-simple</module> --> <!-- temporarily disabled -->
|
||||
<module>spring-resttemplate</module>
|
||||
<module>spring-rest-simple</module>
|
||||
<module>spring-security-acl</module>
|
||||
<module>spring-security-cache-control</module>
|
||||
<module>spring-security-client/spring-security-jsp-authentication</module>
|
||||
@ -550,141 +551,180 @@
|
||||
<module>spring-security-rest</module>
|
||||
<module>spring-security-sso</module>
|
||||
<module>spring-security-x509</module>
|
||||
<module>spring-session</module>
|
||||
<module>spring-sleuth</module>
|
||||
<module>spring-social-login</module>
|
||||
<module>spring-spel</module>
|
||||
<module>spring-state-machine</module>
|
||||
<module>spring-thymeleaf</module>
|
||||
<module>spring-userservice</module>
|
||||
<module>spring-zuul</module>
|
||||
<module>spring-remoting</module>
|
||||
<module>spring-reactor</module>
|
||||
<module>spring-vertx</module>
|
||||
<module>spring-jinq</module>
|
||||
<module>spring-rest-embedded-tomcat</module>
|
||||
<module>testing-modules/testing</module>
|
||||
<module>testing-modules/testng</module>
|
||||
<module>video-tutorials</module>
|
||||
<module>xml</module>
|
||||
<module>xmlunit-2</module>
|
||||
<module>struts-2</module>
|
||||
<module>apache-velocity</module>
|
||||
<module>apache-solrj</module>
|
||||
<module>rabbitmq</module>
|
||||
<module>vertx</module>
|
||||
<module>persistence-modules/spring-data-gemfire</module>
|
||||
<module>mybatis</module>
|
||||
<module>spring-drools</module>
|
||||
<module>drools</module>
|
||||
<module>persistence-modules/liquibase</module>
|
||||
<module>spring-boot-property-exp</module>
|
||||
<module>testing-modules/mockserver</module>
|
||||
<module>testing-modules/test-containers</module>
|
||||
<module>undertow</module>
|
||||
<module>vaadin</module>
|
||||
<module>vertx-and-rxjava</module>
|
||||
<module>saas</module>
|
||||
<module>deeplearning4j</module>
|
||||
<module>lucene</module>
|
||||
<module>vraptor</module>
|
||||
<module>persistence-modules/java-cockroachdb</module>
|
||||
<module>spring-security-thymeleaf</module>
|
||||
<module>persistence-modules/java-jdbi</module>
|
||||
<module>jersey</module>
|
||||
<module>java-spi</module>
|
||||
<module>performance-tests</module>
|
||||
<module>twilio</module>
|
||||
<module>spring-boot-ctx-fluent</module>
|
||||
<module>java-ee-8-security-api</module>
|
||||
<module>spring-webflux-amqp</module>
|
||||
<module>antlr</module>
|
||||
<module>maven-archetype</module>
|
||||
<module>optaplanner</module>
|
||||
<module>apache-meecrowave</module>
|
||||
<module>spring-reactive-kotlin</module>
|
||||
<module>jnosql</module>
|
||||
<module>spring-boot-angular-ecommerce</module>
|
||||
<module>cdi-portable-extension</module>
|
||||
<module>jta</module>
|
||||
<!--<module>java-dates</module> --> <!-- Commented because we have still not upgraded to java 9 -->
|
||||
<module>java-websocket</module>
|
||||
<module>activejdbc</module>
|
||||
<module>animal-sniffer-mvn-plugin</module>
|
||||
<module>apache-avro</module>
|
||||
<module>apache-bval</module>
|
||||
<module>apache-shiro</module>
|
||||
<module>apache-spark</module>
|
||||
<module>asciidoctor</module>
|
||||
<module>checker-plugin</module>
|
||||
<!-- <module>core-java-10</module> --><!-- Not upgraded to java 10 -->
|
||||
<!-- <module>core-java-11</module> --><!-- Not upgraded to java 11 -->
|
||||
<module>core-java-sun</module>
|
||||
<module>custom-pmd</module>
|
||||
<module>dagger</module>
|
||||
<module>data-structures</module>
|
||||
<module>dubbo</module>
|
||||
<module>flyway</module>
|
||||
<!-- <module>grpc</module> --><!-- protobuf-maven-plugin filecopy failure -->
|
||||
<module>java-difference-date</module>
|
||||
<!-- <module>JGit</module> --><!-- Unit test failure -->
|
||||
<module>jni</module>
|
||||
<module>jooby</module>
|
||||
<!-- <module>micronaut</module> --><!-- Not upgraded to java 9 -->
|
||||
<!-- <module>microprofile</module> --><!-- Takes too much time : Downloads 93 MBs zip and .. -->
|
||||
<!-- <module>muleesb</module> --><!-- load main class org.mule.munit.remote.RemoteRunner -->
|
||||
<module>ratpack</module>
|
||||
<module>rest-with-spark-java</module>
|
||||
<module>spring-boot-autoconfiguration</module>
|
||||
<module>spring-boot-custom-starter</module>
|
||||
<module>spring-boot-jasypt</module>
|
||||
<module>spring-custom-aop</module>
|
||||
<module>spring-data-rest-querydsl</module>
|
||||
<module>spring-groovy</module>
|
||||
<module>spring-mobile</module>
|
||||
<module>spring-mustache</module>
|
||||
<module>spring-mvc-simple</module>
|
||||
<module>spring-mybatis</module>
|
||||
<module>spring-rest-hal-browser</module>
|
||||
<module>spring-rest-shell</module>
|
||||
<module>spring-rest-template</module>
|
||||
<module>spring-roo</module>
|
||||
<module>spring-security-stormpath</module>
|
||||
<module>sse-jaxrs</module>
|
||||
<module>static-analysis</module>
|
||||
<module>stripe</module>
|
||||
<!-- <module>structurizr</module> --><!-- Artiifact not found -->
|
||||
<module>Twitter4J</module>
|
||||
<module>wicket</module>
|
||||
<module>xstream</module>
|
||||
<module>cas/cas-secured-app</module>
|
||||
<module>cas/cas-server</module>
|
||||
<!-- <module>graphql/graphql-java</module> --><!-- Wrong parent -->
|
||||
<!-- <module>guest/deep-jsf</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/junit5-example</module> --><!-- guest post on different site - Compilation failure -->
|
||||
<!-- <module>guest/log4j2-example</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/logback-example</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/memory-leaks</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/remote-debugging</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/spring-boot-app</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/spring-mvc</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/spring-security</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/thread-pools</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/tomcat-app</module> --><!-- guest post on different site -->
|
||||
<module>jenkins/hello-world</module>
|
||||
<!-- <module>rule-engines/easy-rules</module> --><!-- Wrong Parent -->
|
||||
<!-- <module>rule-engines/openl-tablets</module> --><!-- Wrong Parent -->
|
||||
<!-- <module>rule-engines/rulebook</module> --><!-- Wrong Parent -->
|
||||
<module>spring-boot-custom-starter/greeter</module>
|
||||
<module>spring-boot-h2/spring-boot-h2-database</module>
|
||||
<!--module>spring-boot-h2/spring-boot-h2-remote-app</module-->
|
||||
<!-- <module>guest\webservices\rest-client</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest\webservices\rest-server</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest\webservices\spring-rest-service</module> --><!-- guest post on different site -->
|
||||
</modules>
|
||||
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>default-second</id>
|
||||
<build>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<forkCount>3</forkCount>
|
||||
<reuseForks>true</reuseForks>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*IntTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
<exclude>**/JdbcTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<modules>
|
||||
<module>parent-boot-1</module>
|
||||
<module>parent-boot-2</module>
|
||||
<module>parent-spring-4</module>
|
||||
<module>parent-spring-5</module>
|
||||
<module>parent-java</module>
|
||||
<module>parent-kotlin</module>
|
||||
|
||||
<module>spring-session</module>
|
||||
<module>spring-sleuth</module>
|
||||
<module>spring-social-login</module>
|
||||
<module>spring-spel</module>
|
||||
<module>spring-state-machine</module>
|
||||
<module>spring-thymeleaf</module>
|
||||
<module>spring-userservice</module>
|
||||
<module>spring-zuul</module>
|
||||
<module>spring-remoting</module>
|
||||
<module>spring-reactor</module>
|
||||
<module>spring-vertx</module>
|
||||
<module>spring-jinq</module>
|
||||
<module>spring-rest-embedded-tomcat</module>
|
||||
<module>testing-modules/testing</module>
|
||||
<module>testing-modules/testng</module>
|
||||
<module>video-tutorials</module>
|
||||
<module>xml</module>
|
||||
<module>xmlunit-2</module>
|
||||
<module>struts-2</module>
|
||||
<module>apache-velocity</module>
|
||||
<module>apache-solrj</module>
|
||||
<module>rabbitmq</module>
|
||||
<module>vertx</module>
|
||||
<module>persistence-modules/spring-data-gemfire</module>
|
||||
<module>mybatis</module>
|
||||
<module>spring-drools</module>
|
||||
<module>drools</module>
|
||||
<module>persistence-modules/liquibase</module>
|
||||
<module>spring-boot-property-exp</module>
|
||||
<module>testing-modules/mockserver</module>
|
||||
<module>testing-modules/test-containers</module>
|
||||
<module>undertow</module>
|
||||
<module>vaadin</module>
|
||||
<module>vertx-and-rxjava</module>
|
||||
<module>saas</module>
|
||||
<module>deeplearning4j</module>
|
||||
<module>lucene</module>
|
||||
<module>vraptor</module>
|
||||
<module>persistence-modules/java-cockroachdb</module>
|
||||
<module>spring-security-thymeleaf</module>
|
||||
<module>persistence-modules/java-jdbi</module>
|
||||
<module>jersey</module>
|
||||
<module>java-spi</module>
|
||||
<module>performance-tests</module>
|
||||
<module>twilio</module>
|
||||
<module>spring-boot-ctx-fluent</module>
|
||||
<module>java-ee-8-security-api</module>
|
||||
<module>spring-webflux-amqp</module>
|
||||
<module>antlr</module>
|
||||
<module>maven-archetype</module>
|
||||
<module>optaplanner</module>
|
||||
<module>apache-meecrowave</module>
|
||||
<module>spring-reactive-kotlin</module>
|
||||
<module>jnosql</module>
|
||||
<module>spring-boot-angular-ecommerce</module>
|
||||
<module>cdi-portable-extension</module>
|
||||
<module>jta</module>
|
||||
<!--<module>java-dates</module> --> <!-- Commented because we have still not upgraded to java 9 -->
|
||||
<module>java-websocket</module>
|
||||
<module>activejdbc</module>
|
||||
<module>animal-sniffer-mvn-plugin</module>
|
||||
<module>apache-avro</module>
|
||||
<module>apache-bval</module>
|
||||
<module>apache-shiro</module>
|
||||
<module>apache-spark</module>
|
||||
<module>asciidoctor</module>
|
||||
<module>checker-plugin</module>
|
||||
<!-- <module>core-java-10</module> --><!-- Not upgraded to java 10 -->
|
||||
<!-- <module>core-java-11</module> --><!-- Not upgraded to java 11 -->
|
||||
<module>core-java-sun</module>
|
||||
<module>custom-pmd</module>
|
||||
<module>dagger</module>
|
||||
<module>data-structures</module>
|
||||
<module>dubbo</module>
|
||||
<module>flyway</module>
|
||||
<!-- <module>grpc</module> --><!-- protobuf-maven-plugin filecopy failure -->
|
||||
<module>java-difference-date</module>
|
||||
<!-- <module>JGit</module> --><!-- Unit test failure -->
|
||||
<module>jni</module>
|
||||
<module>jooby</module>
|
||||
<!-- <module>micronaut</module> --><!-- Not upgraded to java 9 -->
|
||||
<!-- <module>microprofile</module> --><!-- Takes too much time : Downloads 93 MBs zip and .. -->
|
||||
<!-- <module>muleesb</module> --><!-- load main class org.mule.munit.remote.RemoteRunner -->
|
||||
<module>ratpack</module>
|
||||
<module>rest-with-spark-java</module>
|
||||
<module>spring-boot-autoconfiguration</module>
|
||||
<module>spring-boot-custom-starter</module>
|
||||
<module>spring-boot-jasypt</module>
|
||||
<module>spring-custom-aop</module>
|
||||
<module>spring-data-rest-querydsl</module>
|
||||
<module>spring-groovy</module>
|
||||
<module>spring-mobile</module>
|
||||
<module>spring-mustache</module>
|
||||
<module>spring-mvc-simple</module>
|
||||
<module>spring-mybatis</module>
|
||||
<module>spring-rest-hal-browser</module>
|
||||
<module>spring-rest-shell</module>
|
||||
<module>spring-rest-template</module>
|
||||
<module>spring-roo</module>
|
||||
<module>spring-security-stormpath</module>
|
||||
<module>sse-jaxrs</module>
|
||||
<module>static-analysis</module>
|
||||
<module>stripe</module>
|
||||
<!-- <module>structurizr</module> --><!-- Artiifact not found -->
|
||||
<module>Twitter4J</module>
|
||||
<module>wicket</module>
|
||||
<module>xstream</module>
|
||||
<module>cas/cas-secured-app</module>
|
||||
<module>cas/cas-server</module>
|
||||
<!-- <module>graphql/graphql-java</module> --><!-- Wrong parent -->
|
||||
<!-- <module>guest/deep-jsf</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/junit5-example</module> --><!-- guest post on different site - Compilation failure -->
|
||||
<!-- <module>guest/log4j2-example</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/logback-example</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/memory-leaks</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/remote-debugging</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/spring-boot-app</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/spring-mvc</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/spring-security</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/thread-pools</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest/tomcat-app</module> --><!-- guest post on different site -->
|
||||
<!-- <module>jenkins/hello-world</module> --> <!-- disabled in the default profile -->
|
||||
<!-- <module>rule-engines/easy-rules</module> --><!-- Wrong Parent -->
|
||||
<!-- <module>rule-engines/openl-tablets</module> --><!-- Wrong Parent -->
|
||||
<!-- <module>rule-engines/rulebook</module> --><!-- Wrong Parent -->
|
||||
<module>spring-boot-custom-starter/greeter</module>
|
||||
<module>spring-boot-h2/spring-boot-h2-database</module>
|
||||
<!--module>spring-boot-h2/spring-boot-h2-remote-app</module-->
|
||||
<!-- <module>guest\webservices\rest-client</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest\webservices\rest-server</module> --><!-- guest post on different site -->
|
||||
<!-- <module>guest\webservices\spring-rest-service</module> --><!-- guest post on different site -->
|
||||
<module>flyway-cdi-extension</module>
|
||||
</modules>
|
||||
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>spring-context</id>
|
||||
<build>
|
||||
@ -1033,7 +1073,7 @@
|
||||
<module>spring-rest</module>
|
||||
<module>spring-resttemplate</module>
|
||||
<module>spring-rest-simple</module>
|
||||
<module>spring-reactive-kotlin</module>
|
||||
<module>spring-reactive-kotlin</module>
|
||||
|
||||
|
||||
<!-- group 3.2 - Pass, 8 minutes, 1 failed test, 2,294 KB log -->
|
||||
@ -1447,7 +1487,6 @@
|
||||
<module>spring-security-thymeleaf</module>
|
||||
<module>persistence-modules/java-jdbi</module>
|
||||
<module>jersey</module>
|
||||
<module>jersey-client-rx</module>
|
||||
<module>java-spi</module>
|
||||
<module>performance-tests</module>
|
||||
<module>twilio</module>
|
||||
|
@ -145,6 +145,20 @@
|
||||
<artifactId>chaos-monkey-spring-boot</artifactId>
|
||||
<version>${chaos.monkey.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- for Graylog demo -->
|
||||
<dependency>
|
||||
<!-- forcing spring boot 1.x sing log4j was dropped in spring boot 1.4 and beyond -->
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-log4j</artifactId>
|
||||
<version>1.3.8.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.graylog2</groupId>
|
||||
<artifactId>gelfj</artifactId>
|
||||
<version>1.1.16</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@ -224,4 +238,4 @@
|
||||
<git-commit-id-plugin.version>2.2.4</git-commit-id-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.graylog;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class GraylogDemoApplication {
|
||||
|
||||
private final static Logger LOG =
|
||||
Logger.getLogger(GraylogDemoApplication.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(GraylogDemoApplication.class, args);
|
||||
LOG.info("Hello from Spring Boot");
|
||||
}
|
||||
}
|
24
spring-boot/src/main/resources/log4j.xml
Normal file
24
spring-boot/src/main/resources/log4j.xml
Normal file
@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE log4j:configuration SYSTEM "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
|
||||
<log4j:configuration>
|
||||
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } [%t] --- %-40.40logger{39} : %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
<appender name="graylog" class="org.graylog2.log.GelfAppender">
|
||||
<param name="graylogHost" value="18.217.253.212"/>
|
||||
<param name="originHost" value="localhost"/>
|
||||
<param name="graylogPort" value="12201"/>
|
||||
<param name="extractStacktrace" value="true"/>
|
||||
<param name="addExtendedInformation" value="true"/>
|
||||
<param name="facility" value="log4j"/>
|
||||
<param name="Threshold" value="DEBUG"/>
|
||||
<param name="additionalFields" value="{'environment': 'DEV', 'application': 'GraylogDemoApplication'}"/>
|
||||
</appender>
|
||||
<root>
|
||||
<priority value="DEBUG"/>
|
||||
<appender-ref ref="stdout"/>
|
||||
<appender-ref ref="graylog"/>
|
||||
</root>
|
||||
</log4j:configuration>
|
Loading…
x
Reference in New Issue
Block a user