commit
						28c33f8aea
					
				
							
								
								
									
										2
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							| @ -62,3 +62,5 @@ jmeter/src/main/resources/*-JMeter.csv | ||||
| **/dist | ||||
| **/tmp | ||||
| **/out-tsc | ||||
| **/nbproject/ | ||||
| **/nb-configuration.xml | ||||
							
								
								
									
										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) | ||||
|  | ||||
| @ -1,13 +1,9 @@ | ||||
| <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/maven-v4_0_0.xsd"> | ||||
|     <modelVersion>4.0.0</modelVersion> | ||||
| 
 | ||||
|     <groupId>com.mabsisa</groupId> | ||||
|     <artifactId>Twitter4J</artifactId> | ||||
|     <packaging>jar</packaging> | ||||
|     <version>1.0-SNAPSHOT</version> | ||||
|     <name>Twitter4J</name> | ||||
|     <url>http://maven.apache.org</url> | ||||
| 
 | ||||
|     <parent> | ||||
|         <groupId>com.baeldung</groupId> | ||||
| @ -23,27 +19,6 @@ | ||||
|         </dependency> | ||||
|     </dependencies> | ||||
| 
 | ||||
|     <build> | ||||
|         <finalName>${project.artifactId}</finalName> | ||||
|         <resources> | ||||
|             <resource> | ||||
|                 <directory>src/main/resources</directory> | ||||
|             </resource> | ||||
|         </resources> | ||||
|         <plugins> | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-surefire-plugin</artifactId> | ||||
|                 <version>${maven-surefire-plugin.version}</version> | ||||
|                 <configuration> | ||||
|                     <excludes> | ||||
|                         <exclude>**/ApplicationTest.java</exclude> | ||||
|                     </excludes> | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
|     <properties> | ||||
|         <twitter4j-stream.version>4.0.6</twitter4j-stream.version> | ||||
|     </properties> | ||||
|  | ||||
| @ -1,7 +1,6 @@ | ||||
| <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>activejdbc</artifactId> | ||||
|     <version>1.0-SNAPSHOT</version> | ||||
|     <packaging>jar</packaging> | ||||
| @ -79,55 +78,11 @@ | ||||
|                     </dependency> | ||||
|                 </dependencies> | ||||
|             </plugin> | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-surefire-plugin</artifactId> | ||||
|                 <version>${maven-surefire-plugin.version}</version> | ||||
|                 <configuration> | ||||
|                     <reportFormat>brief</reportFormat> | ||||
|                     <trimStackTrace>true</trimStackTrace> | ||||
|                     <useFile>false</useFile> | ||||
|                     <includes> | ||||
|                         <include>**/*Spec*.java</include> | ||||
|                         <include>**/*Test*.java</include> | ||||
|                     </includes> | ||||
|                     <excludes> | ||||
|                         <exclude>**/helpers/*</exclude> | ||||
|                         <exclude>**/*$*</exclude> | ||||
|                     </excludes> | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
|     <repositories> | ||||
|         <repository> | ||||
|             <id>snapshots1</id> | ||||
|             <name>JavaLite Snapshots1</name> | ||||
|             <url>http://repo.javalite.io/</url> | ||||
|             <snapshots> | ||||
|                 <enabled>true</enabled> | ||||
|                 <updatePolicy>always</updatePolicy> | ||||
|                 <checksumPolicy>warn</checksumPolicy> | ||||
|             </snapshots> | ||||
|         </repository> | ||||
|     </repositories> | ||||
| 
 | ||||
|     <pluginRepositories> | ||||
|         <pluginRepository> | ||||
|             <id>snapshots2</id> | ||||
|             <name>JavaLite Snapshots2</name> | ||||
|             <url>http://repo.javalite.io/</url> | ||||
|             <snapshots> | ||||
|                 <enabled>true</enabled> | ||||
|                 <updatePolicy>always</updatePolicy> | ||||
|                 <checksumPolicy>warn</checksumPolicy> | ||||
|             </snapshots> | ||||
|         </pluginRepository> | ||||
|     </pluginRepositories> | ||||
| 
 | ||||
|     <properties> | ||||
|         <activejdbc.version>1.4.13</activejdbc.version> | ||||
|         <activejdbc.version>2.0</activejdbc.version> | ||||
|         <environments>development.test,development</environments> | ||||
|         <mysql.connector.version>5.1.34</mysql.connector.version> | ||||
|     </properties> | ||||
|  | ||||
| @ -16,4 +16,8 @@ public class Employee extends Model { | ||||
|         set("created_by",createdBy); | ||||
|     } | ||||
| 
 | ||||
|     public String getLastName() { | ||||
|         return getString("last_name"); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
|  | ||||
| @ -15,4 +15,8 @@ public class Role extends Model { | ||||
|         set("role_name",role); | ||||
|         set("created_by",createdBy); | ||||
|     } | ||||
| 
 | ||||
|     public String getRoleName() { | ||||
|         return getString("role_name"); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -7,7 +7,7 @@ import org.junit.Test; | ||||
| 
 | ||||
| import java.util.List; | ||||
| 
 | ||||
| public class ActiveJDBCAppTest extends DBSpec | ||||
| public class ActiveJDBCAppManualTest extends DBSpec | ||||
| { | ||||
|     @Test | ||||
|     public void ifEmployeeCreated_thenIsValid() { | ||||
| @ -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) | ||||
|  | ||||
							
								
								
									
										1
									
								
								algorithms/roundUpToHundred/.gitignore
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										1
									
								
								algorithms/roundUpToHundred/.gitignore
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1 @@ | ||||
| /bin/ | ||||
| @ -0,0 +1,20 @@ | ||||
| package com.java.src; | ||||
| 
 | ||||
| import java.util.Scanner; | ||||
| 
 | ||||
| public class RoundUpToHundred { | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         Scanner scanner = new Scanner(System.in); | ||||
|         double input = scanner.nextDouble(); | ||||
|         scanner.close(); | ||||
| 
 | ||||
|         RoundUpToHundred.round(input); | ||||
|     } | ||||
| 
 | ||||
|     static long round(double input) { | ||||
|         long i = (long) Math.ceil(input); | ||||
|         return ((i + 99) / 100) * 100; | ||||
|     }; | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,14 @@ | ||||
| package com.java.src; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class RoundUpToHundredTest { | ||||
|     @Test | ||||
|     public void givenInput_whenRound_thenRoundUpToTheNearestHundred() { | ||||
|         assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99)); | ||||
|         assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2)); | ||||
|         assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400)); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,41 @@ | ||||
| package com.baeldung.algorithms.insertionsort; | ||||
| 
 | ||||
| public class InsertionSort { | ||||
| 
 | ||||
|     public static void insertionSortImperative(int[] input) { | ||||
|         for (int i = 1; i < input.length; i++) { | ||||
|             int key = input[i]; | ||||
|             int j = i - 1; | ||||
|             while (j >= 0 && input[j] > key) { | ||||
|                 input[j + 1] = input[j]; | ||||
|                 j = j - 1; | ||||
|             } | ||||
|             input[j + 1] = key; | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public static void insertionSortRecursive(int[] input) { | ||||
|         insertionSortRecursive(input, input.length); | ||||
|     } | ||||
| 
 | ||||
|     private static void insertionSortRecursive(int[] input, int i) { | ||||
|         // base case | ||||
|         if (i <= 1) { | ||||
|             return; | ||||
|         } | ||||
| 
 | ||||
|         // sort the first i - 1 elements of the array | ||||
|         insertionSortRecursive(input, i - 1); | ||||
| 
 | ||||
|         // then find the correct position of the element at position i | ||||
|         int key = input[i - 1]; | ||||
|         int j = i - 2; | ||||
|         // shifting the elements from their position by 1 | ||||
|         while (j >= 0 && input[j] > key) { | ||||
|             input[j + 1] = input[j]; | ||||
|             j = j - 1; | ||||
|         } | ||||
|         // inserting the key at the appropriate position | ||||
|         input[j + 1] = key; | ||||
|     } | ||||
| } | ||||
| @ -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,50 @@ | ||||
| package com.baeldung.algorithms.mergesort; | ||||
| 
 | ||||
| public class MergeSort { | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         int[] a = { 5, 1, 6, 2, 3, 4 }; | ||||
|         mergeSort(a, a.length); | ||||
|         for (int i = 0; i < a.length; i++) | ||||
|             System.out.println(a[i]); | ||||
|     } | ||||
| 
 | ||||
|     public static void mergeSort(int[] a, int n) { | ||||
|         if (n < 2) | ||||
|             return; | ||||
|         int mid = n / 2; | ||||
|         int[] l = new int[mid]; | ||||
|         int[] r = new int[n - mid]; | ||||
| 
 | ||||
|         for (int i = 0; i < mid; i++) { | ||||
|             l[i] = a[i]; | ||||
|         } | ||||
|         for (int i = mid; i < n; i++) { | ||||
|             r[i - mid] = a[i]; | ||||
|         } | ||||
|         mergeSort(l, mid); | ||||
|         mergeSort(r, n - mid); | ||||
| 
 | ||||
|         merge(a, l, r, mid, n - mid); | ||||
|     } | ||||
| 
 | ||||
|     public static void merge(int[] a, int[] l, int[] r, int left, int right) { | ||||
| 
 | ||||
|         int i = 0, j = 0, k = 0; | ||||
| 
 | ||||
|         while (i < left && j < right) { | ||||
| 
 | ||||
|             if (l[i] < r[j]) | ||||
|                 a[k++] = l[i++]; | ||||
|             else | ||||
|                 a[k++] = r[j++]; | ||||
| 
 | ||||
|         } | ||||
| 
 | ||||
|         while (i < left) | ||||
|             a[k++] = l[i++]; | ||||
| 
 | ||||
|         while (j < right) | ||||
|             a[k++] = r[j++]; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,39 @@ | ||||
| package com.baeldung.algorithms.quicksort; | ||||
| 
 | ||||
| public class QuickSort { | ||||
| 
 | ||||
|     public static void quickSort(int arr[], int begin, int end) | ||||
|     { | ||||
|         if (begin < end) { | ||||
|             int partitionIndex = partition(arr, begin, end); | ||||
| 
 | ||||
|             // Recursively sort elements of the 2 sub-arrays | ||||
|             quickSort(arr, begin, partitionIndex-1); | ||||
|             quickSort(arr, partitionIndex+1, end); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     private static int partition(int arr[], int begin, int end) | ||||
|     { | ||||
|         int pivot = arr[end]; | ||||
|         int i = (begin-1); | ||||
| 
 | ||||
|         for (int j=begin; j<end; j++) | ||||
|         { | ||||
|             if (arr[j] <= pivot) { | ||||
|                 i++; | ||||
| 
 | ||||
|                 int swapTemp = arr[i]; | ||||
|                 arr[i] = arr[j]; | ||||
|                 arr[j] = swapTemp; | ||||
|             } | ||||
|         } | ||||
| 
 | ||||
|         int swapTemp = arr[i+1]; | ||||
|         arr[i+1] = arr[end]; | ||||
|         arr[end] = swapTemp; | ||||
| 
 | ||||
|         return i+1; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,38 @@ | ||||
| package com.baeldung.algorithms.quicksort; | ||||
| 
 | ||||
| public class ThreeWayQuickSort { | ||||
| 
 | ||||
|     public static void threeWayQuickSort(int[] a, int begin, int end) | ||||
|     { | ||||
|         if (end <= begin) return; | ||||
| 
 | ||||
|         // partition | ||||
|         int i = begin; | ||||
|         int less = begin; | ||||
|         int greater = end; | ||||
| 
 | ||||
|         while (i <= greater){ | ||||
|             if (a[i] < a[less]) { | ||||
|                 int tmp = a[i]; | ||||
|                 a[i] = a[less]; | ||||
|                 a[less] = tmp; | ||||
| 
 | ||||
|                 i++; | ||||
|                 less++; | ||||
|             } | ||||
|             else if (a[less] < a[i])	{ | ||||
|                 int tmp = a[i]; | ||||
|                 a[i] = a[greater]; | ||||
|                 a[greater] = tmp; | ||||
| 
 | ||||
|                 greater--; | ||||
|             } | ||||
|             else { | ||||
|                 i++; | ||||
|             } | ||||
|         } | ||||
| 
 | ||||
|         threeWayQuickSort(a, begin, less - 1); | ||||
|         threeWayQuickSort(a, greater + 1, end); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,29 @@ | ||||
| package com.baeldung.algorithms.rectanglesoverlap; | ||||
| 
 | ||||
| public class Point { | ||||
| 
 | ||||
|     private int x; | ||||
|     private int y; | ||||
| 
 | ||||
|     public Point(int x, int y) { | ||||
|         this.x = x; | ||||
|         this.y = y; | ||||
|     } | ||||
| 
 | ||||
|     public int getX() { | ||||
|         return x; | ||||
|     } | ||||
| 
 | ||||
|     public void setX(int x) { | ||||
|         this.x = x; | ||||
|     } | ||||
| 
 | ||||
|     public int getY() { | ||||
|         return y; | ||||
|     } | ||||
| 
 | ||||
|     public void setY(int y) { | ||||
|         this.y = y; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,40 @@ | ||||
| package com.baeldung.algorithms.rectanglesoverlap; | ||||
| 
 | ||||
| public class Rectangle { | ||||
| 
 | ||||
|     private Point bottomLeft; | ||||
|     private Point topRight; | ||||
| 
 | ||||
|     public Rectangle(Point bottomLeft, Point topRight) { | ||||
|         this.bottomLeft = bottomLeft; | ||||
|         this.topRight = topRight; | ||||
|     } | ||||
| 
 | ||||
|     public Point getBottomLeft() { | ||||
|         return bottomLeft; | ||||
|     } | ||||
| 
 | ||||
|     public void setBottomLeft(Point bottomLeft) { | ||||
|         this.bottomLeft = bottomLeft; | ||||
|     } | ||||
| 
 | ||||
|     public Point getTopRight() { | ||||
|         return topRight; | ||||
|     } | ||||
| 
 | ||||
|     public void setTopRight(Point topRight) { | ||||
|         this.topRight = topRight; | ||||
|     } | ||||
| 
 | ||||
|     public boolean isOverlapping(Rectangle other) { | ||||
|         // one rectangle is to the top of the other | ||||
|         if (this.topRight.getY() < other.bottomLeft.getY() || this.bottomLeft.getY() > other.topRight.getY()) { | ||||
|             return false; | ||||
|         } | ||||
|         // one rectangle is to the left of the other | ||||
|         if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) { | ||||
|             return false; | ||||
|         } | ||||
|         return true; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,25 @@ | ||||
| package com.baeldung.algorithms.insertionsort; | ||||
| 
 | ||||
| import com.baeldung.algorithms.insertionsort.InsertionSort; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import static org.junit.Assert.assertArrayEquals; | ||||
| 
 | ||||
| public class InsertionSortUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() { | ||||
|         int[] input = {6, 2, 3, 4, 5, 1}; | ||||
|         InsertionSort.insertionSortImperative(input); | ||||
|         int[] expected = {1, 2, 3, 4, 5, 6}; | ||||
|         assertArrayEquals("the two arrays are not equal", expected, input); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() { | ||||
|         int[] input = {6, 4, 5, 2, 3, 1}; | ||||
|         InsertionSort.insertionSortRecursive(input); | ||||
|         int[] expected = {1, 2, 3, 4, 5, 6}; | ||||
|         assertArrayEquals("the two arrays are not equal", expected, input); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,17 @@ | ||||
| package com.baeldung.algorithms.mergesort; | ||||
| 
 | ||||
| import org.junit.Assert; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class MergeSortUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void positiveTest() { | ||||
|         int[] actual = { 5, 1, 6, 2, 3, 4 }; | ||||
|         int[] expected = { 1, 2, 3, 4, 5, 6 }; | ||||
|         MergeSort.mergeSort(actual, actual.length); | ||||
|         Assert.assertArrayEquals(expected, actual); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,17 @@ | ||||
| package com.baeldung.algorithms.quicksort; | ||||
| 
 | ||||
| import com.baeldung.algorithms.quicksort.QuickSort; | ||||
| import org.junit.Assert; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class QuickSortUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() { | ||||
|         int[] actual = { 9, 5, 1, 0, 6, 2, 3, 4, 7, 8 }; | ||||
|         int[] expected = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; | ||||
|         QuickSort.quickSort(actual, 0, actual.length-1); | ||||
|         Assert.assertArrayEquals(expected, actual); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,15 @@ | ||||
| package com.baeldung.algorithms.quicksort; | ||||
| 
 | ||||
| import org.junit.Assert; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class ThreeWayQuickSortUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { | ||||
|         int[] actual = { 3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3 }; | ||||
|         int[] expected = { 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7 }; | ||||
|         ThreeWayQuickSort.threeWayQuickSort(actual, 0, actual.length-1); | ||||
|         Assert.assertArrayEquals(expected, actual); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,42 @@ | ||||
| package com.baeldung.algorithms.rectanglesoverlap; | ||||
| 
 | ||||
| import static org.junit.Assert.assertTrue; | ||||
| import static org.junit.Assert.assertFalse; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.baeldung.algorithms.rectanglesoverlap.Point; | ||||
| import com.baeldung.algorithms.rectanglesoverlap.Rectangle; | ||||
| 
 | ||||
| public class RectangleUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenTwoOverlappingRectangles_whenisOverlappingCalled_shouldReturnTrue() { | ||||
|         Rectangle rectangle1 = new Rectangle(new Point(2, 1), new Point(4, 3)); | ||||
|         Rectangle rectangle2 = new Rectangle(new Point(1, 1), new Point(6, 4)); | ||||
|         assertTrue(rectangle1.isOverlapping(rectangle2)); | ||||
| 
 | ||||
|         rectangle1 = new Rectangle(new Point(-5, -2), new Point(2, 3)); | ||||
|         rectangle2 = new Rectangle(new Point(-2, -1), new Point(5, 2)); | ||||
|         assertTrue(rectangle1.isOverlapping(rectangle2)); | ||||
| 
 | ||||
|         rectangle1 = new Rectangle(new Point(-5, 1), new Point(2, 4)); | ||||
|         rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5)); | ||||
|         assertTrue(rectangle1.isOverlapping(rectangle2)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenTwoNonOverlappingRectangles_whenisOverlappingCalled_shouldReturnFalse() { | ||||
|         Rectangle rectangle1 = new Rectangle(new Point(-5, 1), new Point(-3, 4)); | ||||
|         Rectangle rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5)); | ||||
|         assertFalse(rectangle1.isOverlapping(rectangle2)); | ||||
| 
 | ||||
|         rectangle1 = new Rectangle(new Point(-5, 1), new Point(3, 4)); | ||||
|         rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, -1)); | ||||
|         assertFalse(rectangle1.isOverlapping(rectangle2)); | ||||
| 
 | ||||
|         rectangle1 = new Rectangle(new Point(-2, 1), new Point(0, 3)); | ||||
|         rectangle2 = new Rectangle(new Point(3, 1), new Point(5, 4)); | ||||
|         assertFalse(rectangle1.isOverlapping(rectangle2)); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -7,7 +7,7 @@ import junit.framework.TestSuite; | ||||
| /** | ||||
|  * Unit test for simple App. | ||||
|  */ | ||||
| public class AppTest  | ||||
| public class AppUnitTest  | ||||
|     extends TestCase | ||||
| { | ||||
|     /** | ||||
| @ -15,7 +15,7 @@ public class AppTest | ||||
|      * | ||||
|      * @param testName name of the test case | ||||
|      */ | ||||
|     public AppTest( String testName ) | ||||
|     public AppUnitTest( String testName ) | ||||
|     { | ||||
|         super( testName ); | ||||
|     } | ||||
| @ -25,7 +25,7 @@ public class AppTest | ||||
|      */ | ||||
|     public static Test suite() | ||||
|     { | ||||
|         return new TestSuite( AppTest.class ); | ||||
|         return new TestSuite( AppUnitTest.class ); | ||||
|     } | ||||
| 
 | ||||
|     /** | ||||
| @ -6,7 +6,7 @@ | ||||
|     <groupId>com.baeldung</groupId> | ||||
|     <artifactId>apache-avro</artifactId> | ||||
|     <version>0.0.1-SNAPSHOT</version> | ||||
| 	<name>Apache Avro</version> | ||||
| 	<name>Apache Avro</name> | ||||
| 
 | ||||
|     <properties> | ||||
|         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||
|  | ||||
| @ -13,7 +13,7 @@ import java.util.Objects; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| public class AvroSerealizerDeSerealizerTest { | ||||
| public class AvroSerealizerDeSerealizerUnitTest { | ||||
| 
 | ||||
|     AvroSerealizer serealizer; | ||||
|     AvroDeSerealizer deSerealizer; | ||||
| @ -3,3 +3,4 @@ | ||||
| - [Apache CXF Support for RESTful Web Services](http://www.baeldung.com/apache-cxf-rest-api) | ||||
| - [A Guide to Apache CXF with Spring](http://www.baeldung.com/apache-cxf-with-spring) | ||||
| - [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf) | ||||
| - [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse) | ||||
|  | ||||
							
								
								
									
										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()); | ||||
|     } | ||||
| } | ||||
| @ -3,7 +3,6 @@ | ||||
|          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-shiro</artifactId> | ||||
|     <version>1.0-SNAPSHOT</version> | ||||
| 
 | ||||
| @ -36,13 +35,11 @@ | ||||
|         <dependency> | ||||
|             <groupId>org.slf4j</groupId> | ||||
|             <artifactId>jcl-over-slf4j</artifactId> | ||||
|             <version>${slf4j-version}</version> | ||||
|             <scope>runtime</scope> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>org.slf4j</groupId> | ||||
|             <artifactId>slf4j-log4j12</artifactId> | ||||
|             <version>${slf4j-version}</version> | ||||
|             <scope>runtime</scope> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
| @ -53,26 +50,9 @@ | ||||
|         </dependency> | ||||
|     </dependencies> | ||||
| 
 | ||||
|     <build> | ||||
|         <plugins> | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-compiler-plugin</artifactId> | ||||
|                 <version>${maven-compiler-plugin.version}</version> | ||||
|                 <configuration> | ||||
|                     <source>${java.version}</source> | ||||
|                     <target>${java.version}</target> | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
|     <properties> | ||||
|         <apache-shiro-core-version>1.4.0</apache-shiro-core-version> | ||||
|         <maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version> | ||||
|         <java.version>1.8</java.version> | ||||
|         <log4j-version>1.2.17</log4j-version> | ||||
|         <slf4j-version>1.7.25</slf4j-version> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
| @ -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) | ||||
|  | ||||
| @ -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> | ||||
| 
 | ||||
|  | ||||
| @ -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() { | ||||
| @ -42,14 +42,6 @@ | ||||
|                     </archive> | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-surefire-plugin</artifactId> | ||||
|                 <version>${maven-surefire-plugin.version}</version> | ||||
|                 <configuration> | ||||
|                     <argLine>-javaagent:"C:\asm-1.0.jar"</argLine> | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
|  | ||||
| @ -95,7 +95,6 @@ | ||||
|         <gson.version>2.8.2</gson.version> | ||||
|         <aws-java-sdk.version>1.11.241</aws-java-sdk.version> | ||||
|         <maven-shade-plugin.version>3.0.0</maven-shade-plugin.version> | ||||
|         <maven-dependency-plugin.version>2.10</maven-dependency-plugin.version> | ||||
|     </properties> | ||||
|      | ||||
| </project> | ||||
							
								
								
									
										21
									
								
								aws/pom.xml
									
									
									
									
									
								
							
							
						
						
									
										21
									
								
								aws/pom.xml
									
									
									
									
									
								
							| @ -100,26 +100,6 @@ | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
| 
 | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-dependency-plugin</artifactId> | ||||
|                 <version>${maven-dependency-plugin.version}</version> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <id>copy-dependencies</id> | ||||
|                         <phase>test-compile</phase> | ||||
|                         <goals> | ||||
|                             <goal>copy-dependencies</goal> | ||||
|                         </goals> | ||||
|                         <configuration> | ||||
|                             <includeScope>test</includeScope> | ||||
|                             <includeTypes>so,dll,dylib</includeTypes> | ||||
|                             <outputDirectory>${project.basedir}/native-libs</outputDirectory> | ||||
|                         </configuration> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
| @ -144,7 +124,6 @@ | ||||
|         <commons-codec-version>1.10.L001</commons-codec-version> | ||||
|         <jets3t-version>0.9.4.0006L</jets3t-version> | ||||
|         <maven-shade-plugin.version>3.0.0</maven-shade-plugin.version> | ||||
|         <maven-dependency-plugin.version>2.10</maven-dependency-plugin.version> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
| @ -2,12 +2,10 @@ | ||||
| <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>cas-secured-app</artifactId> | ||||
|     <version>0.0.1-SNAPSHOT</version> | ||||
|     <packaging>jar</packaging> | ||||
|     <name>cas-secured-app</name> | ||||
|     <description>Demo project for Spring Boot</description> | ||||
|     <description>Demo project for CAS</description> | ||||
| 
 | ||||
|     <parent> | ||||
|         <artifactId>parent-boot-1</artifactId> | ||||
| @ -60,10 +58,4 @@ | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
|     <properties> | ||||
|         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||
|         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> | ||||
|         <java.version>1.8</java.version> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
|  | ||||
| @ -2,11 +2,17 @@ | ||||
| <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>cas-server</artifactId> | ||||
|     <packaging>war</packaging> | ||||
|     <version>1.0</version> | ||||
| 
 | ||||
|     <parent> | ||||
|         <artifactId>parent-boot-1</artifactId> | ||||
|         <groupId>com.baeldung</groupId> | ||||
|         <version>0.0.1-SNAPSHOT</version> | ||||
|         <relativePath>../../parent-boot-1</relativePath> | ||||
|     </parent> | ||||
|      | ||||
|     <dependencies> | ||||
|         <dependency> | ||||
|             <groupId>org.apereo.cas</groupId> | ||||
| @ -39,7 +45,6 @@ | ||||
|             <plugin> | ||||
|                 <groupId>org.springframework.boot</groupId> | ||||
|                 <artifactId>spring-boot-maven-plugin</artifactId> | ||||
|                 <version>${springboot.version}</version> | ||||
|                 <configuration> | ||||
|                     <mainClass>${mainClassName}</mainClass> | ||||
|                     <addResources>true</addResources> | ||||
| @ -74,42 +79,10 @@ | ||||
|                     </overlays> | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-compiler-plugin</artifactId> | ||||
|                 <version>${maven-compiler-plugin.version}</version> | ||||
|             </plugin> | ||||
|         </plugins> | ||||
|         <finalName>cas</finalName> | ||||
|     </build> | ||||
| 
 | ||||
|     <repositories> | ||||
|         <repository> | ||||
|             <id>sonatype-releases</id> | ||||
|             <url>http://oss.sonatype.org/content/repositories/releases/</url> | ||||
|             <snapshots> | ||||
|                 <enabled>false</enabled> | ||||
|             </snapshots> | ||||
|             <releases> | ||||
|                 <enabled>true</enabled> | ||||
|             </releases> | ||||
|         </repository> | ||||
|         <repository> | ||||
|             <id>sonatype-snapshots</id> | ||||
|             <url>https://oss.sonatype.org/content/repositories/snapshots/</url> | ||||
|             <snapshots> | ||||
|                 <enabled>true</enabled> | ||||
|             </snapshots> | ||||
|             <releases> | ||||
|                 <enabled>false</enabled> | ||||
|             </releases> | ||||
|         </repository> | ||||
|         <repository> | ||||
|             <id>shibboleth-releases</id> | ||||
|             <url>https://build.shibboleth.net/nexus/content/repositories/releases</url> | ||||
|         </repository> | ||||
|     </repositories> | ||||
| 
 | ||||
|     <profiles> | ||||
|         <profile> | ||||
|             <activation> | ||||
| @ -214,8 +187,7 @@ | ||||
|     </profiles> | ||||
| 
 | ||||
|     <properties> | ||||
|         <cas.version>5.3.0-SNAPSHOT</cas.version> | ||||
|         <springboot.version>1.5.13.RELEASE</springboot.version> | ||||
|         <cas.version>5.3.3</cas.version> | ||||
|         <!-- app.server could be -jetty, -undertow, -tomcat, or blank if you plan to provide appserver --> | ||||
|         <app.server>-tomcat</app.server> | ||||
| 
 | ||||
| @ -223,14 +195,12 @@ | ||||
|         <isExecutable>false</isExecutable> | ||||
|         <manifestFileToUse>${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF</manifestFileToUse> | ||||
| 
 | ||||
|         <maven.compiler.source>1.8</maven.compiler.source> | ||||
|         <maven.compiler.target>1.8</maven.compiler.target> | ||||
|         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||
|         <wrapper-maven-plugin.version>0.0.4</wrapper-maven-plugin.version> | ||||
|         <maven-war-plugin.version>2.6</maven-war-plugin.version> | ||||
|         <maven-compiler-plugin.version>3.3</maven-compiler-plugin.version> | ||||
|          | ||||
|         <echo-maven-plugin.version>0.3.0</echo-maven-plugin.version> | ||||
|         <pgpverify-maven-plugin.version>1.1.0</pgpverify-maven-plugin.version> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
| </project> | ||||
|  | ||||
							
								
								
									
										38
									
								
								cdi-portable-extension/flyway-cdi/pom.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										38
									
								
								cdi-portable-extension/flyway-cdi/pom.xml
									
									
									
									
									
										Normal 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> | ||||
| @ -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,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 | ||||
| 
 | ||||
							
								
								
									
										52
									
								
								cdi-portable-extension/main-app/pom.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										52
									
								
								cdi-portable-extension/main-app/pom.xml
									
									
									
									
									
										Normal 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> | ||||
| @ -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,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'); | ||||
							
								
								
									
										30
									
								
								cdi-portable-extension/pom.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										30
									
								
								cdi-portable-extension/pom.xml
									
									
									
									
									
										Normal 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> | ||||
| @ -41,27 +41,6 @@ | ||||
| 
 | ||||
|     <build> | ||||
|         <plugins> | ||||
|             <plugin> | ||||
|                 <!-- This plugin will set properties values using dependency information --> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-dependency-plugin</artifactId> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <goals> | ||||
|                             <!-- | ||||
|                             Goal that sets a property pointing to the artifact file for each project dependency. | ||||
|                             For each dependency (direct and transitive) a project property will be set which | ||||
|                             follows the: | ||||
| 
 | ||||
|                                groupId:artifactId:type:[classifier] | ||||
| 
 | ||||
|                             form and contains the path to the resolved artifact. --> | ||||
|                             <goal>properties</goal> | ||||
|                         </goals> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
| 
 | ||||
|             <plugin> | ||||
|                 <artifactId>maven-compiler-plugin</artifactId> | ||||
|                 <version>${maven-compiler-plugin.version}</version> | ||||
|  | ||||
| @ -29,3 +29,6 @@ | ||||
| - [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic) | ||||
| - [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference) | ||||
| - [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time) | ||||
| - [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone) | ||||
| - [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance) | ||||
| - [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects) | ||||
|  | ||||
| @ -116,23 +116,6 @@ | ||||
|         </resources> | ||||
| 
 | ||||
|         <plugins> | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-dependency-plugin</artifactId> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <id>copy-dependencies</id> | ||||
|                         <phase>prepare-package</phase> | ||||
|                         <goals> | ||||
|                             <goal>copy-dependencies</goal> | ||||
|                         </goals> | ||||
|                         <configuration> | ||||
|                             <outputDirectory>${project.build.directory}/libs</outputDirectory> | ||||
|                         </configuration> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
| 
 | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-compiler-plugin</artifactId> | ||||
|  | ||||
| @ -3,11 +3,15 @@ package com.baeldung.internationalization; | ||||
| import org.junit.Assert; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.time.LocalDate; | ||||
| import java.time.LocalDateTime; | ||||
| import java.time.LocalTime; | ||||
| import java.time.ZoneId; | ||||
| import java.time.ZonedDateTime; | ||||
| import java.time.format.DateTimeFormatter; | ||||
| import java.time.format.DateTimeParseException; | ||||
| import java.time.format.FormatStyle; | ||||
| import java.time.temporal.ChronoUnit; | ||||
| import java.util.Locale; | ||||
| import java.util.TimeZone; | ||||
| 
 | ||||
| @ -43,4 +47,112 @@ public class DateTimeFormatterUnitTest { | ||||
|         Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime); | ||||
|         Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldPrintFormattedDate() { | ||||
|         String europeanDatePattern = "dd.MM.yyyy"; | ||||
|         DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern(europeanDatePattern); | ||||
|         LocalDate summerDay = LocalDate.of(2016, 7, 31); | ||||
|         Assert.assertEquals("31.07.2016", europeanDateFormatter.format(summerDay)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldPrintFormattedTime24() { | ||||
|         String timeColonPattern = "HH:mm:ss"; | ||||
|         DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); | ||||
|         LocalTime colonTime = LocalTime.of(17, 35, 50); | ||||
|         Assert.assertEquals("17:35:50", timeColonFormatter.format(colonTime)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldPrintFormattedTimeWithMillis() { | ||||
|         String timeColonPattern = "HH:mm:ss SSS"; | ||||
|         DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); | ||||
|         LocalTime colonTime = LocalTime.of(17, 35, 50).plus(329, ChronoUnit.MILLIS); | ||||
|         Assert.assertEquals("17:35:50 329", timeColonFormatter.format(colonTime)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldPrintFormattedTimePM() { | ||||
|         String timeColonPattern = "hh:mm:ss a"; | ||||
|         DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); | ||||
|         LocalTime colonTime = LocalTime.of(17, 35, 50); | ||||
|         Assert.assertEquals("05:35:50 PM", timeColonFormatter.format(colonTime)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldPrintFormattedUTCRelatedZonedDateTime() { | ||||
|         String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z"; | ||||
|         DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern); | ||||
|         LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15); | ||||
|         Assert.assertEquals("31.07.2016 14:15 UTC-04:00", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("UTC-4")))); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldPrintFormattedNewYorkZonedDateTime() { | ||||
|         String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z"; | ||||
|         DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern); | ||||
|         LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15); | ||||
|         Assert.assertEquals("31.07.2016 14:15 EDT", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("America/New_York")))); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldPrintStyledDate() { | ||||
|         LocalDate anotherSummerDay = LocalDate.of(2016, 8, 23); | ||||
|         Assert.assertEquals("Tuesday, August 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).format(anotherSummerDay)); | ||||
|         Assert.assertEquals("August 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).format(anotherSummerDay)); | ||||
|         Assert.assertEquals("Aug 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(anotherSummerDay)); | ||||
|         Assert.assertEquals("8/23/16", DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(anotherSummerDay)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldPrintStyledDateTime() { | ||||
|         LocalDateTime anotherSummerDay = LocalDateTime.of(2016, 8, 23, 13, 12, 45); | ||||
|         Assert.assertEquals("Tuesday, August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); | ||||
|         Assert.assertEquals("August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); | ||||
|         Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); | ||||
|         Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldPrintFormattedDateTimeWithPredefined() { | ||||
|         Assert.assertEquals("2018-03-09", DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.of(2018, 3, 9))); | ||||
|         Assert.assertEquals("2018-03-09-03:00", DateTimeFormatter.ISO_OFFSET_DATE.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); | ||||
|         Assert.assertEquals("Fri, 9 Mar 2018 00:00:00 -0300", DateTimeFormatter.RFC_1123_DATE_TIME.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldParseDateTime() { | ||||
|         Assert.assertEquals(LocalDate.of(2018, 3, 12), LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2018-03-09")).plusDays(3)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldParseFormatStyleFull() { | ||||
|         ZonedDateTime dateTime = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).parse("Tuesday, August 23, 2016 1:12:45 PM EET")); | ||||
|         Assert.assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 8, 23, 22, 12, 45), ZoneId.of("Europe/Bucharest")), dateTime.plusHours(9)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldParseDateWithCustomFormatter() { | ||||
|         DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); | ||||
|         Assert.assertFalse(LocalDate.from(europeanDateFormatter.parse("15.08.2014")).isLeapYear()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldParseTimeWithCustomFormatter() { | ||||
|         DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm:ss a"); | ||||
|         Assert.assertTrue(LocalTime.from(timeFormatter.parse("12:25:30 AM")).isBefore(LocalTime.NOON)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldParseZonedDateTimeWithCustomFormatter() { | ||||
|         DateTimeFormatter zonedFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z"); | ||||
|         Assert.assertEquals(7200, ZonedDateTime.from(zonedFormatter.parse("31.07.2016 14:15 GMT+02:00")).getOffset().getTotalSeconds()); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = DateTimeParseException.class) | ||||
|     public void shouldExpectAnExceptionIfDateTimeStringNotMatchPattern() { | ||||
|         DateTimeFormatter zonedFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z"); | ||||
|         ZonedDateTime.from(zonedFormatter.parse("31.07.2016 14:15")); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -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)); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -24,3 +24,5 @@ | ||||
| - [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional) | ||||
| - [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api) | ||||
| - [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range) | ||||
| - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) | ||||
| - [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) | ||||
|  | ||||
							
								
								
									
										15
									
								
								core-java-9/logging.sh
									
									
									
									
									
										Executable file
									
								
							
							
						
						
									
										15
									
								
								core-java-9/logging.sh
									
									
									
									
									
										Executable file
									
								
							| @ -0,0 +1,15 @@ | ||||
| # compile logging  module | ||||
| # javac --module-path mods -d mods/com.baeldung.logging src/modules/com.baeldung.logging/module-info.java src/modules/com.baeldung.logging/com/baeldung/logging/*.java | ||||
| 
 | ||||
| # compile logging slf4j module | ||||
| javac --module-path mods -d mods/com.baeldung.logging.slf4j src/modules/com.baeldung.logging.slf4j/module-info.java src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/*.java | ||||
| 
 | ||||
| 
 | ||||
| # compile logging main app module | ||||
| javac --module-path mods -d mods/com.baeldung.logging.app src/modules/com.baeldung.logging.app/module-info.java src/modules/com.baeldung.logging.app/com/baeldung/logging/app/*.java | ||||
| 
 | ||||
| # run logging main app | ||||
| # java --module-path mods -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp | ||||
| 
 | ||||
| # run looging main app using logback | ||||
| java --module-path mods -Dlogback.configurationFile=mods/logback.xml -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp | ||||
							
								
								
									
										16
									
								
								core-java-9/mods/logback.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								core-java-9/mods/logback.xml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,16 @@ | ||||
| <?xml version="1.0" encoding="UTF-8"?> | ||||
| <configuration> | ||||
| 
 | ||||
|     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> | ||||
|         <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> | ||||
|             <pattern> | ||||
|                 %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} -- %msg%n | ||||
|             </pattern> | ||||
|         </encoder> | ||||
|     </appender> | ||||
| 
 | ||||
|     <root> | ||||
|         <appender-ref ref="STDOUT"/> | ||||
|     </root> | ||||
| 
 | ||||
| </configuration> | ||||
| @ -0,0 +1,13 @@ | ||||
| package com.baeldung.logging.app; | ||||
| 
 | ||||
| import static java.lang.System.Logger.*; | ||||
| 
 | ||||
| public class MainApp { | ||||
| 
 | ||||
|     private static System.Logger LOGGER = System.getLogger("MainApp"); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         LOGGER.log(Level.ERROR, "error test"); | ||||
|         LOGGER.log(Level.INFO, "info test"); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,2 @@ | ||||
| module com.baeldung.logging.app { | ||||
| } | ||||
| @ -0,0 +1,99 @@ | ||||
| package com.baeldung.logging.slf4j; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.ResourceBundle; | ||||
| 
 | ||||
| public class Slf4jLogger implements System.Logger { | ||||
| 
 | ||||
|     private final String name; | ||||
|     private final Logger logger; | ||||
| 
 | ||||
|     public Slf4jLogger(String name) { | ||||
|         this.name = name; | ||||
|         logger = LoggerFactory.getLogger(name); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public String getName() { | ||||
|         return name; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public boolean isLoggable(Level level) { | ||||
|         switch (level) { | ||||
|         case OFF: | ||||
|             return false; | ||||
|         case TRACE: | ||||
|             return logger.isTraceEnabled(); | ||||
|         case DEBUG: | ||||
|             return logger.isDebugEnabled(); | ||||
|         case INFO: | ||||
|             return logger.isInfoEnabled(); | ||||
|         case WARNING: | ||||
|             return logger.isWarnEnabled(); | ||||
|         case ERROR: | ||||
|             return logger.isErrorEnabled(); | ||||
|         case ALL: | ||||
|         default: | ||||
|             return true; | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) { | ||||
|         if (!isLoggable(level)) { | ||||
|             return; | ||||
|         } | ||||
| 
 | ||||
|         switch (level) { | ||||
|         case TRACE: | ||||
|             logger.trace(msg, thrown); | ||||
|             break; | ||||
|         case DEBUG: | ||||
|             logger.debug(msg, thrown); | ||||
|             break; | ||||
|         case INFO: | ||||
|             logger.info(msg, thrown); | ||||
|             break; | ||||
|         case WARNING: | ||||
|             logger.warn(msg, thrown); | ||||
|             break; | ||||
|         case ERROR: | ||||
|             logger.error(msg, thrown); | ||||
|             break; | ||||
|         case ALL: | ||||
|         default: | ||||
|             logger.info(msg, thrown); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void log(Level level, ResourceBundle bundle, String format, Object... params) { | ||||
|         if (!isLoggable(level)) { | ||||
|             return; | ||||
|         } | ||||
| 
 | ||||
|         switch (level) { | ||||
|         case TRACE: | ||||
|             logger.trace(format, params); | ||||
|             break; | ||||
|         case DEBUG: | ||||
|             logger.debug(format, params); | ||||
|             break; | ||||
|         case INFO: | ||||
|             logger.info(format, params); | ||||
|             break; | ||||
|         case WARNING: | ||||
|             logger.warn(format, params); | ||||
|             break; | ||||
|         case ERROR: | ||||
|             logger.error(format, params); | ||||
|             break; | ||||
|         case ALL: | ||||
|         default: | ||||
|             logger.info(format, params); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,8 @@ | ||||
| package com.baeldung.logging.slf4j; | ||||
| 
 | ||||
| public class Slf4jLoggerFinder extends System.LoggerFinder { | ||||
|     @Override | ||||
|     public System.Logger getLogger(String name, Module module) { | ||||
|         return new Slf4jLogger(name); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,6 @@ | ||||
| module com.baeldung.logging.slf4j { | ||||
|     requires org.slf4j; | ||||
|     provides java.lang.System.LoggerFinder | ||||
|       with com.baeldung.logging.slf4j.Slf4jLoggerFinder; | ||||
|     exports com.baeldung.logging.slf4j; | ||||
| } | ||||
| @ -0,0 +1,27 @@ | ||||
| package com.baeldung.logging; | ||||
| 
 | ||||
| import java.text.MessageFormat; | ||||
| import java.util.ResourceBundle; | ||||
| 
 | ||||
| public class ConsoleLogger implements System.Logger { | ||||
| 
 | ||||
|     @Override | ||||
|     public String getName() { | ||||
|         return "ConsoleLogger"; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public boolean isLoggable(Level level) { | ||||
|         return true; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) { | ||||
|         System.out.printf("ConsoleLogger [%s]: %s - %s%n", level, msg, thrown); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void log(Level level, ResourceBundle bundle, String format, Object... params) { | ||||
|         System.out.printf("ConsoleLogger [%s]: %s%n", level, MessageFormat.format(format, params)); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,9 @@ | ||||
| package com.baeldung.logging; | ||||
| 
 | ||||
| public class CustomLoggerFinder extends System.LoggerFinder { | ||||
| 
 | ||||
|     @Override | ||||
|     public System.Logger getLogger(String name, Module module) { | ||||
|         return new ConsoleLogger(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,5 @@ | ||||
| module com.baeldung.logging { | ||||
|     provides java.lang.System.LoggerFinder | ||||
|       with com.baeldung.logging.CustomLoggerFinder; | ||||
|     exports com.baeldung.logging; | ||||
| } | ||||
| @ -43,3 +43,12 @@ | ||||
| - [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) | ||||
| - [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) | ||||
| - [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) | ||||
| - [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections) | ||||
| - [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list) | ||||
| - [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) | ||||
| - [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall) | ||||
| - [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) | ||||
|  | ||||
| @ -63,6 +63,17 @@ | ||||
|             <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> | ||||
|         <dependency> | ||||
|             <groupId>one.util</groupId> | ||||
|             <artifactId>streamex</artifactId> | ||||
|             <version>0.6.5</version> | ||||
|         </dependency> | ||||
| 		         | ||||
|     </dependencies> | ||||
| 
 | ||||
| 
 | ||||
|  | ||||
| @ -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; | ||||
|     } | ||||
|      | ||||
| } | ||||
| @ -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; | ||||
|     } | ||||
|      | ||||
| } | ||||
| @ -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; | ||||
|     } | ||||
|      | ||||
| } | ||||
| @ -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; | ||||
|     } | ||||
|      | ||||
| } | ||||
| @ -0,0 +1,52 @@ | ||||
| package com.baeldung.convertcollectiontoarraylist; | ||||
| 
 | ||||
| /** | ||||
|  * This POJO is the element type of our collection. It has a deepCopy() method. | ||||
|  * | ||||
|  * @author chris | ||||
|  */ | ||||
| public class Foo { | ||||
| 
 | ||||
|     private int id; | ||||
|     private String name; | ||||
|     private Foo parent; | ||||
| 
 | ||||
|     public Foo() { | ||||
|     } | ||||
| 
 | ||||
|     public Foo(int id, String name, Foo parent) { | ||||
|         this.id = id; | ||||
|         this.name = name; | ||||
|         this.parent = parent; | ||||
|     } | ||||
| 
 | ||||
|     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 Foo getParent() { | ||||
|         return parent; | ||||
|     } | ||||
| 
 | ||||
|     public void setParent(Foo parent) { | ||||
|         this.parent = parent; | ||||
|     } | ||||
| 
 | ||||
|     public Foo deepCopy() { | ||||
|         return new Foo( | ||||
|           this.id, this.name, this.parent != null ? this.parent.deepCopy() : null); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,44 @@ | ||||
| /** | ||||
|  *  | ||||
|  */ | ||||
| package com.baeldung.java.map; | ||||
| 
 | ||||
| import java.util.HashSet; | ||||
| import java.util.Map; | ||||
| import java.util.Set; | ||||
| import java.util.Map.Entry; | ||||
| import java.util.stream.Stream; | ||||
| 
 | ||||
| /** | ||||
|  * @author swpraman | ||||
|  * | ||||
|  */ | ||||
| public class MapUtil { | ||||
|      | ||||
|     public static <K, V> Stream<K> keys(Map<K, V> map, V value) { | ||||
|         return map.entrySet() | ||||
|                 .stream() | ||||
|                 .filter(entry -> value.equals(entry.getValue())) | ||||
|                 .map(Map.Entry::getKey); | ||||
|     } | ||||
|      | ||||
|     public static <K, V> Set<K> getKeys(Map<K, V> map, V value) { | ||||
|         Set<K> keys = new HashSet<>(); | ||||
|         for (Entry<K, V> entry : map.entrySet()) { | ||||
|             if (entry.getValue().equals(value)) { | ||||
|                 keys.add(entry.getKey()); | ||||
|             } | ||||
|         } | ||||
|         return keys; | ||||
|     } | ||||
|      | ||||
|     public static <K, V> K getKey(Map<K, V> map, V value) { | ||||
|         for (Entry<K, V> entry : map.entrySet()) { | ||||
|             if (entry.getValue().equals(value)) { | ||||
|                 return entry.getKey(); | ||||
|             } | ||||
|         } | ||||
|         return null; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,105 @@ | ||||
| package com.baeldung.map.java_8; | ||||
| 
 | ||||
| import com.baeldung.sort.Employee; | ||||
| import one.util.streamex.EntryStream; | ||||
| import java.util.HashMap; | ||||
| import java.util.Map; | ||||
| import java.util.stream.Collectors; | ||||
| import java.util.stream.Stream; | ||||
| 
 | ||||
| public class MergeMaps { | ||||
| 
 | ||||
|     private static Map<String, Employee> map1 = new HashMap<>(); | ||||
|     private static Map<String, Employee> map2 = new HashMap<>(); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
| 
 | ||||
|         initialize(); | ||||
| 
 | ||||
|         mergeFunction(); | ||||
| 
 | ||||
|         streamConcat(); | ||||
| 
 | ||||
|         streamOf(); | ||||
| 
 | ||||
|         streamEx(); | ||||
| 
 | ||||
|         streamMerge(); | ||||
|     } | ||||
| 
 | ||||
|     private static void streamMerge() { | ||||
| 
 | ||||
|         Map<String, Employee> map3 = map2.entrySet() | ||||
|                 .stream() | ||||
|                 .collect( | ||||
|                         Collectors.toMap( | ||||
|                                 Map.Entry::getKey, | ||||
|                                 Map.Entry::getValue, | ||||
|                                 (v1, v2) -> new Employee(v1.getId(), v2.getName()), | ||||
|                                 () -> new HashMap<>(map1) | ||||
|                         ) | ||||
|                 ); | ||||
| 
 | ||||
|         System.out.println(map3); | ||||
|     } | ||||
| 
 | ||||
|     private static void streamEx() { | ||||
|         Map<String, Employee> map3 = EntryStream.of(map1) | ||||
|                 .append(EntryStream.of(map2)) | ||||
|                 .toMap((e1, e2) -> e1); | ||||
| 
 | ||||
|         System.out.println(map3); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|     private static void streamOf() { | ||||
|         Map<String, Employee> map3 = Stream.of(map1, map2) | ||||
|                 .flatMap(map -> map.entrySet().stream()) | ||||
|                 .collect( | ||||
|                         Collectors.toMap( | ||||
|                                 Map.Entry::getKey, | ||||
|                                 Map.Entry::getValue, | ||||
|                                 (v1, v2) -> new Employee(v1.getId(), v2.getName()) | ||||
|                         ) | ||||
|                 ); | ||||
| 
 | ||||
|         map3.entrySet().forEach(System.out::println); | ||||
|     } | ||||
| 
 | ||||
|     private static void streamConcat() { | ||||
|         Map<String, Employee> result = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(Collectors.toMap( | ||||
|                 Map.Entry::getKey, | ||||
|                 Map.Entry::getValue, | ||||
|                 (value1, value2) -> new Employee(value2.getId(), value1.getName()) | ||||
|         )); | ||||
| 
 | ||||
|         result.entrySet().forEach(System.out::println); | ||||
|     } | ||||
| 
 | ||||
|     private static void mergeFunction() { | ||||
|         Map<String, Employee> map3 = new HashMap<>(map1); | ||||
| 
 | ||||
|         map2.forEach( | ||||
|                 (key, value) -> map3.merge(key, value, (v1, v2) -> | ||||
|                         new Employee(v1.getId(), v2.getName())) | ||||
|         ); | ||||
| 
 | ||||
|         map3.entrySet().forEach(System.out::println); | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
|     private static void initialize() { | ||||
|         Employee employee1 = new Employee(1L, "Henry"); | ||||
|         map1.put(employee1.getName(), employee1); | ||||
|         Employee employee2 = new Employee(22L, "Annie"); | ||||
|         map1.put(employee2.getName(), employee2); | ||||
|         Employee employee3 = new Employee(8L, "John"); | ||||
|         map1.put(employee3.getName(), employee3); | ||||
| 
 | ||||
|         Employee employee4 = new Employee(2L, "George"); | ||||
|         map2.put(employee4.getName(), employee4); | ||||
|         Employee employee5 = new Employee(3L, "Henry"); | ||||
|         map2.put(employee5.getName(), employee5); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -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)); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -44,4 +44,12 @@ public class Employee { | ||||
|         result = 31 * result + name.hashCode(); | ||||
|         return result; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public String toString() { | ||||
|         return "Employee{" + | ||||
|                 "id=" + id + | ||||
|                 ", name='" + name + '\'' + | ||||
|                 '}'; | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -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()); | ||||
|     } | ||||
| } | ||||
| @ -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); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,40 @@ | ||||
| package com.baeldung.collection; | ||||
| 
 | ||||
| import org.junit.jupiter.api.Test; | ||||
| 
 | ||||
| import java.util.ArrayList; | ||||
| import java.util.Arrays; | ||||
| import java.util.Collection; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| /** | ||||
|  * Unit tests demonstrating differences between ArrayList#clear() and ArrayList#removeAll() | ||||
|  */ | ||||
| class ClearVsRemoveAllUnitTest { | ||||
| 
 | ||||
|     /* | ||||
|      * Tests | ||||
|      */ | ||||
|     @Test | ||||
|     void givenArrayListWithElements_whenClear_thenListBecomesEmpty() { | ||||
|         Collection<Integer> collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); | ||||
| 
 | ||||
|         collection.clear(); | ||||
| 
 | ||||
|         assertTrue(collection.isEmpty()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     void givenTwoArrayListsWithCommonElements_whenRemoveAll_thenFirstListMissElementsFromSecondList() { | ||||
|         Collection<Integer> firstCollection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); | ||||
|         Collection<Integer> secondCollection = new ArrayList<>(Arrays.asList(3, 4, 5, 6, 7)); | ||||
| 
 | ||||
|         firstCollection.removeAll(secondCollection); | ||||
| 
 | ||||
|         assertEquals(Arrays.asList(1, 2), firstCollection); | ||||
|         assertEquals(Arrays.asList(3, 4, 5, 6, 7), secondCollection); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -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)); | ||||
|     } | ||||
| } | ||||
| @ -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)); | ||||
|     } | ||||
| } | ||||
| @ -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)); | ||||
|     } | ||||
| } | ||||
| @ -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)); | ||||
| 	} | ||||
| } | ||||
| @ -0,0 +1,148 @@ | ||||
| package com.baeldung.convertcollectiontoarraylist; | ||||
| 
 | ||||
| import java.util.ArrayList; | ||||
| import java.util.Collection; | ||||
| import java.util.Comparator; | ||||
| import java.util.HashSet; | ||||
| import java.util.Iterator; | ||||
| import static java.util.stream.Collectors.toCollection; | ||||
| import org.junit.BeforeClass; | ||||
| import org.junit.Test; | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| /** | ||||
|  * | ||||
|  * @author chris | ||||
|  */ | ||||
| public class FooUnitTest { | ||||
|     private static Collection<Foo> srcCollection = new HashSet<>(); | ||||
| 
 | ||||
|     public FooUnitTest() { | ||||
|     } | ||||
|      | ||||
|     @BeforeClass | ||||
|     public static void setUpClass() { | ||||
|         int i = 0; | ||||
|         Foo john = new Foo(i++, "John", null); | ||||
|         Foo mary = new Foo(i++, "Mary", null); | ||||
|         Foo sam = new Foo(i++, "Sam", john); | ||||
|         Foo alice = new Foo(i++, "Alice", john); | ||||
|         Foo buffy = new Foo(i++, "Buffy", sam); | ||||
|         srcCollection.add(john); | ||||
|         srcCollection.add(mary); | ||||
|         srcCollection.add(sam); | ||||
|         srcCollection.add(alice); | ||||
|         srcCollection.add(buffy); | ||||
| 
 | ||||
|         // make sure the collection isn't sorted accidentally | ||||
|         assertFalse("Oops: source collection is already sorted!", isSorted(srcCollection)); | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * Section 3. Using the ArrayList Constructor | ||||
|      */ | ||||
|     @Test | ||||
|     public void whenUsingConstructor_thenVerifyShallowCopy() { | ||||
|         ArrayList<Foo> newList = new ArrayList<>(srcCollection); | ||||
|         verifyShallowCopy(srcCollection, newList); | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * Section 4. Using the Streams API | ||||
|      */ | ||||
|     @Test | ||||
|     public void whenUsingStream_thenVerifyShallowCopy() { | ||||
|         ArrayList<Foo> newList = srcCollection.stream().collect(toCollection(ArrayList::new)); | ||||
| 
 | ||||
|         verifyShallowCopy(srcCollection, newList); | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * Section 5. Deep Copy | ||||
|      */ | ||||
|     @Test | ||||
|     public void whenUsingDeepCopy_thenVerifyDeepCopy() { | ||||
|         ArrayList<Foo> newList = srcCollection.stream() | ||||
|           .map(foo -> foo.deepCopy()) | ||||
|           .collect(toCollection(ArrayList::new)); | ||||
| 
 | ||||
|         verifyDeepCopy(srcCollection, newList); | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * Section 6. Controlling the List Order | ||||
|      */ | ||||
|     @Test | ||||
|     public void whenUsingSortedStream_thenVerifySortOrder() { | ||||
|         ArrayList<Foo> newList = srcCollection.stream() | ||||
|           .sorted(Comparator.comparing(Foo::getName)) | ||||
|           .collect(toCollection(ArrayList::new)); | ||||
| 
 | ||||
|         assertTrue("ArrayList is not sorted by name", isSorted(newList)); | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * Verify that the contents of the two collections are the same | ||||
|      * @param a | ||||
|      * @param b  | ||||
|      */ | ||||
|     private void verifyShallowCopy(Collection a, Collection b) { | ||||
|         assertEquals("Collections have different lengths", a.size(), b.size()); | ||||
|         Iterator<Foo> iterA = a.iterator(); | ||||
|         Iterator<Foo> iterB = b.iterator(); | ||||
|         while (iterA.hasNext()) { | ||||
|             // use '==' to test instance identity | ||||
|             assertTrue("Foo instances differ!", iterA.next() == iterB.next()); | ||||
|         } | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * Verify that the contents of the two collections are the same | ||||
|      * @param a | ||||
|      * @param b  | ||||
|      */ | ||||
|     private void verifyDeepCopy(Collection a, Collection b) { | ||||
|         assertEquals("Collections have different lengths", a.size(), b.size()); | ||||
|         Iterator<Foo> iterA = a.iterator(); | ||||
|         Iterator<Foo> iterB = b.iterator(); | ||||
|         while (iterA.hasNext()) { | ||||
|             Foo nextA = iterA.next(); | ||||
|             Foo nextB = iterB.next(); | ||||
|             // should not be same instance | ||||
|             assertFalse("Foo instances are the same!", nextA == nextB); | ||||
|             // but should have same content | ||||
|             assertFalse("Foo instances have different content!", fooDiff(nextA, nextB)); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     /** | ||||
|      * Return true if the contents of a and b differ.  Test parent recursively | ||||
|      * @param a | ||||
|      * @param b | ||||
|      * @return False if the two items are the same | ||||
|      */ | ||||
|     private boolean fooDiff(Foo a, Foo b) { | ||||
|         if (a != null && b != null) { | ||||
|             return a.getId() != b.getId()  | ||||
|               || !a.getName().equals(b.getName())  | ||||
|               || fooDiff(a.getParent(), b.getParent()); | ||||
|         } | ||||
|         return !(a == null && b == null); | ||||
|     } | ||||
|      | ||||
|     /** | ||||
|      * @param c collection of Foo | ||||
|      * @return true if the collection is sorted by name | ||||
|      */ | ||||
|     private static boolean isSorted(Collection<Foo> c) { | ||||
|         String prevName = null; | ||||
|         for (Foo foo : c) { | ||||
|             if (prevName == null || foo.getName().compareTo(prevName) > 0) { | ||||
|                 prevName = foo.getName(); | ||||
|             } else { | ||||
|                 return false; | ||||
|             } | ||||
|         } | ||||
|         return true; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,29 @@ | ||||
| package com.baeldung.java.map; | ||||
| 
 | ||||
| import static org.junit.Assert.assertFalse; | ||||
| import static org.junit.Assert.assertNull; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import java.util.Collections; | ||||
| import java.util.Map; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class KeyCheckUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenKeyIsPresent_thenContainsKeyReturnsTrue() { | ||||
|         Map<String, String> map = Collections.singletonMap("key", "value"); | ||||
| 
 | ||||
|         assertTrue(map.containsKey("key")); | ||||
|         assertFalse(map.containsKey("missing")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenKeyHasNullValue_thenGetStillWorks() { | ||||
|         Map<String, String> map = Collections.singletonMap("nothing", null); | ||||
| 
 | ||||
|         assertTrue(map.containsKey("nothing")); | ||||
|         assertNull(map.get("nothing")); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,104 @@ | ||||
| /** | ||||
|  *  | ||||
|  */ | ||||
| package com.baeldung.java.map; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| import java.util.Arrays; | ||||
| import java.util.HashMap; | ||||
| import java.util.HashSet; | ||||
| import java.util.Map; | ||||
| import java.util.stream.Collectors; | ||||
| 
 | ||||
| import org.apache.commons.collections4.BidiMap; | ||||
| import org.apache.commons.collections4.bidimap.DualHashBidiMap; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.google.common.collect.HashBiMap; | ||||
| 
 | ||||
| /** | ||||
|  * @author swpraman | ||||
|  * | ||||
|  */ | ||||
| public class MapUtilUnitTest { | ||||
|      | ||||
|      | ||||
|     @Test | ||||
|     public void whenUsingImperativeWayForSingleKey_shouldReturnSingleKey() { | ||||
|         Map<String, String> capitalCountryMap = new HashMap<>(); | ||||
|         capitalCountryMap.put("Tokyo", "Japan"); | ||||
|         capitalCountryMap.put("New Delhi", "India"); | ||||
|         assertEquals("New Delhi", MapUtil.getKey(capitalCountryMap, "India")); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenUsingImperativeWayForAllKeys_shouldReturnAllKeys() { | ||||
|         Map<String, String> capitalCountryMap = new HashMap<>(); | ||||
|         capitalCountryMap.put("Tokyo", "Japan"); | ||||
|         capitalCountryMap.put("Berlin", "Germany"); | ||||
|         capitalCountryMap.put("Cape Town", "South Africa"); | ||||
|         capitalCountryMap.put("Pretoria", "South Africa"); | ||||
|         capitalCountryMap.put("Bloemfontein", "South Africa"); | ||||
| 
 | ||||
|         assertEquals(new HashSet<String>(Arrays.asList( | ||||
|                 new String[] {"Cape Town", "Pretoria", "Bloemfontein"})),  | ||||
|                 MapUtil.getKeys(capitalCountryMap, "South Africa")); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenUsingFunctionalWayForSingleKey_shouldReturnSingleKey() { | ||||
|         Map<String, String> capitalCountryMap = new HashMap<>(); | ||||
|         capitalCountryMap.put("Tokyo", "Japan"); | ||||
|         capitalCountryMap.put("Berlin", "Germany"); | ||||
|         assertEquals("Berlin", MapUtil.keys(capitalCountryMap, "Germany").findFirst().get()); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenUsingFunctionalWayForAllKeys_shouldReturnAllKeys() { | ||||
|         Map<String, String> capitalCountryMap = new HashMap<>(); | ||||
|         capitalCountryMap.put("Tokyo", "Japan"); | ||||
|         capitalCountryMap.put("Berlin", "Germany"); | ||||
|         capitalCountryMap.put("Cape Town", "South Africa"); | ||||
|         capitalCountryMap.put("Pretoria", "South Africa"); | ||||
|         capitalCountryMap.put("Bloemfontein", "South Africa"); | ||||
|         assertEquals(new HashSet<String>(Arrays.asList( | ||||
|                 new String[] {"Cape Town", "Pretoria", "Bloemfontein"})),  | ||||
|                 MapUtil.keys(capitalCountryMap, "South Africa").collect(Collectors.toSet())); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenUsingBidiMap_shouldReturnKey() { | ||||
|         BidiMap<String, String> capitalCountryMap = new DualHashBidiMap<String, String>(); | ||||
|         capitalCountryMap.put("Berlin", "Germany"); | ||||
|         capitalCountryMap.put("Cape Town", "South Africa"); | ||||
|         assertEquals("Berlin", capitalCountryMap.getKey("Germany")); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenUsingBidiMapAddDuplicateValue_shouldRemoveOldEntry() { | ||||
|         BidiMap<String, String> capitalCountryMap = new DualHashBidiMap<String, String>(); | ||||
|         capitalCountryMap.put("Berlin", "Germany"); | ||||
|         capitalCountryMap.put("Cape Town", "South Africa"); | ||||
|         capitalCountryMap.put("Pretoria", "South Africa"); | ||||
|         assertEquals("Pretoria", capitalCountryMap.getKey("South Africa")); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenUsingBiMap_shouldReturnKey() { | ||||
|         HashBiMap<String, String> capitalCountryMap = HashBiMap.create(); | ||||
|         capitalCountryMap.put("Berlin", "Germany"); | ||||
|         capitalCountryMap.put("Cape Town", "South Africa"); | ||||
|         assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); | ||||
|     } | ||||
|      | ||||
|     @Test(expected=IllegalArgumentException.class) | ||||
|     public void whenUsingBiMapAddDuplicateValue_shouldThrowException() { | ||||
|         HashBiMap<String, String> capitalCountryMap = HashBiMap.create(); | ||||
|         capitalCountryMap.put("Berlin", "Germany"); | ||||
|         capitalCountryMap.put("Cape Town", "South Africa"); | ||||
|         capitalCountryMap.put("Pretoria", "South Africa"); | ||||
|         assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -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)); | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
| } | ||||
| @ -57,26 +57,6 @@ | ||||
|                 <filtering>true</filtering> | ||||
|             </resource> | ||||
|         </resources> | ||||
| 
 | ||||
|         <plugins> | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-dependency-plugin</artifactId> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <id>copy-dependencies</id> | ||||
|                         <phase>prepare-package</phase> | ||||
|                         <goals> | ||||
|                             <goal>copy-dependencies</goal> | ||||
|                         </goals> | ||||
|                         <configuration> | ||||
|                             <outputDirectory>${project.build.directory}/libs</outputDirectory> | ||||
|                         </configuration> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
|              | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
|     <properties> | ||||
|  | ||||
| @ -57,26 +57,6 @@ | ||||
|                 <filtering>true</filtering> | ||||
|             </resource> | ||||
|         </resources> | ||||
| 
 | ||||
|         <plugins> | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-dependency-plugin</artifactId> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <id>copy-dependencies</id> | ||||
|                         <phase>prepare-package</phase> | ||||
|                         <goals> | ||||
|                             <goal>copy-dependencies</goal> | ||||
|                         </goals> | ||||
|                         <configuration> | ||||
|                             <outputDirectory>${project.build.directory}/libs</outputDirectory> | ||||
|                         </configuration> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
|              | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
|     <properties> | ||||
|  | ||||
| @ -0,0 +1,17 @@ | ||||
| package com.baeldung.concurrent.yield; | ||||
| 
 | ||||
| public class ThreadYield { | ||||
|     public static void main(String[] args) { | ||||
|         Runnable r = () -> { | ||||
|             int counter = 0; | ||||
|             while (counter < 2) { | ||||
|                 System.out.println(Thread.currentThread() | ||||
|                     .getName()); | ||||
|                 counter++; | ||||
|                 Thread.yield(); | ||||
|             } | ||||
|         }; | ||||
|         new Thread(r).start(); | ||||
|         new Thread(r).start(); | ||||
|     } | ||||
| } | ||||
| @ -30,3 +30,5 @@ | ||||
| - [Download a File From an URL in Java](http://www.baeldung.com/java-download-file) | ||||
| - [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) | ||||
|  | ||||
| @ -1,7 +1,6 @@ | ||||
| <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>core-java-io</artifactId> | ||||
|     <version>0.1.0-SNAPSHOT</version> | ||||
|     <packaging>jar</packaging> | ||||
| @ -166,36 +165,6 @@ | ||||
|             </resource> | ||||
|         </resources> | ||||
|         <plugins> | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-surefire-plugin</artifactId> | ||||
|                 <configuration> | ||||
|                     <excludes> | ||||
|                         <exclude>**/*LiveTest.java</exclude> | ||||
|                         <exclude>**/*IntegrationTest.java</exclude> | ||||
|                         <exclude>**/*IntTest.java</exclude> | ||||
|                         <exclude>**/*LongRunningUnitTest.java</exclude> | ||||
|                         <exclude>**/*ManualTest.java</exclude> | ||||
|                     </excludes> | ||||
|                     <testFailureIgnore>true</testFailureIgnore> | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
|             <plugin> | ||||
|                 <groupId>org.springframework.boot</groupId> | ||||
|                 <artifactId>spring-boot-maven-plugin</artifactId> | ||||
|                 <version>${spring-boot-maven-plugin.version}</version> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <goals> | ||||
|                             <goal>repackage</goal> | ||||
|                         </goals> | ||||
|                         <configuration> | ||||
|                             <classifier>spring-boot</classifier> | ||||
|                             <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> | ||||
|                         </configuration> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
|             <plugin> | ||||
|                 <groupId>org.codehaus.mojo</groupId> | ||||
|                 <artifactId>exec-maven-plugin</artifactId> | ||||
| @ -229,32 +198,6 @@ | ||||
|             <id>integration</id> | ||||
|             <build> | ||||
|                 <plugins> | ||||
|                     <plugin> | ||||
|                         <groupId>org.apache.maven.plugins</groupId> | ||||
|                         <artifactId>maven-surefire-plugin</artifactId> | ||||
|                         <executions> | ||||
|                             <execution> | ||||
|                                 <phase>integration-test</phase> | ||||
|                                 <goals> | ||||
|                                     <goal>test</goal> | ||||
|                                 </goals> | ||||
|                                 <configuration> | ||||
|                                     <excludes> | ||||
|                                         <exclude>**/*ManualTest.java</exclude> | ||||
|                                     </excludes> | ||||
|                                     <includes> | ||||
|                                         <include>**/*IntegrationTest.java</include> | ||||
|                                         <include>**/*IntTest.java</include> | ||||
|                                     </includes> | ||||
|                                 </configuration> | ||||
|                             </execution> | ||||
|                         </executions> | ||||
|                         <configuration> | ||||
|                             <systemPropertyVariables> | ||||
|                                 <test.mime>json</test.mime> | ||||
|                             </systemPropertyVariables> | ||||
|                         </configuration> | ||||
|                     </plugin> | ||||
|                     <plugin> | ||||
|                         <groupId>org.codehaus.mojo</groupId> | ||||
|                         <artifactId>exec-maven-plugin</artifactId> | ||||
| @ -310,14 +253,11 @@ | ||||
|         <avaitility.version>1.7.0</avaitility.version> | ||||
| 
 | ||||
|         <!-- maven plugins --> | ||||
|         <maven.compiler.source>1.8</maven.compiler.source> | ||||
|         <maven.compiler.target>1.8</maven.compiler.target> | ||||
|         <maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version> | ||||
|         <hsqldb.version>2.4.0</hsqldb.version> | ||||
|         <esapi.version>2.1.0.1</esapi.version> | ||||
|         <jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version> | ||||
|         <async-http-client.version>2.4.5</async-http-client.version> | ||||
|         <spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
| @ -0,0 +1,48 @@ | ||||
| package com.baeldung.stream; | ||||
| 
 | ||||
| import java.io.BufferedOutputStream; | ||||
| import java.io.FileOutputStream; | ||||
| import java.io.IOException; | ||||
| import java.io.OutputStream; | ||||
| import java.io.OutputStreamWriter; | ||||
| import java.io.Writer; | ||||
| 
 | ||||
| public class OutputStreamExamples { | ||||
| 
 | ||||
|     public void fileOutputStreamByteSequence(String file, String data) throws IOException { | ||||
|         byte[] bytes = data.getBytes(); | ||||
|         try (OutputStream out = new FileOutputStream(file)) { | ||||
|             out.write(bytes); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public void fileOutputStreamByteSubSequence(String file, String data) throws IOException { | ||||
|         byte[] bytes = data.getBytes(); | ||||
|         try (OutputStream out = new FileOutputStream(file)) { | ||||
|             out.write(bytes, 6, 5); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public void fileOutputStreamByteSingle(String file, String data) throws IOException { | ||||
|         byte[] bytes = data.getBytes(); | ||||
|         try (OutputStream out = new FileOutputStream(file)) { | ||||
|             out.write(bytes[6]); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public void bufferedOutputStream(String file, String... data) throws IOException { | ||||
|         try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { | ||||
|             for (String s : data) { | ||||
|                 out.write(s.getBytes()); | ||||
|                 out.write(" ".getBytes()); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public void outputStreamWriter(String file, String data) throws IOException { | ||||
|         try (OutputStream out = new FileOutputStream(file); Writer writer = new OutputStreamWriter(out, "UTF-8")) { | ||||
|             writer.write(data); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -24,6 +24,13 @@ public class ZipDirectory { | ||||
|             return; | ||||
|         } | ||||
|         if (fileToZip.isDirectory()) { | ||||
|             if (fileName.endsWith("/")) { | ||||
|                 zipOut.putNextEntry(new ZipEntry(fileName)); | ||||
|                 zipOut.closeEntry(); | ||||
|             } else { | ||||
|                 zipOut.putNextEntry(new ZipEntry(fileName + "/")); | ||||
|                 zipOut.closeEntry(); | ||||
|             } | ||||
|             final File[] children = fileToZip.listFiles(); | ||||
|             for (final File childFile : children) { | ||||
|                 zipFile(childFile, fileName + "/" + childFile.getName(), zipOut); | ||||
|  | ||||
| @ -1,6 +1,7 @@ | ||||
| package com.baeldung.file; | ||||
| 
 | ||||
| import org.apache.commons.io.FileUtils; | ||||
| import org.apache.commons.io.IOUtils; | ||||
| import org.hamcrest.CoreMatchers; | ||||
| import org.hamcrest.Matchers; | ||||
| import org.junit.Test; | ||||
| @ -17,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; | ||||
| @ -49,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"); | ||||
| @ -78,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()); | ||||
|     } | ||||
| @ -101,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 { | ||||
| @ -120,4 +121,14 @@ public class FileOperationsManualTest { | ||||
| 
 | ||||
|         return resultStringBuilder.toString(); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void givenFileName_whenUsingIOUtils_thenFileData() throws IOException { | ||||
|         String expectedData = "This is a content of the file"; | ||||
| 
 | ||||
|         FileInputStream fis = new FileInputStream("src/test/resources/fileToRead.txt"); | ||||
|         String data = IOUtils.toString(fis, "UTF-8"); | ||||
|          | ||||
|         assertEquals(expectedData, data.trim()); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,76 @@ | ||||
| package com.baeldung.stream; | ||||
| 
 | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import java.io.File; | ||||
| import java.io.IOException; | ||||
| 
 | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class OutputStreamExamplesTest { | ||||
|      | ||||
|     StringBuilder filePath = new StringBuilder(); | ||||
|      | ||||
|     @Before | ||||
|     public void init() { | ||||
|         filePath.append("src"); | ||||
|         filePath.append(File.separator); | ||||
|         filePath.append("test"); | ||||
|         filePath.append(File.separator); | ||||
|         filePath.append("resources"); | ||||
|         filePath.append(File.separator); | ||||
|         filePath.append("output_file.txt"); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void givenOutputStream_whenWriteSingleByteCalled_thenOutputCreated() throws IOException { | ||||
|          | ||||
|         final File file = new File(filePath.toString());     | ||||
|         OutputStreamExamples examples = new OutputStreamExamples();     | ||||
|         examples.fileOutputStreamByteSingle(filePath.toString(), "Hello World!"); | ||||
|         assertTrue(file.exists()); | ||||
|         file.delete(); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void givenOutputStream_whenWriteByteSequenceCalled_thenOutputCreated() throws IOException { | ||||
|          | ||||
|         final File file = new File(filePath.toString());     | ||||
|         OutputStreamExamples examples = new OutputStreamExamples();     | ||||
|         examples.fileOutputStreamByteSequence(filePath.toString(), "Hello World!"); | ||||
|         assertTrue(file.exists()); | ||||
|         file.delete(); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void givenOutputStream_whenWriteByteSubSequenceCalled_thenOutputCreated() throws IOException { | ||||
|          | ||||
|         final File file = new File(filePath.toString());     | ||||
|         OutputStreamExamples examples = new OutputStreamExamples();     | ||||
|         examples.fileOutputStreamByteSubSequence(filePath.toString(), "Hello World!"); | ||||
|         assertTrue(file.exists()); | ||||
|         file.delete(); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenBufferedOutputStream_whenCalled_thenOutputCreated() throws IOException { | ||||
|          | ||||
|         final File file = new File(filePath.toString());     | ||||
|         OutputStreamExamples examples = new OutputStreamExamples();     | ||||
|         examples.bufferedOutputStream(filePath.toString(), "Hello", "World!"); | ||||
|         assertTrue(file.exists()); | ||||
|         file.delete(); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void givenOutputStreamWriter_whenCalled_thenOutputCreated() throws IOException { | ||||
|          | ||||
|         final File file = new File(filePath.toString());     | ||||
|         OutputStreamExamples examples = new OutputStreamExamples();     | ||||
|         examples.outputStreamWriter(filePath.toString(), "Hello World!"); | ||||
|         assertTrue(file.exists()); | ||||
|         file.delete(); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
Some files were not shown because too many files have changed in this diff Show More
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user