Merge branch 'master' into thombergs-patch-31-1

This commit is contained in:
Tom Hombergs 2018-10-02 20:40:24 +02:00 committed by GitHub
commit 82dfce8f6c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
422 changed files with 8902 additions and 2131 deletions

View File

@ -24,3 +24,7 @@
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)

View File

@ -0,0 +1,50 @@
package com.baeldung.algorithms.mergesort;
public class MergeSort {
public static void main(String[] args) {
int[] a = { 5, 1, 6, 2, 3, 4 };
mergeSort(a, a.length);
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
public static void mergeSort(int[] a, int n) {
if (n < 2)
return;
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n - mid];
for (int i = 0; i < mid; i++) {
l[i] = a[i];
}
for (int i = mid; i < n; i++) {
r[i - mid] = a[i];
}
mergeSort(l, mid);
mergeSort(r, n - mid);
merge(a, l, r, mid, n - mid);
}
public static void merge(int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0;
while (i < left && j < right) {
if (l[i] < r[j])
a[k++] = l[i++];
else
a[k++] = r[j++];
}
while (i < left)
a[k++] = l[i++];
while (j < right)
a[k++] = r[j++];
}
}

View File

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

View File

@ -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);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.mergesort;
import org.junit.Assert;
import org.junit.Test;
public class MergeSortUnitTest {
@Test
public void positiveTest() {
int[] actual = { 5, 1, 6, 2, 3, 4 };
int[] expected = { 1, 2, 3, 4, 5, 6 };
MergeSort.mergeSort(actual, actual.length);
Assert.assertArrayEquals(expected, actual);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -7,7 +7,7 @@ import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
public class AppUnitTest
extends TestCase
{
/**
@ -15,7 +15,7 @@ public class AppTest
*
* @param testName name of the test case
*/
public AppTest( String testName )
public AppUnitTest( String testName )
{
super( testName );
}
@ -25,7 +25,7 @@ public class AppTest
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
return new TestSuite( AppUnitTest.class );
}
/**

View File

@ -6,7 +6,7 @@
<groupId>com.baeldung</groupId>
<artifactId>apache-avro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Apache Avro</version>
<name>Apache Avro</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -13,7 +13,7 @@ import java.util.Objects;
import static org.junit.Assert.*;
public class AvroSerealizerDeSerealizerTest {
public class AvroSerealizerDeSerealizerUnitTest {
AvroSerealizer serealizer;
AvroDeSerealizer deSerealizer;

46
apache-geode/pom.xml Normal file
View 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>

View 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);
}
}

View File

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

View File

@ -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();
}
}

View File

@ -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());
}
}

View File

@ -1,5 +1,4 @@
### Relevant articles
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book)
- [Introduction to Asciidoctor in Java](http://www.baeldung.com/asciidoctor)

View File

@ -61,9 +61,10 @@
</build>
<properties>
<asciidoctor-maven-plugin.version>1.5.5</asciidoctor-maven-plugin.version>
<asciidoctorj.version>1.5.4</asciidoctorj.version>
<asciidoctorj-pdf.src.version>1.5.0-alpha.11</asciidoctorj-pdf.src.version>
<asciidoctor-maven-plugin.version>1.5.6</asciidoctor-maven-plugin.version>
<asciidoctorj.version>1.5.6</asciidoctorj.version>
<asciidoctorj-pdf.version>1.5.0-alpha.15</asciidoctorj-pdf.version>
<asciidoctorj-pdf.plugin.version>1.5.0-alpha.15</asciidoctorj-pdf.plugin.version>
</properties>

View File

@ -3,7 +3,7 @@ package com.baeldung.asciidoctor;
import org.junit.Assert;
import org.junit.Test;
public class AsciidoctorDemoTest {
public class AsciidoctorDemoIntegrationTest {
@Test
public void givenString_whenConverting_thenResultingHTMLCode() {

View File

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>flyway-cdi</artifactId>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>cdi-portable-extension</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
</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>
</dependencies>
</project>

View File

@ -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();
}
}

View File

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

View File

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

View File

@ -0,0 +1,2 @@
com.baeldung.cdi.extension.FlywayExtension

View File

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>main-app</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>cdi-portable-extension</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<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>com.baeldung</groupId>
<artifactId>flyway-cdi</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</project>

View File

@ -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()) {
}
}
}

View File

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

View File

@ -0,0 +1,4 @@
create table PERSON (
ID int not null,
NAME varchar(100) not null
);

View File

@ -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');

View File

@ -0,0 +1,30 @@
<?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>cdi-portable-extension</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<modules>
<module>main-app</module>
<module>flyway-cdi</module>
</modules>
<dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
</dependency>
</dependencies>
</project>

View File

@ -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));
}
}

View File

@ -48,4 +48,6 @@
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)

View File

@ -63,6 +63,12 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
</dependencies>

View File

@ -0,0 +1,39 @@
package com.baeldung.combiningcollections;
import java.util.Arrays;
import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
import com.google.common.collect.ObjectArrays;
public class CombiningArrays {
public static Object[] usingNativeJava(Object[] first, Object[] second) {
Object[] combined = new Object[first.length + second.length];
System.arraycopy(first, 0, combined, 0, first.length);
System.arraycopy(second, 0, combined, first.length, second.length);
return combined;
}
public static Object[] usingJava8ObjectStream(Object[] first, Object[] second) {
Object[] combined = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray();
return combined;
}
public static Object[] usingJava8FlatMaps(Object[] first, Object[] second) {
Object[] combined = Stream.of(first, second).flatMap(Stream::of).toArray(String[]::new);
return combined;
}
public static Object[] usingApacheCommons(Object[] first, Object[] second) {
Object[] combined = ArrayUtils.addAll(first, second);
return combined;
}
public static Object[] usingGuava(Object[] first, Object[] second) {
Object [] combined = ObjectArrays.concat(first, second, Object.class);
return combined;
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.combiningcollections;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.collections4.ListUtils;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class CombiningLists {
public static List<Object> usingNativeJava(List<Object> first, List<Object> second) {
List<Object> combined = new ArrayList<>();
combined.addAll(first);
combined.addAll(second);
return combined;
}
public static List<Object> usingJava8ObjectStream(List<Object> first, List<Object> second) {
List<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toList());
return combined;
}
public static List<Object> usingJava8FlatMaps(List<Object> first, List<Object> second) {
List<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toList());
return combined;
}
public static List<Object> usingApacheCommons(List<Object> first, List<Object> second) {
List<Object> combined = ListUtils.union(first, second);
return combined;
}
public static List<Object> usingGuava(List<Object> first, List<Object> second) {
Iterable<Object> combinedIterables = Iterables.unmodifiableIterable(
Iterables.concat(first, second));
List<Object> combined = Lists.newArrayList(combinedIterables);
return combined;
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.combiningcollections;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.exec.util.MapUtils;
import com.google.common.collect.ImmutableMap;
public class CombiningMaps {
public static Map<String, String> usingPlainJava(Map<String, String> first, Map<String, String> second) {
Map<String, String> combined = new HashMap<>();
combined.putAll(first);
combined.putAll(second);
return combined;
}
public static Map<String, String> usingJava8ForEach(Map<String, String> first, Map<String, String> second) {
second.forEach((key, value) -> first.merge(key, value, String::concat));
return first;
}
public static Map<String, String> usingJava8FlatMaps(Map<String, String> first, Map<String, String> second) {
Map<String, String> combined = Stream.of(first, second).map(Map::entrySet).flatMap(Collection::stream)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, String::concat));
return combined;
}
public static Map<String, String> usingApacheCommons(Map<String, String> first, Map<String, String> second) {
Map<String, String> combined = MapUtils.merge(first, second);
return combined;
}
public static Map<String, String> usingGuava(Map<String, String> first, Map<String, String> second) {
Map<String, String> combined = ImmutableMap.<String, String>builder()
.putAll(first)
.putAll(second)
.build();
return combined;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.combiningcollections;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.collections4.SetUtils;
import com.google.common.collect.Sets;
public class CombiningSets {
public static Set<Object> usingNativeJava(Set<Object> first, Set<Object> second) {
Set<Object> combined = new HashSet<>();
combined.addAll(first);
combined.addAll(second);
return combined;
}
public static Set<Object> usingJava8ObjectStream(Set<Object> first, Set<Object> second) {
Set<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toSet());
return combined;
}
public static Set<Object> usingJava8FlatMaps(Set<Object> first, Set<Object> second) {
Set<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toSet());
return combined;
}
public static Set<Object> usingApacheCommons(Set<Object> first, Set<Object> second) {
Set<Object> combined = SetUtils.union(first, second);
return combined;
}
public static Set<Object> usingGuava(Set<Object> first, Set<Object> second) {
Set<Object> combined = Sets.union(first, second);
return combined;
}
}

View File

@ -0,0 +1,96 @@
package com.baeldung.map.util;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
public class MapMax {
public <K, V extends Comparable<V>> V maxUsingIteration(Map<K, V> map) {
Map.Entry<K, V> maxEntry = null;
for (Map.Entry<K, V> entry : map.entrySet()) {
if (maxEntry == null || entry.getValue()
.compareTo(maxEntry.getValue()) > 0) {
maxEntry = entry;
}
}
return maxEntry.getValue();
}
public <K, V extends Comparable<V>> V maxUsingCollectionsMax(Map<K, V> map) {
Entry<K, V> maxEntry = Collections.max(map.entrySet(), new Comparator<Entry<K, V>>() {
public int compare(Entry<K, V> e1, Entry<K, V> e2) {
return e1.getValue()
.compareTo(e2.getValue());
}
});
return maxEntry.getValue();
}
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) {
Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
.compareTo(e2.getValue()));
return maxEntry.getValue();
}
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndMethodReference(Map<K, V> map) {
Entry<K, V> maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Map.Entry::getValue));
return maxEntry.getValue();
}
public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) {
Optional<Entry<K, V>> maxEntry = map.entrySet()
.stream()
.max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
.compareTo(e2.getValue()));
return maxEntry.get()
.getValue();
}
public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) {
Optional<Entry<K, V>> maxEntry = map.entrySet()
.stream()
.max(Comparator.comparing(Map.Entry::getValue));
return maxEntry.get()
.getValue();
}
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 3);
map.put(2, 4);
map.put(3, 5);
map.put(4, 6);
map.put(5, 7);
MapMax mapMax = new MapMax();
System.out.println(mapMax.maxUsingIteration(map));
System.out.println(mapMax.maxUsingCollectionsMax(map));
System.out.println(mapMax.maxUsingCollectionsMaxAndLambda(map));
System.out.println(mapMax.maxUsingCollectionsMaxAndMethodReference(map));
System.out.println(mapMax.maxUsingStreamAndLambda(map));
System.out.println(mapMax.maxUsingStreamAndMethodReference(map));
}
}

View File

@ -44,4 +44,12 @@ public class Employee {
result = 31 * result + name.hashCode();
return result;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.sort;
public class Employee implements Comparable<Employee> {
private Long id;
private String name;
public Employee(Long id, String name) {
this.name = name;
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
if (!id.equals(employee.id)) return false;
return name.equals(employee.name);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + name.hashCode();
return result;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
@Override
public int compareTo(Employee employee) {
return (int)(this.id - employee.getId());
}
}

View File

@ -0,0 +1,104 @@
package com.baeldung.sort;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import java.util.*;
import java.util.stream.Collectors;
public class SortHashMap {
private static Map<String, Employee> map = new HashMap<>();
public static void main(String[] args) {
initialize();
treeMapSortByKey();
arrayListSortByValue();
arrayListSortByKey();
sortStream();
sortGuava();
addDuplicates();
treeSetByKey();
treeSetByValue();
}
private static void sortGuava() {
final Ordering naturalOrdering =
Ordering.natural().onResultOf(Functions.forMap(map, null));
System.out.println(ImmutableSortedMap.copyOf(map, naturalOrdering));
}
private static void sortStream() {
map.entrySet().stream()
.sorted(Map.Entry.<String, Employee>comparingByKey().reversed())
.forEach(System.out::println);
Map<String, Employee> result = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
result.entrySet().forEach(System.out::println);
}
private static void treeSetByValue() {
SortedSet<Employee> values = new TreeSet<>(map.values());
System.out.println(values);
}
private static void treeSetByKey() {
SortedSet<String> keysSet = new TreeSet<>(map.keySet());
System.out.println(keysSet);
}
private static void treeMapSortByKey() {
TreeMap<String, Employee> sorted = new TreeMap<>(map);
sorted.putAll(map);
sorted.entrySet().forEach(System.out::println);
}
private static void arrayListSortByValue() {
List<Employee> employeeById = new ArrayList<>(map.values());
Collections.sort(employeeById);
System.out.println(employeeById);
}
private static void arrayListSortByKey() {
List<String> employeeByKey = new ArrayList<>(map.keySet());
Collections.sort(employeeByKey);
System.out.println(employeeByKey);
}
private static void initialize() {
Employee employee1 = new Employee(1L, "Mher");
map.put(employee1.getName(), employee1);
Employee employee2 = new Employee(22L, "Annie");
map.put(employee2.getName(), employee2);
Employee employee3 = new Employee(8L, "John");
map.put(employee3.getName(), employee3);
Employee employee4 = new Employee(2L, "George");
map.put(employee4.getName(), employee4);
}
private static void addDuplicates() {
Employee employee5 = new Employee(1L, "Mher");
map.put(employee5.getName(), employee5);
Employee employee6 = new Employee(22L, "Annie");
map.put(employee6.getName(), employee6);
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.combiningcollections;
import static org.junit.Assert.*;
import org.junit.Test;
public class CombiningArraysUnitTest {
private static final String first[] = {
"One",
"Two",
"Three"
};
private static final String second[] = {
"Four",
"Five",
"Six"
};
private static final String expected[] = {
"One",
"Two",
"Three",
"Four",
"Five",
"Six"
};
@Test
public void givenTwoArrays_whenUsingNativeJava_thenArraysCombined() {
assertArrayEquals(expected, CombiningArrays.usingNativeJava(first, second));
}
@Test
public void givenTwoArrays_whenUsingObjectStreams_thenArraysCombined() {
assertArrayEquals(expected, CombiningArrays.usingJava8ObjectStream(first, second));
}
@Test
public void givenTwoArrays_whenUsingFlatMaps_thenArraysCombined() {
assertArrayEquals(expected, CombiningArrays.usingJava8FlatMaps(first, second));
}
@Test
public void givenTwoArrays_whenUsingApacheCommons_thenArraysCombined() {
assertArrayEquals(expected, CombiningArrays.usingApacheCommons(first, second));
}
@Test
public void givenTwoArrays_whenUsingGuava_thenArraysCombined() {
assertArrayEquals(expected, CombiningArrays.usingGuava(first, second));
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.combiningcollections;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class CombiningListsUnitTest {
private static final List<Object> first = Arrays.asList(new Object[]{
"One",
"Two",
"Three"
});
private static final List<Object> second = Arrays.asList(new Object[]{
"Four",
"Five",
"Six"
});
private static final List<Object> expected = Arrays.asList(new Object[]{
"One",
"Two",
"Three",
"Four",
"Five",
"Six"
});
@Test
public void givenTwoLists_whenUsingNativeJava_thenArraysCombined() {
assertThat(CombiningLists.usingNativeJava(first, second), is(expected));
}
@Test
public void givenTwoLists_whenUsingObjectStreams_thenArraysCombined() {
assertThat(CombiningLists.usingJava8ObjectStream(first, second), is(expected));
}
@Test
public void givenTwoLists_whenUsingFlatMaps_thenArraysCombined() {
assertThat(CombiningLists.usingJava8FlatMaps(first, second), is(expected));
}
@Test
public void givenTwoLists_whenUsingApacheCommons_thenArraysCombined() {
assertThat(CombiningLists.usingApacheCommons(first, second), is(expected));
}
@Test
public void givenTwoLists_whenUsingGuava_thenArraysCombined() {
assertThat(CombiningLists.usingGuava(first, second), is(expected));
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.combiningcollections;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class CombiningMapsUnitTest {
private static final Map<String, String> first = new HashMap<>();
private static final Map<String, String> second = new HashMap<>();
private static Map<String, String> expected = new HashMap<>();
static {
first.put("one", "first String");
first.put("two", "second String");
second.put("three", "third String");
second.put("four", "fourth String");
expected.put("one", "first String");
expected.put("two", "second String");
expected.put("three", "third String");
expected.put("four", "fourth String");
}
@Test
public void givenTwoMaps_whenUsingNativeJava_thenMapsCombined() {
assertThat(CombiningMaps.usingPlainJava(first, second), is(expected));
}
@Test
public void givenTwoMaps_whenUsingForEach_thenMapsCombined() {
assertThat(CombiningMaps.usingJava8ForEach(first, second), is(expected));
}
@Test
public void givenTwoMaps_whenUsingFlatMaps_thenMapsCombined() {
assertThat(CombiningMaps.usingJava8FlatMaps(first, second), is(expected));
}
@Test
public void givenTwoMaps_whenUsingApacheCommons_thenMapsCombined() {
assertThat(CombiningMaps.usingApacheCommons(first, second), is(expected));
}
@Test
public void givenTwoMaps_whenUsingGuava_thenMapsCombined() {
assertThat(CombiningMaps.usingGuava(first, second), is(expected));
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.combiningcollections;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
public class CombiningSetsUnitTest {
private static final Set<Object> first = new HashSet<Object>(Arrays.asList(new Object[] { "One", "Two", "Three" }));
private static final Set<Object> second = new HashSet<Object>(Arrays.asList(new Object[] { "Four", "Five", "Six" }));
private static final Set<Object> expected = new HashSet<Object>(Arrays
.asList(new Object[] { "One", "Two", "Three", "Four", "Five", "Six" }));
@Test
public void givenTwoSets_whenUsingNativeJava_thenArraysCombined() {
assertThat(CombiningSets.usingNativeJava(first, second), is(expected));
}
@Test
public void givenTwoSets_whenUsingObjectStreams_thenArraysCombined() {
assertThat(CombiningSets.usingJava8ObjectStream(first, second), is(expected));
}
@Test
public void givenTwoSets_whenUsingFlatMaps_thenArraysCombined() {
assertThat(CombiningSets.usingJava8FlatMaps(first, second), is(expected));
}
@Test
public void givenTwoSets_whenUsingApacheCommons_thenArraysCombined() {
assertThat(CombiningSets.usingApacheCommons(first, second), is(expected));
}
@Test
public void givenTwoSets_whenUsingGuava_thenArraysCombined() {
assertThat(CombiningSets.usingGuava(first, second), is(expected));
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.map.util;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class MapMaxUnitTest {
Map<Integer, Integer> map = null;
MapMax mapMax = null;
@Before
public void setupTestData() {
map = new HashMap<Integer, Integer>();
map.put(23, 12);
map.put(46, 24);
map.put(27, 38);
mapMax = new MapMax();
}
@Test
public void givenMap_whenIterated_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingIteration(map));
}
@Test
public void givenMap_whenUsingCollectionsMax_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMax(map));
}
@Test
public void givenMap_whenUsingCollectionsMaxAndLambda_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndLambda(map));
}
@Test
public void givenMap_whenUsingCollectionsMaxAndMethodReference_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndMethodReference(map));
}
@Test
public void givenMap_whenUsingStreamAndLambda_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingStreamAndLambda(map));
}
@Test
public void givenMap_whenUsingStreamAndMethodReference_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingStreamAndMethodReference (map));
}
}

View File

@ -31,3 +31,4 @@
- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink)
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [ Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)

View File

@ -18,6 +18,7 @@ import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
@ -50,7 +51,7 @@ public class FileOperationsManualTest {
@Test
public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
String expectedData = "BSD License";
String expectedData = "MIT License";
Class clazz = Matchers.class;
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
@ -79,7 +80,7 @@ public class FileOperationsManualTest {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileTest.txt").getFile());
String data = FileUtils.readFileToString(file);
String data = FileUtils.readFileToString(file, "UTF-8");
assertEquals(expectedData, data.trim());
}
@ -102,12 +103,11 @@ public class FileOperationsManualTest {
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
StringBuilder data = new StringBuilder();
Stream<String> lines = Files.lines(path);
lines.forEach(line -> data.append(line).append("\n"));
String data = lines.collect(Collectors.joining("\n"));
lines.close();
assertEquals(expectedData, data.toString().trim());
assertEquals(expectedData, data.trim());
}
private String readFromInputStream(InputStream inputStream) throws IOException {

View File

@ -0,0 +1 @@
Hello World from fileTest.txt!!!

View File

@ -151,3 +151,4 @@
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)

View File

@ -0,0 +1,9 @@
package com.baeldung.memoryleaks.equalshashcode;
public class Person {
public String name;
public Person(String name) {
this.name = name;
}
}

View File

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

View 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");
}
}

View File

@ -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"));
}
}

View 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"));
}
}

View File

@ -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");
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.memoryleaks.innerclass;
public class InnerClassWrapper {
private BulkyObject bulkyObject = new BulkyObject();
public class SimpleInnerClass {
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.memoryleaks.innerclass;
public class StaticNestedClassWrapper {
private BulkyObject bulkyObject = new BulkyObject();
public static class StaticNestedClass {
}
}

View File

@ -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");
}
}
}

View File

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

View File

@ -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");
}
}
}

View File

@ -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");
}
}

View File

@ -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");
}
}

View File

@ -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);
}
}

View 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 + ".");
}
}

View File

@ -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");
}
}

View File

@ -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");
}
}

View File

@ -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");
}
}

View File

@ -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");
}
}

View File

@ -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");
}
}

View File

@ -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");
}
}

View File

@ -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);
}
}

View File

@ -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", ""));
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.ternaryoperator;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class TernaryOperatorUnitTest {
@Test
public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() {
int number = 10;
String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10";
assertThat(msg).isEqualTo("Number is less than or equal to 10");
}
@Test
public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() {
int exp1 = 0, exp2 = 0;
int result = 12 > 10 ? ++exp1 : ++exp2;
assertThat(exp1).isEqualTo(1);
assertThat(exp2).isEqualTo(0);
assertThat(result).isEqualTo(1);
}
@Test
public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() {
int exp1 = 0, exp2 = 0;
int result = 8 > 10 ? ++exp1 : ++exp2;
assertThat(exp1).isEqualTo(0);
assertThat(exp2).isEqualTo(1);
assertThat(result).isEqualTo(1);
}
@Test
public void givenANestedCondition_whenUsingTernaryOperator_thenCorrectValueIsReturned() {
int number = 6;
String msg = number > 10 ? "Number is greater than 10" : number > 5 ? "Number is greater than 5" : "Number is less than or equal to 5";
assertThat(msg).isEqualTo("Number is greater than 5");
}
}

View File

@ -33,4 +33,7 @@
- [Idiomatic Logging in Kotlin](http://www.baeldung.com/kotlin-logging)
- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors)
- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern)
- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes)
- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes)
- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor)
- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel)
- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant)

View File

@ -15,7 +15,6 @@
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>

View File

@ -24,7 +24,6 @@
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>

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

View File

@ -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();
}
}

View File

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

View File

@ -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()) {
}
}
}

View File

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

View File

@ -0,0 +1,2 @@
com.baeldung.cdi.extension.FlywayExtension

View File

@ -0,0 +1,4 @@
create table PERSON (
ID int not null,
NAME varchar(100) not null
);

View File

@ -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');

View File

@ -65,6 +65,7 @@
<properties>
<flyway-core.version>5.0.2</flyway-core.version>
<flyway-maven-plugin.version>5.0.2</flyway-maven-plugin.version>
<h2.version>1.4.195</h2.version>
</properties>
</project>

View File

@ -16,7 +16,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@ContextConfiguration(classes = FlywayCallbackTestConfig.class)
public class FlywayApplicationTest {
public class FlywayApplicationUnitTest {
private Log log = LogFactory.getLog(getClass());

View File

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

View 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;
}
}

View File

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

View File

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

View File

@ -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());
}
}

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

View File

@ -18,9 +18,9 @@ import org.junit.Test;
import com.stackify.models.User;
import com.stackify.services.MyService;
public class MyServiceTest {
public class MyServiceUnitTest {
private static final Logger logger = LogManager.getLogger(MyServiceTest.class);
private static final Logger logger = LogManager.getLogger(MyServiceUnitTest.class);
@Test
public void testService() {

View File

@ -9,7 +9,7 @@ import com.stackify.models.Employee;
import ch.qos.logback.classic.Level;
public class EmployeeServiceTest {
public class EmployeeServiceUnitTest {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
private EmployeeService employeeService = new EmployeeService();

View File

@ -12,7 +12,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M5</version>
<version>2.0.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>

View File

@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M6</version>
<version>2.0.0.RELEASE</version>
<relativePath />
</parent>

View File

@ -6,7 +6,7 @@ import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.CoreMatchers.*;
public class UserServiceTest {
public class UserServiceLiveTest {
@Test
public void whenAddUser_thenGetUserOk() {
RestAssured.baseURI = "http://localhost:8080/rest-server";

View File

@ -14,3 +14,4 @@
- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa)
- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking)
- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle)
- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column)

View File

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

View File

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

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