Merge branch 'master' of https://github.com/ahmedtawila/tutorials
This commit is contained in:
		
						commit
						c41a54dc40
					
				| @ -6,3 +6,5 @@ | |||||||
| - [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java) | - [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java) | ||||||
| - [Introduction to Jenetics Library](http://www.baeldung.com/jenetics) | - [Introduction to Jenetics Library](http://www.baeldung.com/jenetics) | ||||||
| - [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers) | - [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers) | ||||||
|  | - [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm) | ||||||
|  | - [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search) | ||||||
|  | |||||||
| @ -18,12 +18,12 @@ public class MiniMax { | |||||||
|         constructTree(root); |         constructTree(root); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     private void constructTree(Node node) { |     private void constructTree(Node parentNode) { | ||||||
|         List<Integer> listofPossibleHeaps = GameOfBones.getPossibleStates(node.getNoOfBones()); |         List<Integer> listofPossibleHeaps = GameOfBones.getPossibleStates(parentNode.getNoOfBones()); | ||||||
|         boolean isMaxPlayer = !node.isMaxPlayer(); |         boolean isChildMaxPlayer = !parentNode.isMaxPlayer(); | ||||||
|         listofPossibleHeaps.forEach(n -> { |         listofPossibleHeaps.forEach(n -> { | ||||||
|             Node newNode = new Node(n, isMaxPlayer); |             Node newNode = new Node(n, isChildMaxPlayer); | ||||||
|             node.addChild(newNode); |             parentNode.addChild(newNode); | ||||||
|             if (newNode.getNoOfBones() > 0) { |             if (newNode.getNoOfBones() > 0) { | ||||||
|                 constructTree(newNode); |                 constructTree(newNode); | ||||||
|             } |             } | ||||||
|  | |||||||
| @ -35,7 +35,12 @@ | |||||||
|                 <configuration> |                 <configuration> | ||||||
|                     <sourceDirectory>src/docs/asciidoc</sourceDirectory> |                     <sourceDirectory>src/docs/asciidoc</sourceDirectory> | ||||||
|                     <outputDirectory>target/docs/asciidoc</outputDirectory> |                     <outputDirectory>target/docs/asciidoc</outputDirectory> | ||||||
|  |                     <attributes> | ||||||
|  |                         <pdf-stylesdir>${project.basedir}/src/themes</pdf-stylesdir> | ||||||
|  |                         <pdf-style>custom</pdf-style> | ||||||
|  |                     </attributes> | ||||||
|                     <backend>pdf</backend> |                     <backend>pdf</backend> | ||||||
|  |                     <doctype>book</doctype> | ||||||
|                 </configuration> |                 </configuration> | ||||||
|             </plugin> |             </plugin> | ||||||
|         </plugins> |         </plugins> | ||||||
|  | |||||||
| @ -1,3 +1,13 @@ | |||||||
| == Introduction Section | :icons: font | ||||||
| 
 | 
 | ||||||
| Hi. I'm a simple test to see if this Maven build is working. If you see me in a nice PDF, then it means everything is [red]#working#. | 
 | ||||||
|  | = Generating book with AsciiDoctorj | ||||||
|  | Baeldung | ||||||
|  | 
 | ||||||
|  | [abstract] | ||||||
|  | This is the actual content. | ||||||
|  | 
 | ||||||
|  | == First Section | ||||||
|  | 
 | ||||||
|  | This is first section of the book where you can include some nice icons like icon:comment[]. | ||||||
|  | You can also create http://www.baeldung.com[links] | ||||||
|  | |||||||
							
								
								
									
										29
									
								
								asciidoctor/src/themes/custom-theme.yml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										29
									
								
								asciidoctor/src/themes/custom-theme.yml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,29 @@ | |||||||
|  | title_page: | ||||||
|  |   align: left | ||||||
|  | 
 | ||||||
|  | page: | ||||||
|  |   layout: portrait | ||||||
|  |   margin: [0.75in, 1in, 0.75in, 1in] | ||||||
|  |   size: A4 | ||||||
|  | base: | ||||||
|  |   font_color: #333333 | ||||||
|  |   line_height_length: 17 | ||||||
|  |   line_height: $base_line_height_length / $base_font_size | ||||||
|  | link: | ||||||
|  |   font_color: #009900 | ||||||
|  | 
 | ||||||
|  | header: | ||||||
|  |   height: 0.5in | ||||||
|  |   line_height: 1 | ||||||
|  |   recto_content: | ||||||
|  |     center: '{document-title}' | ||||||
|  |   verso_content: | ||||||
|  |     center: '{document-title}' | ||||||
|  | 
 | ||||||
|  | footer: | ||||||
|  |   height: 0.5in | ||||||
|  |   line_height: 1 | ||||||
|  |   recto_content: | ||||||
|  |     right: '{chapter-title} | *{page-number}*' | ||||||
|  |   verso_content: | ||||||
|  |     left: '*{page-number}* | {chapter-title}' | ||||||
							
								
								
									
										32
									
								
								aws/pom.xml
									
									
									
									
									
								
							
							
						
						
									
										32
									
								
								aws/pom.xml
									
									
									
									
									
								
							| @ -18,9 +18,41 @@ | |||||||
|         <aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version> |         <aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version> | ||||||
|         <aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version> |         <aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version> | ||||||
|         <gson.version>2.8.0</gson.version> |         <gson.version>2.8.0</gson.version> | ||||||
|  |         <aws-java-sdk.version>1.11.154</aws-java-sdk.version> | ||||||
|  |         <junit.version>4.12</junit.version> | ||||||
|  |         <mockito-core.version>2.8.9</mockito-core.version> | ||||||
|  |         <assertj-core.version>3.8.0</assertj-core.version> | ||||||
|     </properties> |     </properties> | ||||||
| 
 | 
 | ||||||
|     <dependencies> |     <dependencies> | ||||||
|  |      | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>com.amazonaws</groupId> | ||||||
|  |             <artifactId>aws-java-sdk</artifactId> | ||||||
|  |             <version>${aws-java-sdk.version}</version> | ||||||
|  |         </dependency> | ||||||
|  |          | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>junit</groupId> | ||||||
|  |             <artifactId>junit</artifactId> | ||||||
|  |             <version>${junit.version}</version> | ||||||
|  |             <scope>test</scope> | ||||||
|  |         </dependency> | ||||||
|  |          | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.mockito</groupId> | ||||||
|  |             <artifactId>mockito-core</artifactId> | ||||||
|  |             <version>${mockito-core.version}</version> | ||||||
|  |             <scope>test</scope> | ||||||
|  |         </dependency> | ||||||
|  |          | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.assertj</groupId> | ||||||
|  |             <artifactId>assertj-core</artifactId> | ||||||
|  |             <version>${assertj-core.version}</version> | ||||||
|  |             <scope>test</scope> | ||||||
|  |         </dependency> | ||||||
|  |      | ||||||
|         <dependency> |         <dependency> | ||||||
|             <groupId>com.amazonaws</groupId> |             <groupId>com.amazonaws</groupId> | ||||||
|             <artifactId>aws-lambda-java-core</artifactId> |             <artifactId>aws-lambda-java-core</artifactId> | ||||||
|  | |||||||
							
								
								
									
										87
									
								
								aws/src/main/java/com/baeldung/s3/AWSS3Service.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										87
									
								
								aws/src/main/java/com/baeldung/s3/AWSS3Service.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,87 @@ | |||||||
|  | package com.baeldung.s3; | ||||||
|  | 
 | ||||||
|  | import java.io.File; | ||||||
|  | import java.util.List; | ||||||
|  | 
 | ||||||
|  | import com.amazonaws.services.s3.AmazonS3; | ||||||
|  | import com.amazonaws.services.s3.AmazonS3Client; | ||||||
|  | import com.amazonaws.services.s3.model.Bucket; | ||||||
|  | import com.amazonaws.services.s3.model.CopyObjectResult; | ||||||
|  | import com.amazonaws.services.s3.model.DeleteObjectsRequest; | ||||||
|  | import com.amazonaws.services.s3.model.DeleteObjectsResult; | ||||||
|  | import com.amazonaws.services.s3.model.ObjectListing; | ||||||
|  | import com.amazonaws.services.s3.model.PutObjectResult; | ||||||
|  | import com.amazonaws.services.s3.model.S3Object; | ||||||
|  | 
 | ||||||
|  | public class AWSS3Service { | ||||||
|  |     private final AmazonS3 s3client; | ||||||
|  | 
 | ||||||
|  |     public AWSS3Service() {  | ||||||
|  |         this(new AmazonS3Client() { | ||||||
|  |         });  | ||||||
|  |     }  | ||||||
|  |      | ||||||
|  |     public AWSS3Service(AmazonS3 s3client) { | ||||||
|  |         this.s3client = s3client; | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     //is bucket exist? | ||||||
|  |     public boolean doesBucketExist(String bucketName) {  | ||||||
|  |         return s3client.doesBucketExist(bucketName);  | ||||||
|  |     }  | ||||||
|  |      | ||||||
|  |     //create a bucket | ||||||
|  |     public Bucket createBucket(String bucketName) {  | ||||||
|  |         return s3client.createBucket(bucketName);  | ||||||
|  |     }  | ||||||
|  | 
 | ||||||
|  |     //list all buckets | ||||||
|  |     public List<Bucket> listBuckets() {  | ||||||
|  |         return s3client.listBuckets();  | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     //delete a bucket | ||||||
|  |     public void deleteBucket(String bucketName) {  | ||||||
|  |         s3client.deleteBucket(bucketName);  | ||||||
|  |     }   | ||||||
|  |      | ||||||
|  |     //uploading object | ||||||
|  |     public PutObjectResult putObject(String bucketName, String key, File file) { | ||||||
|  |         return s3client.putObject(bucketName, key, file); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     //listing objects | ||||||
|  |     public ObjectListing listObjects(String bucketName) { | ||||||
|  |         return s3client.listObjects(bucketName); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     //get an object | ||||||
|  |     public S3Object getObject(String bucketName, String objectKey) { | ||||||
|  |         return s3client.getObject(bucketName, objectKey); | ||||||
|  |     }  | ||||||
|  |      | ||||||
|  |     //copying an object | ||||||
|  |     public CopyObjectResult copyObject( | ||||||
|  |       String sourceBucketName, | ||||||
|  |       String sourceKey, | ||||||
|  |       String destinationBucketName, | ||||||
|  |       String destinationKey | ||||||
|  |     ) { | ||||||
|  |         return s3client.copyObject( | ||||||
|  |           sourceBucketName,  | ||||||
|  |           sourceKey,  | ||||||
|  |           destinationBucketName,  | ||||||
|  |           destinationKey | ||||||
|  |         ); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     //deleting an object | ||||||
|  |     public void deleteObject(String bucketName, String objectKey) { | ||||||
|  |         s3client.deleteObject(bucketName, objectKey); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     //deleting multiple Objects | ||||||
|  |     public DeleteObjectsResult deleteObjects(DeleteObjectsRequest delObjReq) { | ||||||
|  |         return s3client.deleteObjects(delObjReq); | ||||||
|  |     } | ||||||
|  | } | ||||||
							
								
								
									
										101
									
								
								aws/src/main/java/com/baeldung/s3/S3Application.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										101
									
								
								aws/src/main/java/com/baeldung/s3/S3Application.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,101 @@ | |||||||
|  | package com.baeldung.s3; | ||||||
|  | 
 | ||||||
|  | import java.io.File; | ||||||
|  | import java.io.IOException; | ||||||
|  | 
 | ||||||
|  | import org.apache.commons.io.FileUtils; | ||||||
|  | 
 | ||||||
|  | import com.amazonaws.auth.AWSCredentials; | ||||||
|  | import com.amazonaws.auth.AWSStaticCredentialsProvider; | ||||||
|  | import com.amazonaws.auth.BasicAWSCredentials; | ||||||
|  | import com.amazonaws.regions.Regions; | ||||||
|  | import com.amazonaws.services.s3.AmazonS3; | ||||||
|  | import com.amazonaws.services.s3.AmazonS3ClientBuilder; | ||||||
|  | import com.amazonaws.services.s3.model.Bucket; | ||||||
|  | import com.amazonaws.services.s3.model.DeleteObjectsRequest; | ||||||
|  | import com.amazonaws.services.s3.model.ObjectListing; | ||||||
|  | import com.amazonaws.services.s3.model.S3Object; | ||||||
|  | import com.amazonaws.services.s3.model.S3ObjectInputStream; | ||||||
|  | import com.amazonaws.services.s3.model.S3ObjectSummary; | ||||||
|  | 
 | ||||||
|  | public class S3Application { | ||||||
|  | 
 | ||||||
|  |     private static final AWSCredentials credentials; | ||||||
|  |     private static String bucketName;   | ||||||
|  | 
 | ||||||
|  |     static { | ||||||
|  |         //put your accesskey and secretkey here | ||||||
|  |         credentials = new BasicAWSCredentials( | ||||||
|  |           "<AWS accesskey>",  | ||||||
|  |           "<AWS secretkey>" | ||||||
|  |         ); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     public static void main(String[] args) throws IOException { | ||||||
|  |         //set-up the client | ||||||
|  |         AmazonS3 s3client = AmazonS3ClientBuilder | ||||||
|  |           .standard() | ||||||
|  |           .withCredentials(new AWSStaticCredentialsProvider(credentials)) | ||||||
|  |           .withRegion(Regions.US_EAST_2) | ||||||
|  |           .build(); | ||||||
|  |          | ||||||
|  |         AWSS3Service awsService = new AWSS3Service(s3client); | ||||||
|  | 
 | ||||||
|  |         bucketName = "baeldung-bucket"; | ||||||
|  | 
 | ||||||
|  |         //creating a bucket | ||||||
|  |         if(awsService.doesBucketExist(bucketName)) { | ||||||
|  |             System.out.println("Bucket name is not available." | ||||||
|  |               + " Try again with a different Bucket name."); | ||||||
|  |             return; | ||||||
|  |         } | ||||||
|  |         awsService.createBucket(bucketName); | ||||||
|  |          | ||||||
|  |         //list all the buckets | ||||||
|  |         for(Bucket s : awsService.listBuckets() ) { | ||||||
|  |             System.out.println(s.getName()); | ||||||
|  |         } | ||||||
|  |          | ||||||
|  |         //deleting bucket | ||||||
|  |         awsService.deleteBucket("baeldung-bucket-test2"); | ||||||
|  |          | ||||||
|  |         //uploading object | ||||||
|  |         awsService.putObject( | ||||||
|  |           bucketName,  | ||||||
|  |           "Document/hello.txt", | ||||||
|  |           new File("/Users/user/Document/hello.txt") | ||||||
|  |         ); | ||||||
|  | 
 | ||||||
|  |         //listing objects | ||||||
|  |         ObjectListing objectListing = awsService.listObjects(bucketName); | ||||||
|  |         for(S3ObjectSummary os : objectListing.getObjectSummaries()) { | ||||||
|  |             System.out.println(os.getKey()); | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|  |         //downloading an object | ||||||
|  |         S3Object s3object = awsService.getObject(bucketName, "Document/hello.txt"); | ||||||
|  |         S3ObjectInputStream inputStream = s3object.getObjectContent(); | ||||||
|  |         FileUtils.copyInputStreamToFile(inputStream, new File("/Users/user/Desktop/hello.txt")); | ||||||
|  |          | ||||||
|  |         //copying an object | ||||||
|  |         awsService.copyObject( | ||||||
|  |           "baeldung-bucket",  | ||||||
|  |           "picture/pic.png",  | ||||||
|  |           "baeldung-bucket2",  | ||||||
|  |           "Document/picture.png" | ||||||
|  |         ); | ||||||
|  |          | ||||||
|  |         //deleting an object | ||||||
|  |         awsService.deleteObject(bucketName, "Document/hello.txt"); | ||||||
|  | 
 | ||||||
|  |         //deleting multiple objects | ||||||
|  |         String objkeyArr[] = { | ||||||
|  |           "Document/hello2.txt",  | ||||||
|  |           "Document/picture.png" | ||||||
|  |         }; | ||||||
|  |          | ||||||
|  |         DeleteObjectsRequest delObjReq = new DeleteObjectsRequest("baeldung-bucket") | ||||||
|  |           .withKeys(objkeyArr); | ||||||
|  |         awsService.deleteObjects(delObjReq); | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,113 @@ | |||||||
|  | package com.baeldung.s3; | ||||||
|  | 
 | ||||||
|  | import static org.assertj.core.api.Assertions.assertThat; | ||||||
|  | import static org.mockito.ArgumentMatchers.any; | ||||||
|  | import static org.mockito.ArgumentMatchers.anyString; | ||||||
|  | import static org.mockito.Mockito.mock; | ||||||
|  | import static org.mockito.Mockito.verify; | ||||||
|  | import static org.mockito.Mockito.when; | ||||||
|  | 
 | ||||||
|  | import java.io.File; | ||||||
|  | 
 | ||||||
|  | import org.junit.Before; | ||||||
|  | import org.junit.Test; | ||||||
|  | 
 | ||||||
|  | import com.amazonaws.services.s3.AmazonS3; | ||||||
|  | import com.amazonaws.services.s3.model.CopyObjectResult; | ||||||
|  | import com.amazonaws.services.s3.model.DeleteObjectsRequest; | ||||||
|  | import com.amazonaws.services.s3.model.DeleteObjectsResult; | ||||||
|  | import com.amazonaws.services.s3.model.PutObjectResult;  | ||||||
|  | 
 | ||||||
|  | public class AWSS3ServiceIntegrationTest { | ||||||
|  | 
 | ||||||
|  |     private static final String BUCKET_NAME = "bucket_name";  | ||||||
|  |     private static final String KEY_NAME = "key_name";  | ||||||
|  |     private static final String BUCKET_NAME2 = "bucket_name2";  | ||||||
|  |     private static final String KEY_NAME2 = "key_name2";  | ||||||
|  |   | ||||||
|  |     private AmazonS3 s3;  | ||||||
|  |     private AWSS3Service service;  | ||||||
|  |   | ||||||
|  |     @Before  | ||||||
|  |     public void setUp() {  | ||||||
|  |         s3 = mock(AmazonS3.class);  | ||||||
|  |         service = new AWSS3Service(s3);  | ||||||
|  |     }  | ||||||
|  |   | ||||||
|  |     @Test  | ||||||
|  |     public void whenInitializingAWSS3Service_thenNotNull() {  | ||||||
|  |         assertThat(new AWSS3Service()).isNotNull();  | ||||||
|  |     }  | ||||||
|  |      | ||||||
|  |     @Test  | ||||||
|  |     public void whenVerifyingIfS3BucketExist_thenCorrect() {  | ||||||
|  |         service.doesBucketExist(BUCKET_NAME);  | ||||||
|  |         verify(s3).doesBucketExist(BUCKET_NAME);  | ||||||
|  |     }  | ||||||
|  |   | ||||||
|  |     @Test  | ||||||
|  |     public void whenVerifyingCreationOfS3Bucket_thenCorrect() {  | ||||||
|  |         service.createBucket(BUCKET_NAME);  | ||||||
|  |         verify(s3).createBucket(BUCKET_NAME);  | ||||||
|  |     }  | ||||||
|  |   | ||||||
|  |     @Test  | ||||||
|  |     public void whenVerifyingListBuckets_thenCorrect() {  | ||||||
|  |         service.listBuckets();  | ||||||
|  |         verify(s3).listBuckets();  | ||||||
|  |     }  | ||||||
|  | 
 | ||||||
|  |     @Test  | ||||||
|  |     public void whenDeletingBucket_thenCorrect() {  | ||||||
|  |         service.deleteBucket(BUCKET_NAME);  | ||||||
|  |         verify(s3).deleteBucket(BUCKET_NAME);  | ||||||
|  |     }  | ||||||
|  |      | ||||||
|  |     @Test  | ||||||
|  |     public void whenVerifyingPutObject_thenCorrect() {  | ||||||
|  |         File file = mock(File.class);  | ||||||
|  |         PutObjectResult result = mock(PutObjectResult.class);  | ||||||
|  |         when(s3.putObject(anyString(), anyString(), (File) any())).thenReturn(result);  | ||||||
|  |   | ||||||
|  |         assertThat(service.putObject(BUCKET_NAME, KEY_NAME, file)).isEqualTo(result);  | ||||||
|  |         verify(s3).putObject(BUCKET_NAME, KEY_NAME, file);  | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     @Test  | ||||||
|  |     public void whenVerifyingListObjects_thenCorrect() {  | ||||||
|  |         service.listObjects(BUCKET_NAME);  | ||||||
|  |         verify(s3).listObjects(BUCKET_NAME);  | ||||||
|  |     }  | ||||||
|  |      | ||||||
|  |     @Test  | ||||||
|  |     public void whenVerifyingGetObject_thenCorrect() {  | ||||||
|  |         service.getObject(BUCKET_NAME, KEY_NAME);  | ||||||
|  |         verify(s3).getObject(BUCKET_NAME, KEY_NAME);  | ||||||
|  |     }  | ||||||
|  |      | ||||||
|  |     @Test  | ||||||
|  |     public void whenVerifyingCopyObject_thenCorrect() {  | ||||||
|  |         CopyObjectResult result = mock(CopyObjectResult.class);  | ||||||
|  |         when(s3.copyObject(anyString(), anyString(), anyString(), anyString())).thenReturn(result);  | ||||||
|  |   | ||||||
|  |         assertThat(service.copyObject(BUCKET_NAME, KEY_NAME, BUCKET_NAME2, KEY_NAME2)).isEqualTo(result);  | ||||||
|  |         verify(s3).copyObject(BUCKET_NAME, KEY_NAME, BUCKET_NAME2, KEY_NAME2); | ||||||
|  |     }  | ||||||
|  |      | ||||||
|  |     @Test  | ||||||
|  |     public void whenVerifyingDeleteObject_thenCorrect() {  | ||||||
|  |         service.deleteObject(BUCKET_NAME, KEY_NAME);  | ||||||
|  |         verify(s3).deleteObject(BUCKET_NAME, KEY_NAME);  | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     @Test  | ||||||
|  |     public void whenVerifyingDeleteObjects_thenCorrect() {  | ||||||
|  |         DeleteObjectsRequest request = mock(DeleteObjectsRequest.class); | ||||||
|  |         DeleteObjectsResult result = mock(DeleteObjectsResult.class); | ||||||
|  |         when(s3.deleteObjects((DeleteObjectsRequest)any())).thenReturn(result);  | ||||||
|  |          | ||||||
|  |         assertThat(service.deleteObjects(request)).isEqualTo(result); | ||||||
|  |         verify(s3).deleteObjects(request);  | ||||||
|  |     } | ||||||
|  |      | ||||||
|  | } | ||||||
| @ -13,14 +13,13 @@ import org.springframework.beans.factory.annotation.Value; | |||||||
| import org.springframework.boot.SpringApplication; | import org.springframework.boot.SpringApplication; | ||||||
| import org.springframework.boot.autoconfigure.SpringBootApplication; | import org.springframework.boot.autoconfigure.SpringBootApplication; | ||||||
| import org.springframework.boot.web.servlet.ServletRegistrationBean; | import org.springframework.boot.web.servlet.ServletRegistrationBean; | ||||||
| import org.springframework.boot.web.support.SpringBootServletInitializer; |  | ||||||
| import org.springframework.context.annotation.Bean; | import org.springframework.context.annotation.Bean; | ||||||
| import org.springframework.context.annotation.ComponentScan; | import org.springframework.context.annotation.ComponentScan; | ||||||
| import org.springframework.stereotype.Component; | import org.springframework.stereotype.Component; | ||||||
| 
 | 
 | ||||||
| @SpringBootApplication | @SpringBootApplication | ||||||
| @ComponentScan(basePackages="com.baeldung.camel") | @ComponentScan(basePackages="com.baeldung.camel") | ||||||
| public class Application extends SpringBootServletInitializer { | public class Application{ | ||||||
| 
 | 
 | ||||||
|     @Value("${server.port}") |     @Value("${server.port}") | ||||||
|     String serverPort; |     String serverPort; | ||||||
| @ -62,10 +61,12 @@ public class Application extends SpringBootServletInitializer { | |||||||
|                 .bindingMode(RestBindingMode.json) |                 .bindingMode(RestBindingMode.json) | ||||||
|                 .dataFormatProperty("prettyPrint", "true"); |                 .dataFormatProperty("prettyPrint", "true"); | ||||||
| /**  | /**  | ||||||
| The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format. | The Rest DSL supports automatic binding json/xml contents to/from  | ||||||
| By default the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages. | POJOs using Camels Data Format. | ||||||
| You may want to use binding if you develop POJOs that maps to your REST services request and response types.  | By default the binding mode is off, meaning there is no automatic  | ||||||
| This allows you, as a developer, to work with the POJOs in Java code. | binding happening for incoming and outgoing messages. | ||||||
|  | You may want to use binding if you develop POJOs that maps to  | ||||||
|  | your REST services request and response types.  | ||||||
| */          | */          | ||||||
|              |              | ||||||
|             rest("/api/").description("Teste REST Service") |             rest("/api/").description("Teste REST Service") | ||||||
|  | |||||||
| @ -13,3 +13,6 @@ | |||||||
| - [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api) | - [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api) | ||||||
| - [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api) | - [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api) | ||||||
| - [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) | - [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) | ||||||
|  | - [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional) | ||||||
|  | - [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams) | ||||||
|  | - [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) | ||||||
|  | |||||||
| @ -113,6 +113,16 @@ | |||||||
| - [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep) | - [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep) | ||||||
| - [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator) | - [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator) | ||||||
| - [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer) | - [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer) | ||||||
|  | - [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers) | ||||||
|  | - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) | ||||||
|  | - [How to Round a Number to N Decimal Places in Java](http://www.baeldung.com/java-round-decimal-number) | ||||||
|  | - [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params) | ||||||
|  | - [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null) | ||||||
|  | - [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream) | ||||||
|  | - [Changing the Order in a Sum Operation Can Produce Different Results?](http://www.baeldung.com/java-floating-point-sum-order) | ||||||
|  | - [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method) | ||||||
|  | - [Iterate over a Map in Java](http://www.baeldung.com/java-iterate-map) | ||||||
|  | - [CyclicBarrier in Java](http://www.baeldung.com/java-cyclic-barrier) | ||||||
| - [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) | - [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) | ||||||
| - [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy) | - [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy) | ||||||
| - [Introduction to JDBC](http://www.baeldung.com/java-jdbc) | - [Introduction to JDBC](http://www.baeldung.com/java-jdbc) | ||||||
|  | |||||||
							
								
								
									
										39
									
								
								core-java/hashcode/pom.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										39
									
								
								core-java/hashcode/pom.xml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,39 @@ | |||||||
|  | <?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.hashcode</groupId> | ||||||
|  |     <artifactId>hashcode</artifactId> | ||||||
|  |     <version>1.0</version> | ||||||
|  |     <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>junit</groupId> | ||||||
|  |             <artifactId>junit</artifactId> | ||||||
|  |             <version>4.12</version> | ||||||
|  |             <scope>test</scope> | ||||||
|  |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.slf4j</groupId> | ||||||
|  |             <artifactId>slf4j-api</artifactId> | ||||||
|  |             <version>1.7.25</version> | ||||||
|  |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.slf4j</groupId> | ||||||
|  |             <artifactId>slf4j-simple</artifactId> | ||||||
|  |             <version>1.7.25</version> | ||||||
|  |         </dependency> | ||||||
|  |     </dependencies> | ||||||
|  | </project> | ||||||
| @ -0,0 +1,23 @@ | |||||||
|  | package com.baeldung.application; | ||||||
|  | 
 | ||||||
|  | import com.baeldung.entities.User; | ||||||
|  | import java.util.HashMap; | ||||||
|  | import java.util.Map; | ||||||
|  | 
 | ||||||
|  | public class Application { | ||||||
|  | 
 | ||||||
|  |     public static void main(String[] args) { | ||||||
|  |         Map<User, User> users = new HashMap<>(); | ||||||
|  |         User user1 = new User(1L, "John", "john@domain.com"); | ||||||
|  |         User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); | ||||||
|  |         User user3 = new User(3L, "Mary", "mary@domain.com"); | ||||||
|  | 
 | ||||||
|  |         users.put(user1, user1); | ||||||
|  |         users.put(user2, user2); | ||||||
|  |         users.put(user3, user3); | ||||||
|  | 
 | ||||||
|  |         if (users.containsKey(user1)) { | ||||||
|  |             System.out.print("User found in the collection"); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,38 @@ | |||||||
|  | package com.baeldung.entities; | ||||||
|  | 
 | ||||||
|  | import org.slf4j.Logger; | ||||||
|  | import org.slf4j.LoggerFactory; | ||||||
|  | 
 | ||||||
|  | public class User { | ||||||
|  | 
 | ||||||
|  |     private final Logger logger = LoggerFactory.getLogger(User.class); | ||||||
|  |     private long id; | ||||||
|  |     private String name; | ||||||
|  |     private String email; | ||||||
|  | 
 | ||||||
|  |     public User(long id, String name, String email) { | ||||||
|  |         this.id = id; | ||||||
|  |         this.name = name; | ||||||
|  |         this.email = email; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Override | ||||||
|  |     public boolean equals(Object o) { | ||||||
|  |         if (this == o) return true; | ||||||
|  |         if (o == null) return false; | ||||||
|  |         if (this.getClass() != o.getClass()) return false; | ||||||
|  |         User user = (User) o; | ||||||
|  |         return id != user.id && (!name.equals(user.name) && !email.equals(user.email)); | ||||||
|  |     } | ||||||
|  |     	 | ||||||
|  |     @Override | ||||||
|  |     public int hashCode() { | ||||||
|  |         int hash = 7; | ||||||
|  |         hash = 31 * hash + (int) id; | ||||||
|  |         hash = 31 * hash + (name == null ? 0 : name.hashCode()); | ||||||
|  |         hash = 31 * hash + (email == null ? 0 : email.hashCode()); | ||||||
|  |         logger.info("hashCode() method called - Computed hash: " + hash); | ||||||
|  |         return hash; | ||||||
|  |     } | ||||||
|  |     // getters and setters here | ||||||
|  | } | ||||||
| @ -0,0 +1,30 @@ | |||||||
|  | package com.baeldung.application; | ||||||
|  | 
 | ||||||
|  | import org.junit.After; | ||||||
|  | import org.junit.Before; | ||||||
|  | import org.junit.Test; | ||||||
|  | import java.io.ByteArrayOutputStream; | ||||||
|  | import java.io.PrintStream; | ||||||
|  | import static org.junit.Assert.assertEquals; | ||||||
|  | 
 | ||||||
|  | public class ApplicationTest { | ||||||
|  | 
 | ||||||
|  |     private ByteArrayOutputStream outContent; | ||||||
|  | 
 | ||||||
|  |     @Before | ||||||
|  |     public void setUpPrintStreamInstance() throws Exception { | ||||||
|  |         this.outContent = new ByteArrayOutputStream(); | ||||||
|  |         System.setOut(new PrintStream(outContent)); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @After | ||||||
|  |     public void tearDownByteArrayOutputStream() throws Exception { | ||||||
|  |         outContent = null; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void main_NoInputState_TextPrintedToConsole() throws Exception { | ||||||
|  |         Application.main(new String[]{}); | ||||||
|  |         assertEquals("User found in the collection", outContent.toString()); | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,34 @@ | |||||||
|  | package com.baeldung.entities; | ||||||
|  | 
 | ||||||
|  | import org.junit.After; | ||||||
|  | import org.junit.Assert; | ||||||
|  | import org.junit.Before; | ||||||
|  | import org.junit.Test; | ||||||
|  | 
 | ||||||
|  | public class UserTest { | ||||||
|  | 
 | ||||||
|  |     private User user; | ||||||
|  |     private User comparisonUser; | ||||||
|  | 
 | ||||||
|  |     @Before | ||||||
|  |     public void setUpUserInstances() { | ||||||
|  |         this.user = new User(1L, "test", "test@domain.com"); | ||||||
|  |         this.comparisonUser = this.user; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @After | ||||||
|  |     public void tearDownUserInstances() { | ||||||
|  |         user = null; | ||||||
|  |         comparisonUser = null; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void equals_EqualUserInstance_TrueAssertion(){ | ||||||
|  |         Assert.assertTrue(user.equals(comparisonUser)); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void hashCode_UserHash_TrueAssertion() { | ||||||
|  |         Assert.assertEquals(1792276941, user.hashCode()); | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -382,7 +382,7 @@ | |||||||
|         </profile> |         </profile> | ||||||
|     </profiles> |     </profiles> | ||||||
| 
 | 
 | ||||||
|     <properties> |     <properties>    	 | ||||||
|         <!-- marshalling --> |         <!-- marshalling --> | ||||||
|         <jackson.version>2.8.5</jackson.version> |         <jackson.version>2.8.5</jackson.version> | ||||||
| 
 | 
 | ||||||
| @ -408,7 +408,7 @@ | |||||||
|         <!-- testing --> |         <!-- testing --> | ||||||
|         <org.hamcrest.version>1.3</org.hamcrest.version> |         <org.hamcrest.version>1.3</org.hamcrest.version> | ||||||
|         <junit.version>4.12</junit.version> |         <junit.version>4.12</junit.version> | ||||||
|         <mockito.version>1.10.19</mockito.version> |         <mockito.version>2.8.9</mockito.version> | ||||||
|         <assertj.version>3.6.1</assertj.version> |         <assertj.version>3.6.1</assertj.version> | ||||||
|         <avaitility.version>1.7.0</avaitility.version> |         <avaitility.version>1.7.0</avaitility.version> | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -0,0 +1,34 @@ | |||||||
|  | package com.baeldung.concurrent.Scheduledexecutorservice; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.Executors; | ||||||
|  | import java.util.concurrent.Future; | ||||||
|  | import java.util.concurrent.ScheduledExecutorService; | ||||||
|  | import java.util.concurrent.ScheduledFuture; | ||||||
|  | import java.util.concurrent.TimeUnit; | ||||||
|  | 
 | ||||||
|  | public class ScheduledExecutorServiceDemo { | ||||||
|  | 
 | ||||||
|  | 	public void execute() { | ||||||
|  | 		ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); | ||||||
|  | 
 | ||||||
|  | 		ScheduledFuture<?> scheduledFuture = executorService.schedule(() -> { | ||||||
|  | 			// Task | ||||||
|  | 		}, 1, TimeUnit.SECONDS); | ||||||
|  | 
 | ||||||
|  | 		executorService.scheduleAtFixedRate(() -> { | ||||||
|  | 			// Task | ||||||
|  | 		}, 1, 10, TimeUnit.SECONDS); | ||||||
|  | 
 | ||||||
|  | 		executorService.scheduleWithFixedDelay(() -> { | ||||||
|  | 			// Task | ||||||
|  | 		}, 1, 10, TimeUnit.SECONDS); | ||||||
|  | 
 | ||||||
|  | 		Future<String> future = executorService.schedule(() -> { | ||||||
|  | 			// Task | ||||||
|  | 			return "Hellow world"; | ||||||
|  | 		}, 1, TimeUnit.SECONDS); | ||||||
|  | 
 | ||||||
|  | 		executorService.shutdown(); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,13 @@ | |||||||
|  | package com.baeldung.concurrent.atomic; | ||||||
|  | 
 | ||||||
|  | public class SafeCounterWithLock { | ||||||
|  |     private volatile int counter; | ||||||
|  |      | ||||||
|  |     public int getValue() { | ||||||
|  |         return counter; | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     public synchronized void increment() { | ||||||
|  |         counter++; | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,21 @@ | |||||||
|  | package com.baeldung.concurrent.atomic; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.atomic.AtomicInteger; | ||||||
|  | 
 | ||||||
|  | public class SafeCounterWithoutLock { | ||||||
|  |     private final AtomicInteger counter = new AtomicInteger(0); | ||||||
|  |      | ||||||
|  |     public int getValue() { | ||||||
|  |         return counter.get(); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     public void increment() { | ||||||
|  |         while(true) { | ||||||
|  |             int existingValue = getValue(); | ||||||
|  |             int newValue = existingValue + 1; | ||||||
|  |             if(counter.compareAndSet(existingValue, newValue)) { | ||||||
|  |                 return; | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,13 @@ | |||||||
|  | package com.baeldung.concurrent.atomic; | ||||||
|  | 
 | ||||||
|  | public class UnsafeCounter { | ||||||
|  |     int counter; | ||||||
|  |      | ||||||
|  |     public int getValue() { | ||||||
|  |         return counter; | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     public void increment() { | ||||||
|  |         counter++; | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,24 @@ | |||||||
|  | package com.baeldung.concurrent.cyclicbarrier; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.CyclicBarrier; | ||||||
|  | 
 | ||||||
|  | public class CyclicBarrierExample { | ||||||
|  | 
 | ||||||
|  |     public void start() { | ||||||
|  |         CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> { | ||||||
|  |             // Task | ||||||
|  |             System.out.println("All previous tasks are completed"); | ||||||
|  |         }); | ||||||
|  | 
 | ||||||
|  |         Thread t1 = new Thread(new Task(cyclicBarrier), "T1"); | ||||||
|  |         Thread t2 = new Thread(new Task(cyclicBarrier), "T2"); | ||||||
|  |         Thread t3 = new Thread(new Task(cyclicBarrier), "T3"); | ||||||
|  | 
 | ||||||
|  |         if (!cyclicBarrier.isBroken()) { | ||||||
|  |             t1.start(); | ||||||
|  |             t2.start(); | ||||||
|  |             t3.start(); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | } | ||||||
|  | 
 | ||||||
| @ -0,0 +1,24 @@ | |||||||
|  | package com.baeldung.concurrent.cyclicbarrier; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.BrokenBarrierException; | ||||||
|  | import java.util.concurrent.CyclicBarrier; | ||||||
|  | 
 | ||||||
|  | public class Task implements Runnable { | ||||||
|  | 
 | ||||||
|  |     private CyclicBarrier barrier; | ||||||
|  | 
 | ||||||
|  |     public Task(CyclicBarrier barrier) { | ||||||
|  |         this.barrier = barrier; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Override | ||||||
|  |     public void run() { | ||||||
|  |         try { | ||||||
|  |             System.out.println("Thread : " + Thread.currentThread().getName() + " is waiting"); | ||||||
|  |             barrier.await(); | ||||||
|  |             System.out.println("Thread : " + Thread.currentThread().getName() + " is released"); | ||||||
|  |         } catch (InterruptedException | BrokenBarrierException e) { | ||||||
|  |             e.printStackTrace(); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,14 @@ | |||||||
|  | package com.baeldung.concurrent.executor; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.Executor; | ||||||
|  | 
 | ||||||
|  | public class ExecutorDemo { | ||||||
|  | 
 | ||||||
|  | 	public void execute() { | ||||||
|  | 		Executor executor = new Invoker(); | ||||||
|  | 		executor.execute(()->{ | ||||||
|  | 			// task to be performed | ||||||
|  | 		}); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,12 @@ | |||||||
|  | package com.baeldung.concurrent.executor; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.Executor; | ||||||
|  | 
 | ||||||
|  | public class Invoker implements Executor { | ||||||
|  | 
 | ||||||
|  | 	@Override | ||||||
|  | 	public void execute(Runnable r) { | ||||||
|  | 		r.run(); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,27 @@ | |||||||
|  | package com.baeldung.concurrent.executorservice; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.ExecutorService; | ||||||
|  | import java.util.concurrent.Executors; | ||||||
|  | import java.util.concurrent.TimeUnit; | ||||||
|  | 
 | ||||||
|  | public class ExecutorServiceDemo { | ||||||
|  | 
 | ||||||
|  | 	ExecutorService executor = Executors.newFixedThreadPool(10); | ||||||
|  | 
 | ||||||
|  | 	public void execute() { | ||||||
|  | 
 | ||||||
|  | 		executor.submit(() -> { | ||||||
|  | 			new Task(); | ||||||
|  | 		}); | ||||||
|  | 
 | ||||||
|  | 		executor.shutdown(); | ||||||
|  | 		executor.shutdownNow(); | ||||||
|  | 		try { | ||||||
|  | 			executor.awaitTermination(20l, TimeUnit.NANOSECONDS); | ||||||
|  | 		} catch (InterruptedException e) { | ||||||
|  | 			e.printStackTrace(); | ||||||
|  | 		} | ||||||
|  | 
 | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,10 @@ | |||||||
|  | package com.baeldung.concurrent.executorservice; | ||||||
|  | 
 | ||||||
|  | public class Task implements Runnable { | ||||||
|  | 
 | ||||||
|  | 	@Override | ||||||
|  | 	public void run() { | ||||||
|  | 		// task details | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,44 @@ | |||||||
|  | package com.baeldung.concurrent.future; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.ExecutionException; | ||||||
|  | import java.util.concurrent.ExecutorService; | ||||||
|  | import java.util.concurrent.Executors; | ||||||
|  | import java.util.concurrent.Future; | ||||||
|  | import java.util.concurrent.TimeUnit; | ||||||
|  | import java.util.concurrent.TimeoutException; | ||||||
|  | 
 | ||||||
|  | public class FutureDemo { | ||||||
|  | 
 | ||||||
|  | 	public String invoke() { | ||||||
|  | 
 | ||||||
|  | 		String str = null; | ||||||
|  | 
 | ||||||
|  | 		ExecutorService executorService = Executors.newFixedThreadPool(10); | ||||||
|  | 
 | ||||||
|  | 		Future<String> future = executorService.submit(() -> { | ||||||
|  | 			// Task | ||||||
|  | 			Thread.sleep(10000l); | ||||||
|  | 			return "Hellow world"; | ||||||
|  | 		}); | ||||||
|  | 
 | ||||||
|  | 		future.cancel(false); | ||||||
|  | 
 | ||||||
|  | 		try { | ||||||
|  | 			future.get(20, TimeUnit.SECONDS); | ||||||
|  | 		} catch (InterruptedException | ExecutionException | TimeoutException e1) { | ||||||
|  | 			e1.printStackTrace(); | ||||||
|  | 		} | ||||||
|  | 
 | ||||||
|  | 		if (future.isDone() && !future.isCancelled()) { | ||||||
|  | 			try { | ||||||
|  | 				str = future.get(); | ||||||
|  | 			} catch (InterruptedException | ExecutionException e) { | ||||||
|  | 				e.printStackTrace(); | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  | 
 | ||||||
|  | 		return str; | ||||||
|  | 
 | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,22 @@ | |||||||
|  | package com.baeldung.concurrent.semaphore; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.Semaphore; | ||||||
|  | 
 | ||||||
|  | public class SemaPhoreDemo { | ||||||
|  | 
 | ||||||
|  | 	static Semaphore semaphore = new Semaphore(10); | ||||||
|  | 	 | ||||||
|  | 	public void execute() throws InterruptedException { | ||||||
|  | 
 | ||||||
|  | 		System.out.println("Available permit : " + semaphore.availablePermits()); | ||||||
|  | 		System.out.println("Number of threads waiting to acquire: " + semaphore.getQueueLength()); | ||||||
|  | 
 | ||||||
|  | 		if (semaphore.tryAcquire()) { | ||||||
|  | 			semaphore.acquire(); | ||||||
|  | 			// perform some critical operations | ||||||
|  | 			semaphore.release(); | ||||||
|  | 		} | ||||||
|  | 
 | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,23 @@ | |||||||
|  | package com.baeldung.concurrent.threadfactory; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.ThreadFactory; | ||||||
|  | 
 | ||||||
|  | public class BaeldungThreadFactory implements ThreadFactory { | ||||||
|  | 
 | ||||||
|  | 	private int threadId; | ||||||
|  | 	private String name; | ||||||
|  | 
 | ||||||
|  | 	public BaeldungThreadFactory(String name) { | ||||||
|  | 		threadId = 1; | ||||||
|  | 		this.name = name; | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	@Override | ||||||
|  | 	public Thread newThread(Runnable r) { | ||||||
|  | 		Thread t = new Thread(r, name + "-Thread_" + threadId); | ||||||
|  | 		System.out.println("created new thread with id : " + threadId + " and name : " + t.getName()); | ||||||
|  | 		threadId++; | ||||||
|  | 		return t; | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,13 @@ | |||||||
|  | package com.baeldung.concurrent.threadfactory; | ||||||
|  | 
 | ||||||
|  | public class Demo { | ||||||
|  | 
 | ||||||
|  | 	public void execute() { | ||||||
|  | 		BaeldungThreadFactory factory = new BaeldungThreadFactory("BaeldungThreadFactory"); | ||||||
|  | 		for (int i = 0; i < 10; i++) { | ||||||
|  | 			Thread t = factory.newThread(new Task()); | ||||||
|  | 			t.start(); | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,10 @@ | |||||||
|  | package com.baeldung.concurrent.threadfactory; | ||||||
|  | 
 | ||||||
|  | public class Task implements Runnable { | ||||||
|  | 
 | ||||||
|  | 	@Override | ||||||
|  | 	public void run() { | ||||||
|  | 		// task details | ||||||
|  | 	} | ||||||
|  | 	 | ||||||
|  | } | ||||||
| @ -4,12 +4,12 @@ import java.io.Serializable; | |||||||
| 
 | 
 | ||||||
| public class AppleProduct implements Serializable { | public class AppleProduct implements Serializable { | ||||||
| 
 | 
 | ||||||
|      private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated) |     private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated) | ||||||
| //    private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated) |     // private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated) | ||||||
| 
 | 
 | ||||||
|     public String headphonePort; |     public String headphonePort; | ||||||
|     public String thunderboltPort; |     public String thunderboltPort; | ||||||
|     public String lighteningPort; |     public String lightningPort; | ||||||
| 
 | 
 | ||||||
|     public String getHeadphonePort() { |     public String getHeadphonePort() { | ||||||
|         return headphonePort; |         return headphonePort; | ||||||
| @ -23,4 +23,8 @@ public class AppleProduct implements Serializable { | |||||||
|         return serialVersionUID; |         return serialVersionUID; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|  |     public String getLightningPort() { | ||||||
|  |         return lightningPort; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
| } | } | ||||||
| @ -9,11 +9,12 @@ public class DeserializationUtility { | |||||||
| 
 | 
 | ||||||
|     public static void main(String[] args) throws ClassNotFoundException, IOException { |     public static void main(String[] args) throws ClassNotFoundException, IOException { | ||||||
| 
 | 
 | ||||||
|         String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; |         String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; | ||||||
|         System.out.println("Deserializing AppleProduct..."); |         System.out.println("Deserializing AppleProduct..."); | ||||||
|         AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj); |         AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj); | ||||||
|         System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort()); |         System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort()); | ||||||
|         System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort()); |         System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort()); | ||||||
|  |         System.out.println("LightningPort port of AppleProduct:" + deserializedObj.getLightningPort()); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException { |     public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException { | ||||||
|  | |||||||
| @ -13,6 +13,7 @@ public class SerializationUtility { | |||||||
|         AppleProduct macBook = new AppleProduct(); |         AppleProduct macBook = new AppleProduct(); | ||||||
|         macBook.headphonePort = "headphonePort2020"; |         macBook.headphonePort = "headphonePort2020"; | ||||||
|         macBook.thunderboltPort = "thunderboltPort2020"; |         macBook.thunderboltPort = "thunderboltPort2020"; | ||||||
|  |         macBook.lightningPort = "lightningPort2020"; | ||||||
| 
 | 
 | ||||||
|         String serializedObj = serializeObjectToString(macBook); |         String serializedObj = serializeObjectToString(macBook); | ||||||
|         System.out.println("Serialized AppleProduct object to string:"); |         System.out.println("Serialized AppleProduct object to string:"); | ||||||
|  | |||||||
| @ -10,14 +10,13 @@ public class CustomTemporalAdjuster implements TemporalAdjuster { | |||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Temporal adjustInto(Temporal temporal) { |     public Temporal adjustInto(Temporal temporal) { | ||||||
|         DayOfWeek dayOfWeek = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK)); |         switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) { | ||||||
|         int daysToAdd; |             case FRIDAY: | ||||||
|         if (dayOfWeek == DayOfWeek.FRIDAY) |                 return temporal.plus(3, ChronoUnit.DAYS); | ||||||
|             daysToAdd = 3; |             case SATURDAY: | ||||||
|         else if (dayOfWeek == DayOfWeek.SATURDAY) |                 return temporal.plus(2, ChronoUnit.DAYS); | ||||||
|             daysToAdd = 2; |             default: | ||||||
|         else |                 return temporal.plus(1, ChronoUnit.DAYS); | ||||||
|             daysToAdd = 1; |         } | ||||||
|         return temporal.plus(daysToAdd, ChronoUnit.DAYS); |  | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  | |||||||
| @ -4,7 +4,7 @@ public class Rectangle extends Shape { | |||||||
|     private double width; |     private double width; | ||||||
|     private double length; |     private double length; | ||||||
| 
 | 
 | ||||||
|     public Rectangle(double width, double length) { |     Rectangle(double width, double length) { | ||||||
|         this.width = width; |         this.width = width; | ||||||
|         this.length = length; |         this.length = length; | ||||||
|     } |     } | ||||||
|  | |||||||
| @ -1,11 +1,10 @@ | |||||||
| package org.baeldung.executable; | package org.baeldung.executable; | ||||||
| 
 | 
 | ||||||
| import javax.swing.JOptionPane; | import javax.swing.*; | ||||||
| 
 | 
 | ||||||
| public class ExecutableMavenJar { | public class ExecutableMavenJar { | ||||||
| 
 | 
 | ||||||
|     public static void main(String[] args) { |     public static void main(String[] args) { | ||||||
|         JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1); |         JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1); | ||||||
|     } |     } | ||||||
| 
 |  | ||||||
| } | } | ||||||
|  | |||||||
| @ -0,0 +1,38 @@ | |||||||
|  | package com.baeldung.concurrent.atomic; | ||||||
|  | 
 | ||||||
|  | import static org.junit.Assert.assertEquals; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.ExecutorService; | ||||||
|  | import java.util.concurrent.Executors; | ||||||
|  | import java.util.concurrent.TimeUnit; | ||||||
|  | import java.util.stream.IntStream; | ||||||
|  | 
 | ||||||
|  | import org.junit.Test; | ||||||
|  | 
 | ||||||
|  | public class ThreadSafeCounterTest { | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException { | ||||||
|  |         ExecutorService service = Executors.newFixedThreadPool(3); | ||||||
|  |         SafeCounterWithLock safeCounter = new SafeCounterWithLock(); | ||||||
|  | 
 | ||||||
|  |         IntStream.range(0, 1000) | ||||||
|  |           .forEach(count -> service.submit(safeCounter::increment)); | ||||||
|  |         service.awaitTermination(100, TimeUnit.MILLISECONDS); | ||||||
|  | 
 | ||||||
|  |         assertEquals(1000, safeCounter.getValue()); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     @Test | ||||||
|  |     public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws InterruptedException { | ||||||
|  |         ExecutorService service = Executors.newFixedThreadPool(3); | ||||||
|  |         SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock(); | ||||||
|  | 
 | ||||||
|  |         IntStream.range(0, 1000) | ||||||
|  |           .forEach(count -> service.submit(safeCounter::increment)); | ||||||
|  |         service.awaitTermination(100, TimeUnit.MILLISECONDS); | ||||||
|  | 
 | ||||||
|  |         assertEquals(1000, safeCounter.getValue()); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  | } | ||||||
| @ -0,0 +1,33 @@ | |||||||
|  | package com.baeldung.concurrent.atomic; | ||||||
|  | 
 | ||||||
|  | import static org.junit.Assert.assertEquals; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.ExecutorService; | ||||||
|  | import java.util.concurrent.Executors; | ||||||
|  | import java.util.concurrent.TimeUnit; | ||||||
|  | import java.util.stream.IntStream; | ||||||
|  | 
 | ||||||
|  | import org.junit.Test; | ||||||
|  | 
 | ||||||
|  | /** | ||||||
|  |  * This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling | ||||||
|  |  * the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will  | ||||||
|  |  * less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads | ||||||
|  |  * called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this | ||||||
|  |  * test from build by adding this in manual test | ||||||
|  |  */ | ||||||
|  | public class ThreadUnsafeCounterManualTest { | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException { | ||||||
|  |         ExecutorService service = Executors.newFixedThreadPool(3); | ||||||
|  |         UnsafeCounter unsafeCounter = new UnsafeCounter(); | ||||||
|  | 
 | ||||||
|  |         IntStream.range(0, 1000) | ||||||
|  |           .forEach(count -> service.submit(unsafeCounter::increment)); | ||||||
|  |         service.awaitTermination(100, TimeUnit.MILLISECONDS); | ||||||
|  | 
 | ||||||
|  |         assertEquals(1000, unsafeCounter.getValue()); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  | } | ||||||
| @ -12,7 +12,7 @@ import org.junit.Test; | |||||||
| 
 | 
 | ||||||
| public class DeserializationUnitTest { | public class DeserializationUnitTest { | ||||||
| 
 | 
 | ||||||
|     private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; |     private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAdMuxAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA"; | ||||||
| 
 | 
 | ||||||
|     private static long userDefinedSerialVersionUID = 1234567L; |     private static long userDefinedSerialVersionUID = 1234567L; | ||||||
| 
 | 
 | ||||||
| @ -25,20 +25,22 @@ public class DeserializationUnitTest { | |||||||
|     public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException { |     public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException { | ||||||
| 
 | 
 | ||||||
|         assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID()); |         assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID()); | ||||||
|          | 
 | ||||||
|         AppleProduct macBook = new AppleProduct(); |         AppleProduct macBook = new AppleProduct(); | ||||||
|         macBook.headphonePort = "headphonePort2020"; |         macBook.headphonePort = "headphonePort2020"; | ||||||
|         macBook.thunderboltPort = "thunderboltPort2020"; |         macBook.thunderboltPort = "thunderboltPort2020"; | ||||||
|          |         macBook.lightningPort = "lightningPort2020"; | ||||||
|  | 
 | ||||||
|         // serializes the "AppleProduct" object |         // serializes the "AppleProduct" object | ||||||
|         String serializedProduct = SerializationUtility.serializeObjectToString(macBook); |         String serializedProduct = SerializationUtility.serializeObjectToString(macBook); | ||||||
| 
 | 
 | ||||||
|         // deserializes the "AppleProduct" object |         // deserializes the "AppleProduct" object | ||||||
|         AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct); |         AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct); | ||||||
|       | 
 | ||||||
|         assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort)); |         assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort)); | ||||||
|         assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort)); |         assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort)); | ||||||
|      |         assertTrue(deserializedProduct.lightningPort.equalsIgnoreCase(macBook.lightningPort)); | ||||||
|  | 
 | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     /** |     /** | ||||||
| @ -59,7 +61,6 @@ public class DeserializationUnitTest { | |||||||
|     public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException { |     public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException { | ||||||
| 
 | 
 | ||||||
|         assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID()); |         assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID()); | ||||||
|          |  | ||||||
|         // attempts to deserialize the "AppleProduct" object |         // attempts to deserialize the "AppleProduct" object | ||||||
|         DeserializationUtility.deSerializeObjectFromString(serializedObj); |         DeserializationUtility.deSerializeObjectFromString(serializedObj); | ||||||
|     } |     } | ||||||
|  | |||||||
| @ -63,6 +63,6 @@ public class MappedByteBufferUnitTest { | |||||||
| 
 | 
 | ||||||
|     private Path getFileURIFromResources(String fileName) throws Exception { |     private Path getFileURIFromResources(String fileName) throws Exception { | ||||||
|         ClassLoader classLoader = getClass().getClassLoader(); |         ClassLoader classLoader = getClass().getClassLoader(); | ||||||
|         return Paths.get(classLoader.getResource(fileName).getPath()); |         return Paths.get(classLoader.getResource(fileName).toURI()); | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  | |||||||
| @ -179,7 +179,7 @@ public class JavaMoneyUnitTest { | |||||||
|         MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder |         MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder | ||||||
|           .of(Locale.US) |           .of(Locale.US) | ||||||
|           .set(CurrencyStyle.NAME) |           .set(CurrencyStyle.NAME) | ||||||
|           .set("pattern", "00000.00 ¤") |           .set("pattern", "00000.00 ¤") | ||||||
|           .build()); |           .build()); | ||||||
|         String customFormatted = customFormat.format(oneDollar); |         String customFormatted = customFormat.format(oneDollar); | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -1,34 +1,34 @@ | |||||||
| package com.baeldung.temporaladjusters; | package com.baeldung.temporaladjusters; | ||||||
| 
 | 
 | ||||||
| import java.time.DayOfWeek; | import com.baeldung.temporaladjuster.CustomTemporalAdjuster; | ||||||
| import java.time.LocalDate; |  | ||||||
| import java.time.Period; |  | ||||||
| import java.time.temporal.TemporalAdjuster; |  | ||||||
| import java.time.temporal.TemporalAdjusters; |  | ||||||
| 
 |  | ||||||
| import org.junit.Assert; | import org.junit.Assert; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
| import com.baeldung.temporaladjuster.CustomTemporalAdjuster; | import java.time.LocalDate; | ||||||
|  | import java.time.Period; | ||||||
|  | import java.time.temporal.TemporalAdjuster; | ||||||
|  | 
 | ||||||
|  | import static org.junit.Assert.assertEquals; | ||||||
| 
 | 
 | ||||||
| public class CustomTemporalAdjusterTest { | public class CustomTemporalAdjusterTest { | ||||||
| 
 | 
 | ||||||
|  |     private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster(); | ||||||
|  | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenAdjustAndImplementInterface_thenNextWorkingDay() { |     public void whenAdjustAndImplementInterface_thenNextWorkingDay() { | ||||||
|         LocalDate localDate = LocalDate.of(2017, 07, 8); |         LocalDate localDate = LocalDate.of(2017, 07, 8); | ||||||
|         CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster(); |         CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster(); | ||||||
|         LocalDate nextWorkingDay = localDate.with(temporalAdjuster); |         LocalDate nextWorkingDay = localDate.with(temporalAdjuster); | ||||||
| 
 | 
 | ||||||
|         Assert.assertEquals("2017-07-10", nextWorkingDay.toString()); |         assertEquals("2017-07-10", nextWorkingDay.toString()); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenAdjust_thenNextWorkingDay() { |     public void whenAdjust_thenNextWorkingDay() { | ||||||
|         LocalDate localDate = LocalDate.of(2017, 07, 8); |         LocalDate localDate = LocalDate.of(2017, 07, 8); | ||||||
|         TemporalAdjuster temporalAdjuster = NEXT_WORKING_DAY; |         LocalDate date = localDate.with(NEXT_WORKING_DAY); | ||||||
|         LocalDate date = localDate.with(temporalAdjuster); |  | ||||||
| 
 | 
 | ||||||
|         Assert.assertEquals("2017-07-10", date.toString()); |         assertEquals("2017-07-10", date.toString()); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
| @ -39,18 +39,6 @@ public class CustomTemporalAdjusterTest { | |||||||
| 
 | 
 | ||||||
|         String fourteenDaysAfterDate = "2017-07-22"; |         String fourteenDaysAfterDate = "2017-07-22"; | ||||||
| 
 | 
 | ||||||
|         Assert.assertEquals(fourteenDaysAfterDate, result.toString()); |         assertEquals(fourteenDaysAfterDate, result.toString()); | ||||||
|     } |     } | ||||||
| 
 | } | ||||||
|     static TemporalAdjuster NEXT_WORKING_DAY = TemporalAdjusters.ofDateAdjuster(date -> { |  | ||||||
|         DayOfWeek dayOfWeek = date.getDayOfWeek(); |  | ||||||
|         int daysToAdd; |  | ||||||
|         if (dayOfWeek == DayOfWeek.FRIDAY) |  | ||||||
|             daysToAdd = 3; |  | ||||||
|         else if (dayOfWeek == DayOfWeek.SATURDAY) |  | ||||||
|             daysToAdd = 2; |  | ||||||
|         else |  | ||||||
|             daysToAdd = 1; |  | ||||||
|         return date.plusDays(daysToAdd); |  | ||||||
|     }); |  | ||||||
| } |  | ||||||
| @ -11,6 +11,7 @@ import java.io.FileInputStream; | |||||||
| import java.io.FileReader; | import java.io.FileReader; | ||||||
| import java.io.IOException; | import java.io.IOException; | ||||||
| import java.io.InputStream; | import java.io.InputStream; | ||||||
|  | import java.util.Locale; | ||||||
| import java.util.Scanner; | import java.util.Scanner; | ||||||
| 
 | 
 | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| @ -105,6 +106,7 @@ public class JavaScannerUnitTest { | |||||||
|     public void whenScanString_thenCorrect() throws IOException { |     public void whenScanString_thenCorrect() throws IOException { | ||||||
|         final String input = "Hello 1 F 3.5"; |         final String input = "Hello 1 F 3.5"; | ||||||
|         final Scanner scanner = new Scanner(input); |         final Scanner scanner = new Scanner(input); | ||||||
|  |         scanner.useLocale(Locale.US); | ||||||
| 
 | 
 | ||||||
|         assertEquals("Hello", scanner.next()); |         assertEquals("Hello", scanner.next()); | ||||||
|         assertEquals(1, scanner.nextInt()); |         assertEquals(1, scanner.nextInt()); | ||||||
|  | |||||||
| @ -1,3 +1,4 @@ | |||||||
| ## Relevant articles: | ## Relevant articles: | ||||||
| 
 | 
 | ||||||
| - [Guide to EJB Set-up](http://www.baeldung.com/ejb-intro) | - [Guide to EJB Set-up](http://www.baeldung.com/ejb-intro) | ||||||
|  | - [Java EE Session Beans](http://www.baeldung.com/ejb-session-beans) | ||||||
|  | |||||||
| @ -1,12 +1,9 @@ | |||||||
| <?xml version="1.0" encoding="UTF-8"?> | <?xml version="1.0" encoding="UTF-8"?> | ||||||
| <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | ||||||
|     xmlns="http://maven.apache.org/POM/4.0.0" |  | ||||||
|     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |  | ||||||
|     <modelVersion>4.0.0</modelVersion> |     <modelVersion>4.0.0</modelVersion> | ||||||
| 
 | 
 | ||||||
|     <groupId>com.baeldung.feign</groupId> |     <groupId>com.baeldung.feign</groupId> | ||||||
|     <artifactId>feign-client</artifactId> |     <artifactId>feign-client</artifactId> | ||||||
|     <version>1.0.0-SNAPSHOT</version> |  | ||||||
| 
 | 
 | ||||||
|     <parent> |     <parent> | ||||||
|         <groupId>com.baeldung</groupId> |         <groupId>com.baeldung</groupId> | ||||||
|  | |||||||
| @ -28,3 +28,4 @@ | |||||||
| - [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map) | - [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map) | ||||||
| - [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue) | - [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue) | ||||||
| - [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math) | - [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math) | ||||||
|  | - [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter) | ||||||
|  | |||||||
| @ -4,8 +4,7 @@ | |||||||
|          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |          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> |     <modelVersion>4.0.0</modelVersion> | ||||||
| 
 | 
 | ||||||
|     <groupId>com.baeldung.guava</groupId> |     <artifactId>guava21</artifactId> | ||||||
|     <artifactId>tutorial</artifactId> |  | ||||||
|     <version>1.0-SNAPSHOT</version> |     <version>1.0-SNAPSHOT</version> | ||||||
| 
 | 
 | ||||||
|     <parent> |     <parent> | ||||||
| @ -15,12 +14,17 @@ | |||||||
|      </parent> |      </parent> | ||||||
| 
 | 
 | ||||||
|     <dependencies> |     <dependencies> | ||||||
|         <!-- https://mvnrepository.com/artifact/com.google.guava/guava --> |  | ||||||
|         <dependency> |         <dependency> | ||||||
|             <groupId>com.google.guava</groupId> |             <groupId>com.google.guava</groupId> | ||||||
|             <artifactId>guava</artifactId> |             <artifactId>guava</artifactId> | ||||||
|             <version>21.0</version> |             <version>21.0</version> | ||||||
|         </dependency> |         </dependency> | ||||||
|  | 
 | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.jooq</groupId> | ||||||
|  |             <artifactId>jool</artifactId> | ||||||
|  |             <version>0.9.12</version> | ||||||
|  |         </dependency> | ||||||
|     </dependencies> |     </dependencies> | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -1,4 +1,4 @@ | |||||||
| package com.baeldung.zip; | package com.baeldung.guava.zip; | ||||||
| 
 | 
 | ||||||
| import com.google.common.collect.Streams; | import com.google.common.collect.Streams; | ||||||
| import org.jooq.lambda.Seq; | import org.jooq.lambda.Seq; | ||||||
| @ -15,9 +15,9 @@ import static org.junit.Assert.assertEquals; | |||||||
| 
 | 
 | ||||||
| public class ZipCollectionTest { | public class ZipCollectionTest { | ||||||
| 
 | 
 | ||||||
|     List<String> names; |     private List<String> names; | ||||||
|     List<Integer> ages; |     private List<Integer> ages; | ||||||
|     List<String> expectedOutput; |     private List<String> expectedOutput; | ||||||
| 
 | 
 | ||||||
|     @Before |     @Before | ||||||
|     public void setUp() throws Exception { |     public void setUp() throws Exception { | ||||||
| @ -1,3 +1,5 @@ | |||||||
|  | package com.baeldung.guava.tutorial; | ||||||
|  | 
 | ||||||
| import com.google.common.util.concurrent.AtomicLongMap; | import com.google.common.util.concurrent.AtomicLongMap; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
| @ -1,3 +1,5 @@ | |||||||
|  | package com.baeldung.guava.tutorial; | ||||||
|  | 
 | ||||||
| import com.google.common.collect.Comparators; | import com.google.common.collect.Comparators; | ||||||
| import org.junit.Assert; | import org.junit.Assert; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| @ -1,21 +1,33 @@ | |||||||
|  | package com.baeldung.guava.tutorial; | ||||||
|  | 
 | ||||||
| import com.google.common.collect.Streams; | import com.google.common.collect.Streams; | ||||||
| import org.junit.Assert; |  | ||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
| import java.util.*; | import java.util.Arrays; | ||||||
|  | import java.util.Iterator; | ||||||
|  | import java.util.List; | ||||||
|  | import java.util.Optional; | ||||||
|  | import java.util.OptionalDouble; | ||||||
|  | import java.util.OptionalInt; | ||||||
|  | import java.util.OptionalLong; | ||||||
|  | import java.util.stream.Collectors; | ||||||
| import java.util.stream.DoubleStream; | import java.util.stream.DoubleStream; | ||||||
| import java.util.stream.IntStream; | import java.util.stream.IntStream; | ||||||
| import java.util.stream.LongStream; | import java.util.stream.LongStream; | ||||||
| import java.util.stream.Stream; | import java.util.stream.Stream; | ||||||
| 
 | 
 | ||||||
|  | import static com.baeldung.guava.tutorial.StreamUtility.assertStreamEquals; | ||||||
|  | import static org.junit.Assert.assertEquals; | ||||||
|  | import static org.junit.Assert.assertNotNull; | ||||||
|  | 
 | ||||||
| public class GuavaStreamsUnitTest { | public class GuavaStreamsUnitTest { | ||||||
| 
 | 
 | ||||||
|     List<Integer> numbers; |     private List<Integer> numbers; | ||||||
| 
 | 
 | ||||||
|     @Before |     @Before | ||||||
|     public void setUp() { |     public void setUp() { | ||||||
|         numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20); |         numbers = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList()); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
| @ -24,17 +36,17 @@ public class GuavaStreamsUnitTest { | |||||||
|         Stream streamFromCollection = Streams.stream(numbers); |         Stream streamFromCollection = Streams.stream(numbers); | ||||||
| 
 | 
 | ||||||
|         //Assert.assertNotNull(streamFromCollection); |         //Assert.assertNotNull(streamFromCollection); | ||||||
|         StreamUtility.assertStreamEquals(streamFromCollection, numbers.stream()); |         assertStreamEquals(streamFromCollection, numbers.stream()); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void createStreamsWithIterable() { |     public void createStreamsWithIterable() { | ||||||
|         Iterable<Integer> numbersIterable = (Iterable<Integer>) numbers; |         Iterable<Integer> numbersIterable = numbers; | ||||||
| 
 | 
 | ||||||
|         Stream streamFromIterable = Streams.stream(numbersIterable); |         Stream streamFromIterable = Streams.stream(numbersIterable); | ||||||
| 
 | 
 | ||||||
|         Assert.assertNotNull(streamFromIterable); |         assertNotNull(streamFromIterable); | ||||||
|         StreamUtility.assertStreamEquals(streamFromIterable, numbers.stream()); |         assertStreamEquals(streamFromIterable, numbers.stream()); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
| @ -43,8 +55,8 @@ public class GuavaStreamsUnitTest { | |||||||
| 
 | 
 | ||||||
|         Stream streamFromIterator = Streams.stream(numbersIterator); |         Stream streamFromIterator = Streams.stream(numbersIterator); | ||||||
| 
 | 
 | ||||||
|         Assert.assertNotNull(streamFromIterator); |         assertNotNull(streamFromIterator); | ||||||
|         StreamUtility.assertStreamEquals(streamFromIterator, numbers.stream()); |         assertStreamEquals(streamFromIterator, numbers.stream()); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
| @ -52,8 +64,8 @@ public class GuavaStreamsUnitTest { | |||||||
| 
 | 
 | ||||||
|         Stream streamFromOptional = Streams.stream(Optional.of(1)); |         Stream streamFromOptional = Streams.stream(Optional.of(1)); | ||||||
| 
 | 
 | ||||||
|         Assert.assertNotNull(streamFromOptional); |         assertNotNull(streamFromOptional); | ||||||
|         Assert.assertEquals(streamFromOptional.count(), 1); |         assertEquals(streamFromOptional.count(), 1); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
| @ -61,8 +73,8 @@ public class GuavaStreamsUnitTest { | |||||||
| 
 | 
 | ||||||
|         LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1)); |         LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1)); | ||||||
| 
 | 
 | ||||||
|         Assert.assertNotNull(streamFromOptionalLong); |         assertNotNull(streamFromOptionalLong); | ||||||
|         Assert.assertEquals(streamFromOptionalLong.count(), 1); |         assertEquals(streamFromOptionalLong.count(), 1); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
| @ -71,7 +83,7 @@ public class GuavaStreamsUnitTest { | |||||||
|         IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1)); |         IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1)); | ||||||
| 
 | 
 | ||||||
|         //Assert.assertNotNull(streamFromOptionalInt); |         //Assert.assertNotNull(streamFromOptionalInt); | ||||||
|         Assert.assertEquals(streamFromOptionalInt.count(), 1); |         assertEquals(streamFromOptionalInt.count(), 1); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
| @ -80,63 +92,54 @@ public class GuavaStreamsUnitTest { | |||||||
|         DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0)); |         DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0)); | ||||||
| 
 | 
 | ||||||
|         //Assert.assertNotNull(streamFromOptionalDouble); |         //Assert.assertNotNull(streamFromOptionalDouble); | ||||||
|         Assert.assertEquals(streamFromOptionalDouble.count(), 1); |         assertEquals(streamFromOptionalDouble.count(), 1); | ||||||
| 
 | 
 | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void concatStreamsOfSameType() { |     public void concatStreamsOfSameType() { | ||||||
|         Stream oddNumbers = Arrays |         List<Integer> oddNumbers = Arrays | ||||||
|           .asList(1, 3, 5, 7, 9, 11, 13, 15, 17, 19) |           .asList(1, 3, 5, 7, 9, 11, 13, 15, 17, 19); | ||||||
|           .stream(); |         List<Integer> evenNumbers = Arrays | ||||||
|         Stream evenNumbers = Arrays |           .asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20); | ||||||
|           .asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20) |  | ||||||
|           .stream(); |  | ||||||
| 
 | 
 | ||||||
|         Stream combinedStreams = Streams.concat(oddNumbers, evenNumbers); |         Stream<Integer> combinedStreams = Streams.concat(oddNumbers.stream(), evenNumbers.stream()); | ||||||
| 
 | 
 | ||||||
|         //Assert.assertNotNull(combinedStreams); |         //Assert.assertNotNull(combinedStreams); | ||||||
|         StreamUtility.assertStreamEquals(combinedStreams, Stream.concat(oddNumbers, evenNumbers)); |         assertStreamEquals(combinedStreams, Stream.concat(oddNumbers.stream(), evenNumbers.stream())); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void concatStreamsOfTypeLongStream() { |     public void concatStreamsOfTypeLongStream() { | ||||||
|         LongStream firstTwenty = LongStream.range(1, 20); |         LongStream combinedStreams = Streams.concat(LongStream.range(1, 21), LongStream.range(21, 40)); | ||||||
|         LongStream nextTwenty = LongStream.range(21, 40); |  | ||||||
| 
 | 
 | ||||||
|         LongStream combinedStreams = Streams.concat(firstTwenty, nextTwenty); |         assertNotNull(combinedStreams); | ||||||
| 
 |         assertStreamEquals(combinedStreams, LongStream.range(1, 40)); | ||||||
|         Assert.assertNotNull(combinedStreams); |  | ||||||
|         StreamUtility.assertStreamEquals(combinedStreams, LongStream.concat(firstTwenty, nextTwenty)); |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void concatStreamsOfTypeIntStream() { |     public void concatStreamsOfTypeIntStream() { | ||||||
|         IntStream firstTwenty = IntStream.range(1, 20); |         IntStream combinedStreams = Streams.concat(IntStream.range(1, 20), IntStream.range(21, 40)); | ||||||
|         IntStream nextTwenty = IntStream.range(21, 40); |  | ||||||
| 
 | 
 | ||||||
|         IntStream combinedStreams = Streams.concat(firstTwenty, nextTwenty); |         assertNotNull(combinedStreams); | ||||||
| 
 |         assertStreamEquals(combinedStreams, IntStream.concat(IntStream.range(1, 20), IntStream.range(21, 40))); | ||||||
|         Assert.assertNotNull(combinedStreams); |  | ||||||
|         StreamUtility.assertStreamEquals(combinedStreams, IntStream.concat(firstTwenty, nextTwenty)); |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void findLastOfStream() { |     public void findLastOfStream() { | ||||||
|         Optional<Integer> lastElement = Streams.findLast(numbers.stream()); |         Optional<Integer> lastElement = Streams.findLast(numbers.stream()); | ||||||
| 
 | 
 | ||||||
|         Assert.assertNotNull(lastElement.get()); |         assertEquals(lastElement.get(), numbers.get(19)); | ||||||
|         Assert.assertEquals(lastElement.get(), numbers.get(20)); |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void mapWithIndexTest() { |     public void mapWithIndexTest() { | ||||||
|         Stream stringSream = Stream.of("a", "b", "c"); |         Stream<String> stringStream = Stream.of("a", "b", "c"); | ||||||
| 
 | 
 | ||||||
|         Stream<String> mappedStream = Streams.mapWithIndex(stringSream, (str, index) -> str + ":" + index); |         Stream<String> mappedStream = Streams.mapWithIndex(stringStream, (str, index) -> str + ":" + index); | ||||||
| 
 | 
 | ||||||
|         //Assert.assertNotNull(mappedStream); |         //Assert.assertNotNull(mappedStream); | ||||||
|         Assert.assertEquals(mappedStream |         assertEquals(mappedStream | ||||||
|           .findFirst() |           .findFirst() | ||||||
|           .get(), "a:0"); |           .get(), "a:0"); | ||||||
| 
 | 
 | ||||||
| @ -144,12 +147,12 @@ public class GuavaStreamsUnitTest { | |||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void streamsZipTest() { |     public void streamsZipTest() { | ||||||
|         Stream stringSream = Stream.of("a", "b", "c"); |         Stream<String> stringSream = Stream.of("a", "b", "c"); | ||||||
|         Stream intStream = Stream.of(1, 2, 3); |         Stream<Integer> intStream = Stream.of(1, 2, 3); | ||||||
|         Stream<String> mappedStream = Streams.zip(stringSream, intStream, (str, index) -> str + ":" + index); |         Stream<String> mappedStream = Streams.zip(stringSream, intStream, (str, index) -> str + ":" + index); | ||||||
| 
 | 
 | ||||||
|         //Assert.assertNotNull(mappedStream); |         //Assert.assertNotNull(mappedStream); | ||||||
|         Assert.assertEquals(mappedStream |         assertEquals(mappedStream | ||||||
|           .findFirst() |           .findFirst() | ||||||
|           .get(), "a:1"); |           .get(), "a:1"); | ||||||
| 
 | 
 | ||||||
| @ -1,3 +1,5 @@ | |||||||
|  | package com.baeldung.guava.tutorial; | ||||||
|  | 
 | ||||||
| import com.google.common.collect.Interner; | import com.google.common.collect.Interner; | ||||||
| import com.google.common.collect.Interners; | import com.google.common.collect.Interners; | ||||||
| import org.junit.Assert; | import org.junit.Assert; | ||||||
| @ -1,3 +1,5 @@ | |||||||
|  | package com.baeldung.guava.tutorial; | ||||||
|  | 
 | ||||||
| import com.google.common.util.concurrent.Monitor; | import com.google.common.util.concurrent.Monitor; | ||||||
| import org.junit.Assert; | import org.junit.Assert; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| @ -1,3 +1,5 @@ | |||||||
|  | package com.baeldung.guava.tutorial; | ||||||
|  | 
 | ||||||
| import com.google.common.collect.MoreCollectors; | import com.google.common.collect.MoreCollectors; | ||||||
| import org.junit.Assert; | import org.junit.Assert; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| @ -1,3 +1,5 @@ | |||||||
|  | package com.baeldung.guava.tutorial; | ||||||
|  | 
 | ||||||
| import org.junit.Assert; | import org.junit.Assert; | ||||||
| 
 | 
 | ||||||
| import java.util.Iterator; | import java.util.Iterator; | ||||||
| @ -147,7 +147,7 @@ | |||||||
|         <wiremock.version>2.5.1</wiremock.version> |         <wiremock.version>2.5.1</wiremock.version> | ||||||
| 
 | 
 | ||||||
|         <httpcore.version>4.4.5</httpcore.version> |         <httpcore.version>4.4.5</httpcore.version> | ||||||
|         <httpclient.version>4.5.2</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 --> |         <httpclient.version>4.5.3</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 --> | ||||||
| 
 | 
 | ||||||
|         <!-- maven plugins --> |         <!-- maven plugins --> | ||||||
|         <cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version> |         <cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version> | ||||||
|  | |||||||
| @ -101,12 +101,7 @@ public class HttpAsyncClientLiveTest { | |||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception { |     public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception { | ||||||
|         final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { |         final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; | ||||||
|             @Override |  | ||||||
|             public final boolean isTrusted(final X509Certificate[] certificate, final String authType) { |  | ||||||
|                 return true; |  | ||||||
|             } |  | ||||||
|         }; |  | ||||||
|         final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); |         final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); | ||||||
| 
 | 
 | ||||||
|         final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build(); |         final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build(); | ||||||
| @ -160,7 +155,7 @@ public class HttpAsyncClientLiveTest { | |||||||
|         private final HttpContext context; |         private final HttpContext context; | ||||||
|         private final HttpGet request; |         private final HttpGet request; | ||||||
| 
 | 
 | ||||||
|         public GetThread(final CloseableHttpAsyncClient client, final HttpGet request) { |         GetThread(final CloseableHttpAsyncClient client, final HttpGet request) { | ||||||
|             this.client = client; |             this.client = client; | ||||||
|             context = HttpClientContext.create(); |             context = HttpClientContext.create(); | ||||||
|             this.request = request; |             this.request = request; | ||||||
|  | |||||||
| @ -1,11 +1,7 @@ | |||||||
| package org.baeldung.httpclient; | package org.baeldung.httpclient; | ||||||
| 
 | 
 | ||||||
| import java.io.IOException; | import com.google.common.collect.Lists; | ||||||
| import java.io.InputStream; |  | ||||||
| import java.util.List; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.Header; | import org.apache.http.Header; | ||||||
| import org.apache.http.HttpEntity; |  | ||||||
| import org.apache.http.HttpHeaders; | import org.apache.http.HttpHeaders; | ||||||
| import org.apache.http.client.ClientProtocolException; | import org.apache.http.client.ClientProtocolException; | ||||||
| import org.apache.http.client.methods.CloseableHttpResponse; | import org.apache.http.client.methods.CloseableHttpResponse; | ||||||
| @ -20,7 +16,8 @@ import org.junit.After; | |||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
| import com.google.common.collect.Lists; | import java.io.IOException; | ||||||
|  | import java.util.List; | ||||||
| 
 | 
 | ||||||
| public class HttpClientHeadersLiveTest { | public class HttpClientHeadersLiveTest { | ||||||
| 
 | 
 | ||||||
| @ -37,19 +34,7 @@ public class HttpClientHeadersLiveTest { | |||||||
| 
 | 
 | ||||||
|     @After |     @After | ||||||
|     public final void after() throws IllegalStateException, IOException { |     public final void after() throws IllegalStateException, IOException { | ||||||
|         if (response == null) { |         ResponseUtil.closeResponse(response); | ||||||
|             return; |  | ||||||
|         } |  | ||||||
| 
 |  | ||||||
|         try { |  | ||||||
|             final HttpEntity entity = response.getEntity(); |  | ||||||
|             if (entity != null) { |  | ||||||
|                 final InputStream instream = entity.getContent(); |  | ||||||
|                 instream.close(); |  | ||||||
|             } |  | ||||||
|         } finally { |  | ||||||
|             response.close(); |  | ||||||
|         } |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     // tests - headers - deprecated |     // tests - headers - deprecated | ||||||
|  | |||||||
| @ -1,22 +1,7 @@ | |||||||
| package org.baeldung.httpclient; | package org.baeldung.httpclient; | ||||||
| 
 | 
 | ||||||
| import static org.hamcrest.Matchers.equalTo; |  | ||||||
| import static org.junit.Assert.assertThat; |  | ||||||
| import static org.junit.Assert.assertTrue; |  | ||||||
| 
 |  | ||||||
| import java.io.BufferedReader; |  | ||||||
| import java.io.File; |  | ||||||
| import java.io.FileInputStream; |  | ||||||
| import java.io.IOException; |  | ||||||
| import java.io.InputStream; |  | ||||||
| import java.io.InputStreamReader; |  | ||||||
| import java.net.URL; |  | ||||||
| import java.util.logging.Level; |  | ||||||
| import java.util.logging.Logger; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.HttpEntity; | import org.apache.http.HttpEntity; | ||||||
| import org.apache.http.HttpStatus; | import org.apache.http.HttpStatus; | ||||||
| import org.apache.http.client.ClientProtocolException; |  | ||||||
| import org.apache.http.client.methods.CloseableHttpResponse; | import org.apache.http.client.methods.CloseableHttpResponse; | ||||||
| import org.apache.http.client.methods.HttpPost; | import org.apache.http.client.methods.HttpPost; | ||||||
| import org.apache.http.entity.ContentType; | import org.apache.http.entity.ContentType; | ||||||
| @ -30,6 +15,20 @@ import org.junit.After; | |||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import java.io.BufferedReader; | ||||||
|  | import java.io.File; | ||||||
|  | import java.io.FileInputStream; | ||||||
|  | import java.io.IOException; | ||||||
|  | import java.io.InputStream; | ||||||
|  | import java.io.InputStreamReader; | ||||||
|  | import java.net.URL; | ||||||
|  | import java.util.logging.Level; | ||||||
|  | import java.util.logging.Logger; | ||||||
|  | 
 | ||||||
|  | import static org.hamcrest.Matchers.equalTo; | ||||||
|  | import static org.junit.Assert.assertThat; | ||||||
|  | import static org.junit.Assert.assertTrue; | ||||||
|  | 
 | ||||||
| public class HttpClientMultipartLiveTest { | public class HttpClientMultipartLiveTest { | ||||||
| 
 | 
 | ||||||
|     // No longer available |     // No longer available | ||||||
| @ -48,7 +47,7 @@ public class HttpClientMultipartLiveTest { | |||||||
|     @Before |     @Before | ||||||
|     public final void before() { |     public final void before() { | ||||||
|         client = HttpClientBuilder.create() |         client = HttpClientBuilder.create() | ||||||
|             .build(); |           .build(); | ||||||
|         post = new HttpPost(SERVER); |         post = new HttpPost(SERVER); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
| @ -67,15 +66,7 @@ public class HttpClientMultipartLiveTest { | |||||||
|             LOGGER.log(Level.SEVERE, e.getMessage(), e); |             LOGGER.log(Level.SEVERE, e.getMessage(), e); | ||||||
|             throw e; |             throw e; | ||||||
|         } |         } | ||||||
|         try { |         ResponseUtil.closeResponse(response); | ||||||
|             final HttpEntity entity = response.getEntity(); |  | ||||||
|             if (entity != null) { |  | ||||||
|                 final InputStream instream = entity.getContent(); |  | ||||||
|                 instream.close(); |  | ||||||
|             } |  | ||||||
|         } finally { |  | ||||||
|             response.close(); |  | ||||||
|         } |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     // tests |     // tests | ||||||
| @ -83,8 +74,8 @@ public class HttpClientMultipartLiveTest { | |||||||
|     @Test |     @Test | ||||||
|     public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { |     public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { | ||||||
|         final URL url = Thread.currentThread() |         final URL url = Thread.currentThread() | ||||||
|             .getContextClassLoader() |           .getContextClassLoader() | ||||||
|             .getResource("uploads/" + TEXTFILENAME); |           .getResource("uploads/" + TEXTFILENAME); | ||||||
| 
 | 
 | ||||||
|         final File file = new File(url.getPath()); |         final File file = new File(url.getPath()); | ||||||
|         final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); |         final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); | ||||||
| @ -102,7 +93,7 @@ public class HttpClientMultipartLiveTest { | |||||||
|         response = client.execute(post); |         response = client.execute(post); | ||||||
| 
 | 
 | ||||||
|         final int statusCode = response.getStatusLine() |         final int statusCode = response.getStatusLine() | ||||||
|             .getStatusCode(); |           .getStatusCode(); | ||||||
|         final String responseString = getContent(); |         final String responseString = getContent(); | ||||||
|         final String contentTypeInHeader = getContentTypeHeader(); |         final String contentTypeInHeader = getContentTypeHeader(); | ||||||
|         assertThat(statusCode, equalTo(HttpStatus.SC_OK)); |         assertThat(statusCode, equalTo(HttpStatus.SC_OK)); | ||||||
| @ -113,10 +104,10 @@ public class HttpClientMultipartLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException { |     public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException { | ||||||
|         final URL url = Thread.currentThread() |         final URL url = Thread.currentThread() | ||||||
|             .getContextClassLoader() |           .getContextClassLoader() | ||||||
|             .getResource("uploads/" + TEXTFILENAME); |           .getResource("uploads/" + TEXTFILENAME); | ||||||
|         final File file = new File(url.getPath()); |         final File file = new File(url.getPath()); | ||||||
|         final String message = "This is a multipart post"; |         final String message = "This is a multipart post"; | ||||||
|         final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); |         final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); | ||||||
| @ -127,7 +118,7 @@ public class HttpClientMultipartLiveTest { | |||||||
|         post.setEntity(entity); |         post.setEntity(entity); | ||||||
|         response = client.execute(post); |         response = client.execute(post); | ||||||
|         final int statusCode = response.getStatusLine() |         final int statusCode = response.getStatusLine() | ||||||
|             .getStatusCode(); |           .getStatusCode(); | ||||||
|         final String responseString = getContent(); |         final String responseString = getContent(); | ||||||
|         final String contentTypeInHeader = getContentTypeHeader(); |         final String contentTypeInHeader = getContentTypeHeader(); | ||||||
|         assertThat(statusCode, equalTo(HttpStatus.SC_OK)); |         assertThat(statusCode, equalTo(HttpStatus.SC_OK)); | ||||||
| @ -138,13 +129,13 @@ public class HttpClientMultipartLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { |     public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { | ||||||
|         final URL url = Thread.currentThread() |         final URL url = Thread.currentThread() | ||||||
|             .getContextClassLoader() |           .getContextClassLoader() | ||||||
|             .getResource("uploads/" + ZIPFILENAME); |           .getResource("uploads/" + ZIPFILENAME); | ||||||
|         final URL url2 = Thread.currentThread() |         final URL url2 = Thread.currentThread() | ||||||
|             .getContextClassLoader() |           .getContextClassLoader() | ||||||
|             .getResource("uploads/" + IMAGEFILENAME); |           .getResource("uploads/" + IMAGEFILENAME); | ||||||
|         final InputStream inputStream = new FileInputStream(url.getPath()); |         final InputStream inputStream = new FileInputStream(url.getPath()); | ||||||
|         final File file = new File(url2.getPath()); |         final File file = new File(url2.getPath()); | ||||||
|         final String message = "This is a multipart post"; |         final String message = "This is a multipart post"; | ||||||
| @ -157,7 +148,7 @@ public class HttpClientMultipartLiveTest { | |||||||
|         post.setEntity(entity); |         post.setEntity(entity); | ||||||
|         response = client.execute(post); |         response = client.execute(post); | ||||||
|         final int statusCode = response.getStatusLine() |         final int statusCode = response.getStatusLine() | ||||||
|             .getStatusCode(); |           .getStatusCode(); | ||||||
|         final String responseString = getContent(); |         final String responseString = getContent(); | ||||||
|         final String contentTypeInHeader = getContentTypeHeader(); |         final String contentTypeInHeader = getContentTypeHeader(); | ||||||
|         assertThat(statusCode, equalTo(HttpStatus.SC_OK)); |         assertThat(statusCode, equalTo(HttpStatus.SC_OK)); | ||||||
| @ -169,7 +160,7 @@ public class HttpClientMultipartLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { |     public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { | ||||||
|         final String message = "This is a multipart post"; |         final String message = "This is a multipart post"; | ||||||
|         final byte[] bytes = "binary code".getBytes(); |         final byte[] bytes = "binary code".getBytes(); | ||||||
|         final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); |         final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); | ||||||
| @ -180,7 +171,7 @@ public class HttpClientMultipartLiveTest { | |||||||
|         post.setEntity(entity); |         post.setEntity(entity); | ||||||
|         response = client.execute(post); |         response = client.execute(post); | ||||||
|         final int statusCode = response.getStatusLine() |         final int statusCode = response.getStatusLine() | ||||||
|             .getStatusCode(); |           .getStatusCode(); | ||||||
|         final String responseString = getContent(); |         final String responseString = getContent(); | ||||||
|         final String contentTypeInHeader = getContentTypeHeader(); |         final String contentTypeInHeader = getContentTypeHeader(); | ||||||
|         assertThat(statusCode, equalTo(HttpStatus.SC_OK)); |         assertThat(statusCode, equalTo(HttpStatus.SC_OK)); | ||||||
| @ -192,21 +183,21 @@ public class HttpClientMultipartLiveTest { | |||||||
| 
 | 
 | ||||||
|     // UTIL |     // UTIL | ||||||
| 
 | 
 | ||||||
|     final String getContent() throws IOException { |     private String getContent() throws IOException { | ||||||
|         rd = new BufferedReader(new InputStreamReader(response.getEntity() |         rd = new BufferedReader(new InputStreamReader(response.getEntity() | ||||||
|             .getContent())); |           .getContent())); | ||||||
|         String body = ""; |         String body = ""; | ||||||
|         String content = ""; |         StringBuilder content = new StringBuilder(); | ||||||
|         while ((body = rd.readLine()) != null) { |         while ((body = rd.readLine()) != null) { | ||||||
|             content += body + "\n"; |             content.append(body).append("\n"); | ||||||
|         } |         } | ||||||
|         return content.trim(); |         return content.toString().trim(); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     final String getContentTypeHeader() throws IOException { |     private String getContentTypeHeader() throws IOException { | ||||||
|         return post.getEntity() |         return post.getEntity() | ||||||
|             .getContentType() |           .getContentType() | ||||||
|             .toString(); |           .toString(); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
| } | } | ||||||
|  | |||||||
| @ -1,20 +1,10 @@ | |||||||
| package org.baeldung.httpclient; | package org.baeldung.httpclient; | ||||||
| 
 | 
 | ||||||
| import static org.hamcrest.Matchers.equalTo; |  | ||||||
| import static org.junit.Assert.assertFalse; |  | ||||||
| import static org.junit.Assert.assertThat; |  | ||||||
| 
 |  | ||||||
| import java.io.File; |  | ||||||
| import java.io.IOException; |  | ||||||
| import java.util.ArrayList; |  | ||||||
| import java.util.List; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.HttpEntity; | import org.apache.http.HttpEntity; | ||||||
| import org.apache.http.HttpResponse; | import org.apache.http.HttpResponse; | ||||||
| import org.apache.http.NameValuePair; | import org.apache.http.NameValuePair; | ||||||
| import org.apache.http.auth.AuthenticationException; | import org.apache.http.auth.AuthenticationException; | ||||||
| import org.apache.http.auth.UsernamePasswordCredentials; | import org.apache.http.auth.UsernamePasswordCredentials; | ||||||
| import org.apache.http.client.ClientProtocolException; |  | ||||||
| import org.apache.http.client.entity.UrlEncodedFormEntity; | import org.apache.http.client.entity.UrlEncodedFormEntity; | ||||||
| import org.apache.http.client.fluent.Form; | import org.apache.http.client.fluent.Form; | ||||||
| import org.apache.http.client.fluent.Request; | import org.apache.http.client.fluent.Request; | ||||||
| @ -29,17 +19,26 @@ import org.apache.http.impl.client.HttpClients; | |||||||
| import org.apache.http.message.BasicNameValuePair; | import org.apache.http.message.BasicNameValuePair; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import java.io.File; | ||||||
|  | import java.io.IOException; | ||||||
|  | import java.util.ArrayList; | ||||||
|  | import java.util.List; | ||||||
|  | 
 | ||||||
|  | import static org.hamcrest.Matchers.equalTo; | ||||||
|  | import static org.junit.Assert.assertFalse; | ||||||
|  | import static org.junit.Assert.assertThat; | ||||||
|  | 
 | ||||||
| /* | /* | ||||||
|  * NOTE : Need module spring-rest to be running |  * NOTE : Need module spring-rest to be running | ||||||
|  */ |  */ | ||||||
| public class HttpClientPostingLiveTest { | public class HttpClientPostingLiveTest { | ||||||
|     private static final String SAMPLE_URL = "http://localhost:8080/spring-rest/users"; |     private static final String SAMPLE_URL = "http://localhost:8082/spring-rest/users"; | ||||||
|     private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; |     private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; | ||||||
|     private static final String DEFAULT_USER = "test"; |     private static final String DEFAULT_USER = "test"; | ||||||
|     private static final String DEFAULT_PASS = "test"; |     private static final String DEFAULT_PASS = "test"; | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenSendPostRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { |     public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException { | ||||||
|         final CloseableHttpClient client = HttpClients.createDefault(); |         final CloseableHttpClient client = HttpClients.createDefault(); | ||||||
|         final HttpPost httpPost = new HttpPost(SAMPLE_URL); |         final HttpPost httpPost = new HttpPost(SAMPLE_URL); | ||||||
| 
 | 
 | ||||||
| @ -54,7 +53,7 @@ public class HttpClientPostingLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException, AuthenticationException { |     public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException { | ||||||
|         final CloseableHttpClient client = HttpClients.createDefault(); |         final CloseableHttpClient client = HttpClients.createDefault(); | ||||||
|         final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION); |         final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION); | ||||||
| 
 | 
 | ||||||
| @ -68,7 +67,7 @@ public class HttpClientPostingLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { |     public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException { | ||||||
|         final CloseableHttpClient client = HttpClients.createDefault(); |         final CloseableHttpClient client = HttpClients.createDefault(); | ||||||
|         final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail"); |         final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail"); | ||||||
| 
 | 
 | ||||||
| @ -84,14 +83,14 @@ public class HttpClientPostingLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws ClientProtocolException, IOException { |     public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException { | ||||||
|         final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse(); |         final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse(); | ||||||
| 
 | 
 | ||||||
|         assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); |         assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { |     public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException { | ||||||
|         final CloseableHttpClient client = HttpClients.createDefault(); |         final CloseableHttpClient client = HttpClients.createDefault(); | ||||||
|         final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart"); |         final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart"); | ||||||
| 
 | 
 | ||||||
| @ -109,7 +108,7 @@ public class HttpClientPostingLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { |     public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException { | ||||||
|         final CloseableHttpClient client = HttpClients.createDefault(); |         final CloseableHttpClient client = HttpClients.createDefault(); | ||||||
|         final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); |         final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); | ||||||
| 
 | 
 | ||||||
| @ -125,7 +124,7 @@ public class HttpClientPostingLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { |     public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException { | ||||||
|         final CloseableHttpClient client = HttpClients.createDefault(); |         final CloseableHttpClient client = HttpClients.createDefault(); | ||||||
|         final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); |         final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); | ||||||
| 
 | 
 | ||||||
| @ -133,12 +132,7 @@ public class HttpClientPostingLiveTest { | |||||||
|         builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); |         builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); | ||||||
|         final HttpEntity multipart = builder.build(); |         final HttpEntity multipart = builder.build(); | ||||||
| 
 | 
 | ||||||
|         final ProgressEntityWrapper.ProgressListener pListener = new ProgressEntityWrapper.ProgressListener() { |         final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0); | ||||||
|             @Override |  | ||||||
|             public void progress(final float percentage) { |  | ||||||
|                 assertFalse(Float.compare(percentage, 100) > 0); |  | ||||||
|             } |  | ||||||
|         }; |  | ||||||
| 
 | 
 | ||||||
|         httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener)); |         httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener)); | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -1,13 +1,5 @@ | |||||||
| package org.baeldung.httpclient; | package org.baeldung.httpclient; | ||||||
| 
 | 
 | ||||||
| import static org.hamcrest.Matchers.equalTo; |  | ||||||
| import static org.junit.Assert.assertThat; |  | ||||||
| 
 |  | ||||||
| import java.io.IOException; |  | ||||||
| import java.io.InputStream; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.HttpEntity; |  | ||||||
| import org.apache.http.client.ClientProtocolException; |  | ||||||
| import org.apache.http.client.methods.CloseableHttpResponse; | import org.apache.http.client.methods.CloseableHttpResponse; | ||||||
| import org.apache.http.client.methods.HttpGet; | import org.apache.http.client.methods.HttpGet; | ||||||
| import org.apache.http.client.methods.HttpHead; | import org.apache.http.client.methods.HttpHead; | ||||||
| @ -21,6 +13,12 @@ import org.junit.After; | |||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import java.io.IOException; | ||||||
|  | import java.util.Arrays; | ||||||
|  | 
 | ||||||
|  | import static org.hamcrest.Matchers.equalTo; | ||||||
|  | import static org.junit.Assert.assertThat; | ||||||
|  | 
 | ||||||
| public class HttpClientRedirectLiveTest { | public class HttpClientRedirectLiveTest { | ||||||
| 
 | 
 | ||||||
|     private CloseableHttpClient instance; |     private CloseableHttpClient instance; | ||||||
| @ -34,25 +32,13 @@ public class HttpClientRedirectLiveTest { | |||||||
| 
 | 
 | ||||||
|     @After |     @After | ||||||
|     public final void after() throws IllegalStateException, IOException { |     public final void after() throws IllegalStateException, IOException { | ||||||
|         if (response == null) { |         ResponseUtil.closeResponse(response); | ||||||
|             return; |  | ||||||
|         } |  | ||||||
| 
 |  | ||||||
|         try { |  | ||||||
|             final HttpEntity entity = response.getEntity(); |  | ||||||
|             if (entity != null) { |  | ||||||
|                 final InputStream instream = entity.getContent(); |  | ||||||
|                 instream.close(); |  | ||||||
|             } |  | ||||||
|         } finally { |  | ||||||
|             response.close(); |  | ||||||
|         } |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     // tests |     // tests | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { |     public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { | ||||||
|         instance = HttpClients.custom().disableRedirectHandling().build(); |         instance = HttpClients.custom().disableRedirectHandling().build(); | ||||||
| 
 | 
 | ||||||
|         final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw"); |         final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw"); | ||||||
| @ -62,7 +48,7 @@ public class HttpClientRedirectLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { |     public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { | ||||||
|         instance = HttpClientBuilder.create().disableRedirectHandling().build(); |         instance = HttpClientBuilder.create().disableRedirectHandling().build(); | ||||||
|         response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw")); |         response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw")); | ||||||
|         assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); |         assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); | ||||||
| @ -71,26 +57,22 @@ public class HttpClientRedirectLiveTest { | |||||||
|     // redirect with POST |     // redirect with POST | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { |     public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { | ||||||
|         instance = HttpClientBuilder.create().build(); |         instance = HttpClientBuilder.create().build(); | ||||||
|         response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); |         response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); | ||||||
|         assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); |         assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { |     public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { | ||||||
|         final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() { |         final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() { | ||||||
|             /** Redirectable methods. */ |             /** Redirectable methods. */ | ||||||
|             private final String[] REDIRECT_METHODS = new String[] { HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME }; |             private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME}; | ||||||
| 
 | 
 | ||||||
|             @Override |             @Override | ||||||
|             protected boolean isRedirectable(final String method) { |             protected boolean isRedirectable(final String method) { | ||||||
|                 for (final String m : REDIRECT_METHODS) { |                 return Arrays.stream(REDIRECT_METHODS) | ||||||
|                     if (m.equalsIgnoreCase(method)) { |                   .anyMatch(m -> m.equalsIgnoreCase(method)); | ||||||
|                         return true; |  | ||||||
|                     } |  | ||||||
|                 } |  | ||||||
|                 return false; |  | ||||||
|             } |             } | ||||||
|         }).build(); |         }).build(); | ||||||
| 
 | 
 | ||||||
| @ -99,7 +81,7 @@ public class HttpClientRedirectLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { |     public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { | ||||||
|         final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build(); |         final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build(); | ||||||
| 
 | 
 | ||||||
|         response = client.execute(new HttpPost("http://t.co/I5YYd9tddw")); |         response = client.execute(new HttpPost("http://t.co/I5YYd9tddw")); | ||||||
| @ -107,7 +89,7 @@ public class HttpClientRedirectLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { |     public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { | ||||||
|         instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); |         instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); | ||||||
|         response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); |         response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); | ||||||
|         assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); |         assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); | ||||||
|  | |||||||
| @ -1,13 +1,5 @@ | |||||||
| package org.baeldung.httpclient; | package org.baeldung.httpclient; | ||||||
| 
 | 
 | ||||||
| import static org.hamcrest.Matchers.equalTo; |  | ||||||
| import static org.junit.Assert.assertThat; |  | ||||||
| 
 |  | ||||||
| import java.io.IOException; |  | ||||||
| import java.io.InputStream; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.HttpEntity; |  | ||||||
| import org.apache.http.client.ClientProtocolException; |  | ||||||
| import org.apache.http.client.config.RequestConfig; | import org.apache.http.client.config.RequestConfig; | ||||||
| import org.apache.http.client.methods.CloseableHttpResponse; | import org.apache.http.client.methods.CloseableHttpResponse; | ||||||
| import org.apache.http.client.methods.HttpGet; | import org.apache.http.client.methods.HttpGet; | ||||||
| @ -18,31 +10,24 @@ import org.apache.http.impl.client.HttpClientBuilder; | |||||||
| import org.junit.After; | import org.junit.After; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import java.io.IOException; | ||||||
|  | 
 | ||||||
|  | import static org.hamcrest.Matchers.equalTo; | ||||||
|  | import static org.junit.Assert.assertThat; | ||||||
|  | 
 | ||||||
| public class HttpClientTimeoutLiveTest { | public class HttpClientTimeoutLiveTest { | ||||||
| 
 | 
 | ||||||
|     private CloseableHttpResponse response; |     private CloseableHttpResponse response; | ||||||
| 
 | 
 | ||||||
|     @After |     @After | ||||||
|     public final void after() throws IllegalStateException, IOException { |     public final void after() throws IllegalStateException, IOException { | ||||||
|         if (response == null) { |         ResponseUtil.closeResponse(response); | ||||||
|             return; |  | ||||||
|         } |  | ||||||
| 
 |  | ||||||
|         try { |  | ||||||
|             final HttpEntity entity = response.getEntity(); |  | ||||||
|             if (entity != null) { |  | ||||||
|                 final InputStream instream = entity.getContent(); |  | ||||||
|                 instream.close(); |  | ||||||
|             } |  | ||||||
|         } finally { |  | ||||||
|             response.close(); |  | ||||||
|         } |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     // tests |     // tests | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws ClientProtocolException, IOException { |     public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws IOException { | ||||||
|         final int timeout = 2; |         final int timeout = 2; | ||||||
|         final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); |         final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); | ||||||
|         final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); |         final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); | ||||||
| @ -56,7 +41,7 @@ public class HttpClientTimeoutLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws ClientProtocolException, IOException { |     public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws IOException { | ||||||
|         final int timeout = 2; |         final int timeout = 2; | ||||||
| 
 | 
 | ||||||
|         final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build(); |         final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build(); | ||||||
| @ -70,7 +55,7 @@ public class HttpClientTimeoutLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws ClientProtocolException, IOException { |     public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws IOException { | ||||||
|         final int timeout = 5; |         final int timeout = 5; | ||||||
| 
 | 
 | ||||||
|         final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); |         final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); | ||||||
| @ -87,7 +72,7 @@ public class HttpClientTimeoutLiveTest { | |||||||
|      * This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP) |      * This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP) | ||||||
|      */ |      */ | ||||||
|     @Test(expected = HttpHostConnectException.class) |     @Test(expected = HttpHostConnectException.class) | ||||||
|     public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws ClientProtocolException, IOException { |     public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException { | ||||||
|         final int timeout = 3; |         final int timeout = 3; | ||||||
| 
 | 
 | ||||||
|         final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); |         final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); | ||||||
|  | |||||||
| @ -1,14 +1,5 @@ | |||||||
| package org.baeldung.httpclient; | package org.baeldung.httpclient; | ||||||
| 
 | 
 | ||||||
| import static org.hamcrest.CoreMatchers.equalTo; |  | ||||||
| import static org.junit.Assert.assertThat; |  | ||||||
| 
 |  | ||||||
| import java.io.IOException; |  | ||||||
| import java.security.GeneralSecurityException; |  | ||||||
| 
 |  | ||||||
| import javax.net.ssl.SSLContext; |  | ||||||
| import javax.net.ssl.SSLHandshakeException; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.HttpResponse; | import org.apache.http.HttpResponse; | ||||||
| import org.apache.http.client.methods.HttpGet; | import org.apache.http.client.methods.HttpGet; | ||||||
| import org.apache.http.conn.ClientConnectionManager; | import org.apache.http.conn.ClientConnectionManager; | ||||||
| @ -28,6 +19,14 @@ import org.apache.http.ssl.SSLContextBuilder; | |||||||
| import org.apache.http.ssl.SSLContexts; | import org.apache.http.ssl.SSLContexts; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import javax.net.ssl.SSLContext; | ||||||
|  | import javax.net.ssl.SSLHandshakeException; | ||||||
|  | import java.io.IOException; | ||||||
|  | import java.security.GeneralSecurityException; | ||||||
|  | 
 | ||||||
|  | import static org.hamcrest.CoreMatchers.equalTo; | ||||||
|  | import static org.junit.Assert.assertThat; | ||||||
|  | 
 | ||||||
| /** | /** | ||||||
|  * This test requires a localhost server over HTTPS <br> |  * This test requires a localhost server over HTTPS <br> | ||||||
|  * It should only be manually run, not part of the automated build |  * It should only be manually run, not part of the automated build | ||||||
|  | |||||||
| @ -10,7 +10,7 @@ import org.apache.http.entity.HttpEntityWrapper; | |||||||
| public class ProgressEntityWrapper extends HttpEntityWrapper { | public class ProgressEntityWrapper extends HttpEntityWrapper { | ||||||
|     private final ProgressListener listener; |     private final ProgressListener listener; | ||||||
| 
 | 
 | ||||||
|     public ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) { |     ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) { | ||||||
|         super(entity); |         super(entity); | ||||||
|         this.listener = listener; |         this.listener = listener; | ||||||
|     } |     } | ||||||
| @ -20,7 +20,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper { | |||||||
|         super.writeTo(new CountingOutputStream(outstream, listener, getContentLength())); |         super.writeTo(new CountingOutputStream(outstream, listener, getContentLength())); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public static interface ProgressListener { |     public interface ProgressListener { | ||||||
|         void progress(float percentage); |         void progress(float percentage); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
| @ -30,7 +30,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper { | |||||||
|         private long transferred; |         private long transferred; | ||||||
|         private long totalBytes; |         private long totalBytes; | ||||||
| 
 | 
 | ||||||
|         public CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) { |         CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) { | ||||||
|             super(out); |             super(out); | ||||||
|             this.listener = listener; |             this.listener = listener; | ||||||
|             transferred = 0; |             transferred = 0; | ||||||
|  | |||||||
| @ -0,0 +1,26 @@ | |||||||
|  | package org.baeldung.httpclient; | ||||||
|  | 
 | ||||||
|  | import org.apache.http.HttpEntity; | ||||||
|  | import org.apache.http.client.methods.CloseableHttpResponse; | ||||||
|  | 
 | ||||||
|  | import java.io.IOException; | ||||||
|  | 
 | ||||||
|  | public final class ResponseUtil { | ||||||
|  |     private ResponseUtil() { | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     public static void closeResponse(CloseableHttpResponse response) throws IOException { | ||||||
|  |         if (response == null) { | ||||||
|  |             return; | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|  |         try { | ||||||
|  |             final HttpEntity entity = response.getEntity(); | ||||||
|  |             if (entity != null) { | ||||||
|  |                 entity.getContent().close(); | ||||||
|  |             } | ||||||
|  |         } finally { | ||||||
|  |             response.close(); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -24,7 +24,14 @@ import org.junit.Test; | |||||||
| 
 | 
 | ||||||
| import java.io.IOException; | import java.io.IOException; | ||||||
| 
 | 
 | ||||||
| import static com.github.tomakehurst.wiremock.client.WireMock.*; | import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; | ||||||
|  | import static com.github.tomakehurst.wiremock.client.WireMock.containing; | ||||||
|  | import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; | ||||||
|  | import static com.github.tomakehurst.wiremock.client.WireMock.get; | ||||||
|  | import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; | ||||||
|  | import static com.github.tomakehurst.wiremock.client.WireMock.post; | ||||||
|  | import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; | ||||||
|  | import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; | ||||||
| import static org.junit.Assert.assertEquals; | import static org.junit.Assert.assertEquals; | ||||||
| 
 | 
 | ||||||
| public class HttpClientAdvancedConfigurationIntegrationTest { | public class HttpClientAdvancedConfigurationIntegrationTest { | ||||||
| @ -40,9 +47,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { | |||||||
|         //given |         //given | ||||||
|         String userAgent = "BaeldungAgent/1.0"; |         String userAgent = "BaeldungAgent/1.0"; | ||||||
|         serviceMock.stubFor(get(urlEqualTo("/detail")) |         serviceMock.stubFor(get(urlEqualTo("/detail")) | ||||||
|                 .withHeader("User-Agent", equalTo(userAgent)) |           .withHeader("User-Agent", equalTo(userAgent)) | ||||||
|                 .willReturn(aResponse() |           .willReturn(aResponse() | ||||||
|                         .withStatus(200))); |             .withStatus(200))); | ||||||
| 
 | 
 | ||||||
|         HttpClient httpClient = HttpClients.createDefault(); |         HttpClient httpClient = HttpClients.createDefault(); | ||||||
|         HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); |         HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); | ||||||
| @ -60,10 +67,10 @@ public class HttpClientAdvancedConfigurationIntegrationTest { | |||||||
|         //given |         //given | ||||||
|         String xmlBody = "<xml><id>1</id></xml>"; |         String xmlBody = "<xml><id>1</id></xml>"; | ||||||
|         serviceMock.stubFor(post(urlEqualTo("/person")) |         serviceMock.stubFor(post(urlEqualTo("/person")) | ||||||
|                 .withHeader("Content-Type", equalTo("application/xml")) |           .withHeader("Content-Type", equalTo("application/xml")) | ||||||
|                 .withRequestBody(equalTo(xmlBody)) |           .withRequestBody(equalTo(xmlBody)) | ||||||
|                 .willReturn(aResponse() |           .willReturn(aResponse() | ||||||
|                         .withStatus(200))); |             .withStatus(200))); | ||||||
| 
 | 
 | ||||||
|         HttpClient httpClient = HttpClients.createDefault(); |         HttpClient httpClient = HttpClients.createDefault(); | ||||||
|         HttpPost httpPost = new HttpPost("http://localhost:8089/person"); |         HttpPost httpPost = new HttpPost("http://localhost:8089/person"); | ||||||
| @ -83,17 +90,17 @@ public class HttpClientAdvancedConfigurationIntegrationTest { | |||||||
|     public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { |     public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { | ||||||
|         //given |         //given | ||||||
|         proxyMock.stubFor(get(urlMatching(".*")) |         proxyMock.stubFor(get(urlMatching(".*")) | ||||||
|                 .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); |           .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); | ||||||
| 
 | 
 | ||||||
|         serviceMock.stubFor(get(urlEqualTo("/private")) |         serviceMock.stubFor(get(urlEqualTo("/private")) | ||||||
|                 .willReturn(aResponse().withStatus(200))); |           .willReturn(aResponse().withStatus(200))); | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
|         HttpHost proxy = new HttpHost("localhost", 8090); |         HttpHost proxy = new HttpHost("localhost", 8090); | ||||||
|         DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); |         DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); | ||||||
|         HttpClient httpclient = HttpClients.custom() |         HttpClient httpclient = HttpClients.custom() | ||||||
|                 .setRoutePlanner(routePlanner) |           .setRoutePlanner(routePlanner) | ||||||
|                 .build(); |           .build(); | ||||||
| 
 | 
 | ||||||
|         //when |         //when | ||||||
|         final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); |         final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); | ||||||
| @ -109,9 +116,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { | |||||||
|     public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { |     public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { | ||||||
|         //given |         //given | ||||||
|         proxyMock.stubFor(get(urlMatching("/private")) |         proxyMock.stubFor(get(urlMatching("/private")) | ||||||
|                 .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); |           .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); | ||||||
|         serviceMock.stubFor(get(urlEqualTo("/private")) |         serviceMock.stubFor(get(urlEqualTo("/private")) | ||||||
|                 .willReturn(aResponse().withStatus(200))); |           .willReturn(aResponse().withStatus(200))); | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
|         HttpHost proxy = new HttpHost("localhost", 8090); |         HttpHost proxy = new HttpHost("localhost", 8090); | ||||||
| @ -120,7 +127,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest { | |||||||
|         // Client credentials |         // Client credentials | ||||||
|         CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); |         CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); | ||||||
|         credentialsProvider.setCredentials(new AuthScope(proxy), |         credentialsProvider.setCredentials(new AuthScope(proxy), | ||||||
|                 new UsernamePasswordCredentials("username_admin", "secret_password")); |           new UsernamePasswordCredentials("username_admin", "secret_password")); | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
|         // Create AuthCache instance |         // Create AuthCache instance | ||||||
| @ -135,9 +142,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { | |||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
|         HttpClient httpclient = HttpClients.custom() |         HttpClient httpclient = HttpClients.custom() | ||||||
|                 .setRoutePlanner(routePlanner) |           .setRoutePlanner(routePlanner) | ||||||
|                 .setDefaultCredentialsProvider(credentialsProvider) |           .setDefaultCredentialsProvider(credentialsProvider) | ||||||
|                 .build(); |           .build(); | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
|         //when |         //when | ||||||
|  | |||||||
| @ -1,13 +1,5 @@ | |||||||
| package org.baeldung.httpclient.base; | package org.baeldung.httpclient.base; | ||||||
| 
 | 
 | ||||||
| import static org.hamcrest.Matchers.equalTo; |  | ||||||
| import static org.hamcrest.Matchers.notNullValue; |  | ||||||
| import static org.junit.Assert.assertThat; |  | ||||||
| 
 |  | ||||||
| import java.io.IOException; |  | ||||||
| import java.io.InputStream; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.HttpEntity; |  | ||||||
| import org.apache.http.HttpStatus; | import org.apache.http.HttpStatus; | ||||||
| import org.apache.http.client.ClientProtocolException; | import org.apache.http.client.ClientProtocolException; | ||||||
| import org.apache.http.client.methods.CloseableHttpResponse; | import org.apache.http.client.methods.CloseableHttpResponse; | ||||||
| @ -16,10 +8,17 @@ import org.apache.http.entity.ContentType; | |||||||
| import org.apache.http.impl.client.CloseableHttpClient; | import org.apache.http.impl.client.CloseableHttpClient; | ||||||
| import org.apache.http.impl.client.HttpClientBuilder; | import org.apache.http.impl.client.HttpClientBuilder; | ||||||
| import org.apache.http.util.EntityUtils; | import org.apache.http.util.EntityUtils; | ||||||
|  | import org.baeldung.httpclient.ResponseUtil; | ||||||
| import org.junit.After; | import org.junit.After; | ||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import java.io.IOException; | ||||||
|  | 
 | ||||||
|  | import static org.hamcrest.Matchers.equalTo; | ||||||
|  | import static org.hamcrest.Matchers.notNullValue; | ||||||
|  | import static org.junit.Assert.assertThat; | ||||||
|  | 
 | ||||||
| public class HttpClientBasicLiveTest { | public class HttpClientBasicLiveTest { | ||||||
| 
 | 
 | ||||||
|     private static final String SAMPLE_URL = "http://www.github.com"; |     private static final String SAMPLE_URL = "http://www.github.com"; | ||||||
| @ -35,19 +34,7 @@ public class HttpClientBasicLiveTest { | |||||||
| 
 | 
 | ||||||
|     @After |     @After | ||||||
|     public final void after() throws IllegalStateException, IOException { |     public final void after() throws IllegalStateException, IOException { | ||||||
|         if (response == null) { |         ResponseUtil.closeResponse(response); | ||||||
|             return; |  | ||||||
|         } |  | ||||||
| 
 |  | ||||||
|         try { |  | ||||||
|             final HttpEntity entity = response.getEntity(); |  | ||||||
|             if (entity != null) { |  | ||||||
|                 final InputStream instream = entity.getContent(); |  | ||||||
|                 instream.close(); |  | ||||||
|             } |  | ||||||
|         } finally { |  | ||||||
|             response.close(); |  | ||||||
|         } |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     // tests |     // tests | ||||||
|  | |||||||
| @ -1,22 +1,20 @@ | |||||||
| package org.baeldung.httpclient.base; | package org.baeldung.httpclient.base; | ||||||
| 
 | 
 | ||||||
| import java.io.IOException; |  | ||||||
| import java.io.InputStream; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.HttpEntity; |  | ||||||
| import org.apache.http.auth.AuthenticationException; | import org.apache.http.auth.AuthenticationException; | ||||||
| import org.apache.http.auth.UsernamePasswordCredentials; | import org.apache.http.auth.UsernamePasswordCredentials; | ||||||
| import org.apache.http.client.ClientProtocolException; |  | ||||||
| import org.apache.http.client.methods.CloseableHttpResponse; | import org.apache.http.client.methods.CloseableHttpResponse; | ||||||
| import org.apache.http.client.methods.HttpPost; | import org.apache.http.client.methods.HttpPost; | ||||||
| import org.apache.http.entity.StringEntity; | import org.apache.http.entity.StringEntity; | ||||||
| import org.apache.http.impl.auth.BasicScheme; | import org.apache.http.impl.auth.BasicScheme; | ||||||
| import org.apache.http.impl.client.CloseableHttpClient; | import org.apache.http.impl.client.CloseableHttpClient; | ||||||
| import org.apache.http.impl.client.HttpClientBuilder; | import org.apache.http.impl.client.HttpClientBuilder; | ||||||
|  | import org.baeldung.httpclient.ResponseUtil; | ||||||
| import org.junit.After; | import org.junit.After; | ||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import java.io.IOException; | ||||||
|  | 
 | ||||||
| public class HttpClientBasicPostLiveTest { | public class HttpClientBasicPostLiveTest { | ||||||
| 
 | 
 | ||||||
|     private static final String SAMPLE_URL = "http://www.github.com"; |     private static final String SAMPLE_URL = "http://www.github.com"; | ||||||
| @ -32,37 +30,25 @@ public class HttpClientBasicPostLiveTest { | |||||||
| 
 | 
 | ||||||
|     @After |     @After | ||||||
|     public final void after() throws IllegalStateException, IOException { |     public final void after() throws IllegalStateException, IOException { | ||||||
|         if (response == null) { |         ResponseUtil.closeResponse(response); | ||||||
|             return; |  | ||||||
|         } |  | ||||||
| 
 |  | ||||||
|         try { |  | ||||||
|             final HttpEntity entity = response.getEntity(); |  | ||||||
|             if (entity != null) { |  | ||||||
|                 final InputStream instream = entity.getContent(); |  | ||||||
|                 instream.close(); |  | ||||||
|             } |  | ||||||
|         } finally { |  | ||||||
|             response.close(); |  | ||||||
|         } |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     // tests - non-GET |     // tests - non-GET | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void whenExecutingPostRequest_thenNoExceptions() throws ClientProtocolException, IOException { |     public final void whenExecutingPostRequest_thenNoExceptions() throws IOException { | ||||||
|         instance.execute(new HttpPost(SAMPLE_URL)); |         instance.execute(new HttpPost(SAMPLE_URL)); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException { |     public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException { | ||||||
|         final HttpPost request = new HttpPost(SAMPLE_URL); |         final HttpPost request = new HttpPost(SAMPLE_URL); | ||||||
|         request.setEntity(new StringEntity("in the body of the POST")); |         request.setEntity(new StringEntity("in the body of the POST")); | ||||||
|         instance.execute(request); |         instance.execute(request); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException, AuthenticationException { |     public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException { | ||||||
|         final HttpPost request = new HttpPost(SAMPLE_URL); |         final HttpPost request = new HttpPost(SAMPLE_URL); | ||||||
|         request.setEntity(new StringEntity("in the body of the POST")); |         request.setEntity(new StringEntity("in the body of the POST")); | ||||||
|         final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password"); |         final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password"); | ||||||
|  | |||||||
| @ -11,12 +11,12 @@ import org.apache.http.impl.client.CloseableHttpClient; | |||||||
| import org.apache.http.impl.client.HttpClientBuilder; | import org.apache.http.impl.client.HttpClientBuilder; | ||||||
| import org.apache.http.impl.client.HttpClients; | import org.apache.http.impl.client.HttpClients; | ||||||
| import org.apache.http.impl.conn.BasicHttpClientConnectionManager; | import org.apache.http.impl.conn.BasicHttpClientConnectionManager; | ||||||
|  | import org.baeldung.httpclient.ResponseUtil; | ||||||
| import org.junit.After; | import org.junit.After; | ||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
| import java.io.IOException; | import java.io.IOException; | ||||||
| import java.io.InputStream; |  | ||||||
| 
 | 
 | ||||||
| import static org.hamcrest.Matchers.emptyArray; | import static org.hamcrest.Matchers.emptyArray; | ||||||
| import static org.hamcrest.Matchers.not; | import static org.hamcrest.Matchers.not; | ||||||
| @ -37,19 +37,7 @@ public class HttpClientLiveTest { | |||||||
| 
 | 
 | ||||||
|     @After |     @After | ||||||
|     public final void after() throws IllegalStateException, IOException { |     public final void after() throws IllegalStateException, IOException { | ||||||
|         if (response == null) { |         ResponseUtil.closeResponse(response); | ||||||
|             return; |  | ||||||
|         } |  | ||||||
| 
 |  | ||||||
|         try { |  | ||||||
|             final HttpEntity entity = response.getEntity(); |  | ||||||
|             if (entity != null) { |  | ||||||
|                 final InputStream instream = entity.getContent(); |  | ||||||
|                 instream.close(); |  | ||||||
|             } |  | ||||||
|         } finally { |  | ||||||
|             response.close(); |  | ||||||
|         } |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     // tests |     // tests | ||||||
|  | |||||||
| @ -1,9 +1,5 @@ | |||||||
| package org.baeldung.httpclient.base; | package org.baeldung.httpclient.base; | ||||||
| 
 | 
 | ||||||
| import java.io.IOException; |  | ||||||
| import java.io.InputStream; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.HttpEntity; |  | ||||||
| import org.apache.http.auth.AuthScope; | import org.apache.http.auth.AuthScope; | ||||||
| import org.apache.http.auth.UsernamePasswordCredentials; | import org.apache.http.auth.UsernamePasswordCredentials; | ||||||
| import org.apache.http.client.CredentialsProvider; | import org.apache.http.client.CredentialsProvider; | ||||||
| @ -12,8 +8,11 @@ import org.apache.http.client.methods.HttpGet; | |||||||
| import org.apache.http.impl.client.BasicCredentialsProvider; | import org.apache.http.impl.client.BasicCredentialsProvider; | ||||||
| import org.apache.http.impl.client.CloseableHttpClient; | import org.apache.http.impl.client.CloseableHttpClient; | ||||||
| import org.apache.http.impl.client.HttpClientBuilder; | import org.apache.http.impl.client.HttpClientBuilder; | ||||||
|  | import org.baeldung.httpclient.ResponseUtil; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import java.io.IOException; | ||||||
|  | 
 | ||||||
| /* | /* | ||||||
|  * NOTE : Need module spring-security-rest-basic-auth to be running |  * NOTE : Need module spring-security-rest-basic-auth to be running | ||||||
|  */ |  */ | ||||||
| @ -32,15 +31,6 @@ public class HttpClientSandboxLiveTest { | |||||||
| 
 | 
 | ||||||
|         System.out.println(response.getStatusLine()); |         System.out.println(response.getStatusLine()); | ||||||
| 
 | 
 | ||||||
|         try { |         ResponseUtil.closeResponse(response); | ||||||
|             final HttpEntity entity = response.getEntity(); |  | ||||||
|             if (entity != null) { |  | ||||||
|                 // EntityUtils.consume(entity); |  | ||||||
|                 final InputStream instream = entity.getContent(); |  | ||||||
|                 instream.close(); |  | ||||||
|             } |  | ||||||
|         } finally { |  | ||||||
|             response.close(); |  | ||||||
|         } |  | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  | |||||||
| @ -1,11 +1,5 @@ | |||||||
| package org.baeldung.httpclient.conn; | package org.baeldung.httpclient.conn; | ||||||
| 
 | 
 | ||||||
| import static org.junit.Assert.assertTrue; |  | ||||||
| 
 |  | ||||||
| import java.io.IOException; |  | ||||||
| import java.util.concurrent.ExecutionException; |  | ||||||
| import java.util.concurrent.TimeUnit; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.HeaderElement; | import org.apache.http.HeaderElement; | ||||||
| import org.apache.http.HeaderElementIterator; | import org.apache.http.HeaderElementIterator; | ||||||
| import org.apache.http.HttpClientConnection; | import org.apache.http.HttpClientConnection; | ||||||
| @ -36,6 +30,12 @@ import org.junit.Before; | |||||||
| import org.junit.Ignore; | import org.junit.Ignore; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import java.io.IOException; | ||||||
|  | import java.util.concurrent.ExecutionException; | ||||||
|  | import java.util.concurrent.TimeUnit; | ||||||
|  | 
 | ||||||
|  | import static org.junit.Assert.assertTrue; | ||||||
|  | 
 | ||||||
| public class HttpClientConnectionManagementLiveTest { | public class HttpClientConnectionManagementLiveTest { | ||||||
|     private static final String SERVER1 = "http://www.petrikainulainen.net/"; |     private static final String SERVER1 = "http://www.petrikainulainen.net/"; | ||||||
|     private static final String SERVER7 = "http://www.baeldung.com/"; |     private static final String SERVER7 = "http://www.baeldung.com/"; | ||||||
| @ -129,7 +129,7 @@ public class HttpClientConnectionManagementLiveTest { | |||||||
|     @Test |     @Test | ||||||
|     // @Ignore |     // @Ignore | ||||||
|     // Example 3.2. TESTER VERSION |     // Example 3.2. TESTER VERSION | ||||||
|     /*tester*/public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { |     /*tester*/ public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { | ||||||
|         poolingConnManager = new PoolingHttpClientConnectionManager(); |         poolingConnManager = new PoolingHttpClientConnectionManager(); | ||||||
|         final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); |         final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); | ||||||
|         final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); |         final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); | ||||||
| @ -173,7 +173,7 @@ public class HttpClientConnectionManagementLiveTest { | |||||||
|     @Test |     @Test | ||||||
|     // @Ignore |     // @Ignore | ||||||
|     // 4.2 Tester Version |     // 4.2 Tester Version | ||||||
|     /*tester*/public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { |     /*tester*/ public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { | ||||||
|         poolingConnManager = new PoolingHttpClientConnectionManager(); |         poolingConnManager = new PoolingHttpClientConnectionManager(); | ||||||
|         client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); |         client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); | ||||||
|         final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); |         final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); | ||||||
| @ -266,7 +266,7 @@ public class HttpClientConnectionManagementLiveTest { | |||||||
|     @Test |     @Test | ||||||
|     // @Ignore |     // @Ignore | ||||||
|     // 6.2 TESTER VERSION |     // 6.2 TESTER VERSION | ||||||
|     /*tester*/public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { |     /*tester*/ public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { | ||||||
|         poolingConnManager = new PoolingHttpClientConnectionManager(); |         poolingConnManager = new PoolingHttpClientConnectionManager(); | ||||||
|         poolingConnManager.setDefaultMaxPerRoute(5); |         poolingConnManager.setDefaultMaxPerRoute(5); | ||||||
|         poolingConnManager.setMaxTotal(5); |         poolingConnManager.setMaxTotal(5); | ||||||
| @ -333,7 +333,7 @@ public class HttpClientConnectionManagementLiveTest { | |||||||
|     @Test |     @Test | ||||||
|     @Ignore("Very Long Running") |     @Ignore("Very Long Running") | ||||||
|     // 8.2 TESTER VERSION |     // 8.2 TESTER VERSION | ||||||
|     /*tester*/public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { |     /*tester*/ public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { | ||||||
|         poolingConnManager = new PoolingHttpClientConnectionManager(); |         poolingConnManager = new PoolingHttpClientConnectionManager(); | ||||||
|         client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); |         client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); | ||||||
|         final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager); |         final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager); | ||||||
|  | |||||||
| @ -9,7 +9,7 @@ public class IdleConnectionMonitorThread extends Thread { | |||||||
|     private final HttpClientConnectionManager connMgr; |     private final HttpClientConnectionManager connMgr; | ||||||
|     private volatile boolean shutdown; |     private volatile boolean shutdown; | ||||||
| 
 | 
 | ||||||
|     public IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { |     IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { | ||||||
|         super(); |         super(); | ||||||
|         this.connMgr = connMgr; |         this.connMgr = connMgr; | ||||||
|     } |     } | ||||||
| @ -31,7 +31,7 @@ public class IdleConnectionMonitorThread extends Thread { | |||||||
|         } |         } | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public final void shutdown() { |     private void shutdown() { | ||||||
|         shutdown = true; |         shutdown = true; | ||||||
|         synchronized (this) { |         synchronized (this) { | ||||||
|             notifyAll(); |             notifyAll(); | ||||||
|  | |||||||
| @ -18,23 +18,23 @@ public class MultiHttpClientConnThread extends Thread { | |||||||
|     private final HttpGet get; |     private final HttpGet get; | ||||||
| 
 | 
 | ||||||
|     private PoolingHttpClientConnectionManager connManager; |     private PoolingHttpClientConnectionManager connManager; | ||||||
|     public int leasedConn; |     private int leasedConn; | ||||||
| 
 | 
 | ||||||
|     public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { |     MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { | ||||||
|         this.client = client; |         this.client = client; | ||||||
|         this.get = get; |         this.get = get; | ||||||
|         this.connManager = connManager; |         this.connManager = connManager; | ||||||
|         leasedConn = 0; |         leasedConn = 0; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { |     MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { | ||||||
|         this.client = client; |         this.client = client; | ||||||
|         this.get = get; |         this.get = get; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     // API |     // API | ||||||
| 
 | 
 | ||||||
|     public final int getLeasedConn() { |     final int getLeasedConn() { | ||||||
|         return leasedConn; |         return leasedConn; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
| @ -61,8 +61,6 @@ public class MultiHttpClientConnThread extends Thread { | |||||||
|             } |             } | ||||||
| 
 | 
 | ||||||
|             EntityUtils.consume(response.getEntity()); |             EntityUtils.consume(response.getEntity()); | ||||||
|         } catch (final ClientProtocolException ex) { |  | ||||||
|             logger.error("", ex); |  | ||||||
|         } catch (final IOException ex) { |         } catch (final IOException ex) { | ||||||
|             logger.error("", ex); |             logger.error("", ex); | ||||||
|         } |         } | ||||||
|  | |||||||
| @ -18,7 +18,7 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread { | |||||||
|     private final HttpGet get; |     private final HttpGet get; | ||||||
|     private PoolingHttpClientConnectionManager connManager; |     private PoolingHttpClientConnectionManager connManager; | ||||||
| 
 | 
 | ||||||
|     public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { |     TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { | ||||||
|         this.client = client; |         this.client = client; | ||||||
|         this.get = get; |         this.get = get; | ||||||
|         this.connManager = Preconditions.checkNotNull(connManager); |         this.connManager = Preconditions.checkNotNull(connManager); | ||||||
| @ -38,8 +38,6 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread { | |||||||
| 
 | 
 | ||||||
|             logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased()); |             logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased()); | ||||||
|             logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable()); |             logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable()); | ||||||
|         } catch (final ClientProtocolException ex) { |  | ||||||
|             logger.error("", ex); |  | ||||||
|         } catch (final IOException ex) { |         } catch (final IOException ex) { | ||||||
|             logger.error("", ex); |             logger.error("", ex); | ||||||
|         } |         } | ||||||
|  | |||||||
| @ -1,12 +1,7 @@ | |||||||
| package org.baeldung.httpclient.rare; | package org.baeldung.httpclient.rare; | ||||||
| 
 | 
 | ||||||
| import static org.hamcrest.Matchers.equalTo; | import com.google.common.base.Preconditions; | ||||||
| import static org.junit.Assert.assertThat; | import com.google.common.collect.Lists; | ||||||
| 
 |  | ||||||
| import java.io.IOException; |  | ||||||
| import java.io.InputStream; |  | ||||||
| import java.util.List; |  | ||||||
| 
 |  | ||||||
| import org.apache.commons.lang3.tuple.ImmutablePair; | import org.apache.commons.lang3.tuple.ImmutablePair; | ||||||
| import org.apache.commons.lang3.tuple.Pair; | import org.apache.commons.lang3.tuple.Pair; | ||||||
| import org.apache.http.Header; | import org.apache.http.Header; | ||||||
| @ -20,8 +15,12 @@ import org.apache.http.util.EntityUtils; | |||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
| import com.google.common.base.Preconditions; | import java.io.IOException; | ||||||
| import com.google.common.collect.Lists; | import java.io.InputStream; | ||||||
|  | import java.util.List; | ||||||
|  | 
 | ||||||
|  | import static org.hamcrest.Matchers.equalTo; | ||||||
|  | import static org.junit.Assert.assertThat; | ||||||
| 
 | 
 | ||||||
| public class HttpClientUnshortenLiveTest { | public class HttpClientUnshortenLiveTest { | ||||||
| 
 | 
 | ||||||
| @ -52,7 +51,7 @@ public class HttpClientUnshortenLiveTest { | |||||||
| 
 | 
 | ||||||
|     // API |     // API | ||||||
| 
 | 
 | ||||||
|     final String expand(final String urlArg) throws IOException { |     private String expand(final String urlArg) throws IOException { | ||||||
|         String originalUrl = urlArg; |         String originalUrl = urlArg; | ||||||
|         String newUrl = expandSingleLevel(originalUrl); |         String newUrl = expandSingleLevel(originalUrl); | ||||||
|         while (!originalUrl.equals(newUrl)) { |         while (!originalUrl.equals(newUrl)) { | ||||||
| @ -81,7 +80,7 @@ public class HttpClientUnshortenLiveTest { | |||||||
|         return newUrl; |         return newUrl; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     final Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException { |     private Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException { | ||||||
|         HttpHead request = null; |         HttpHead request = null; | ||||||
|         HttpEntity httpEntity = null; |         HttpEntity httpEntity = null; | ||||||
|         InputStream entityContentStream = null; |         InputStream entityContentStream = null; | ||||||
| @ -95,15 +94,15 @@ public class HttpClientUnshortenLiveTest { | |||||||
| 
 | 
 | ||||||
|             final int statusCode = httpResponse.getStatusLine().getStatusCode(); |             final int statusCode = httpResponse.getStatusLine().getStatusCode(); | ||||||
|             if (statusCode != 301 && statusCode != 302) { |             if (statusCode != 301 && statusCode != 302) { | ||||||
|                 return new ImmutablePair<Integer, String>(statusCode, url); |                 return new ImmutablePair<>(statusCode, url); | ||||||
|             } |             } | ||||||
|             final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); |             final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); | ||||||
|             Preconditions.checkState(headers.length == 1); |             Preconditions.checkState(headers.length == 1); | ||||||
|             final String newUrl = headers[0].getValue(); |             final String newUrl = headers[0].getValue(); | ||||||
| 
 | 
 | ||||||
|             return new ImmutablePair<Integer, String>(statusCode, newUrl); |             return new ImmutablePair<>(statusCode, newUrl); | ||||||
|         } catch (final IllegalArgumentException uriEx) { |         } catch (final IllegalArgumentException uriEx) { | ||||||
|             return new ImmutablePair<Integer, String>(500, url); |             return new ImmutablePair<>(500, url); | ||||||
|         } finally { |         } finally { | ||||||
|             if (request != null) { |             if (request != null) { | ||||||
|                 request.releaseConnection(); |                 request.releaseConnection(); | ||||||
| @ -117,7 +116,7 @@ public class HttpClientUnshortenLiveTest { | |||||||
|         } |         } | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     final String expandSingleLevel(final String url) throws IOException { |     private String expandSingleLevel(final String url) throws IOException { | ||||||
|         HttpHead request = null; |         HttpHead request = null; | ||||||
| 
 | 
 | ||||||
|         try { |         try { | ||||||
| @ -130,9 +129,8 @@ public class HttpClientUnshortenLiveTest { | |||||||
|             } |             } | ||||||
|             final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); |             final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); | ||||||
|             Preconditions.checkState(headers.length == 1); |             Preconditions.checkState(headers.length == 1); | ||||||
|             final String newUrl = headers[0].getValue(); |  | ||||||
| 
 | 
 | ||||||
|             return newUrl; |             return headers[0].getValue(); | ||||||
|         } catch (final IllegalArgumentException uriEx) { |         } catch (final IllegalArgumentException uriEx) { | ||||||
|             return url; |             return url; | ||||||
|         } finally { |         } finally { | ||||||
|  | |||||||
| @ -1,21 +1,12 @@ | |||||||
| package org.baeldung.httpclient.sec; | package org.baeldung.httpclient.sec; | ||||||
| 
 | 
 | ||||||
| import static org.hamcrest.Matchers.equalTo; |  | ||||||
| import static org.junit.Assert.assertThat; |  | ||||||
| 
 |  | ||||||
| import java.io.IOException; |  | ||||||
| import java.io.InputStream; |  | ||||||
| import java.nio.charset.Charset; |  | ||||||
| 
 |  | ||||||
| import org.apache.commons.codec.binary.Base64; | import org.apache.commons.codec.binary.Base64; | ||||||
| import org.apache.http.HttpEntity; |  | ||||||
| import org.apache.http.HttpHeaders; | import org.apache.http.HttpHeaders; | ||||||
| import org.apache.http.HttpHost; | import org.apache.http.HttpHost; | ||||||
| import org.apache.http.HttpStatus; | import org.apache.http.HttpStatus; | ||||||
| import org.apache.http.auth.AuthScope; | import org.apache.http.auth.AuthScope; | ||||||
| import org.apache.http.auth.UsernamePasswordCredentials; | import org.apache.http.auth.UsernamePasswordCredentials; | ||||||
| import org.apache.http.client.AuthCache; | import org.apache.http.client.AuthCache; | ||||||
| import org.apache.http.client.ClientProtocolException; |  | ||||||
| import org.apache.http.client.CredentialsProvider; | import org.apache.http.client.CredentialsProvider; | ||||||
| import org.apache.http.client.methods.CloseableHttpResponse; | import org.apache.http.client.methods.CloseableHttpResponse; | ||||||
| import org.apache.http.client.methods.HttpGet; | import org.apache.http.client.methods.HttpGet; | ||||||
| @ -26,10 +17,17 @@ import org.apache.http.impl.client.BasicCredentialsProvider; | |||||||
| import org.apache.http.impl.client.CloseableHttpClient; | import org.apache.http.impl.client.CloseableHttpClient; | ||||||
| import org.apache.http.impl.client.HttpClientBuilder; | import org.apache.http.impl.client.HttpClientBuilder; | ||||||
| import org.apache.http.protocol.HttpContext; | import org.apache.http.protocol.HttpContext; | ||||||
|  | import org.baeldung.httpclient.ResponseUtil; | ||||||
| import org.junit.After; | import org.junit.After; | ||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import java.io.IOException; | ||||||
|  | import java.nio.charset.Charset; | ||||||
|  | 
 | ||||||
|  | import static org.hamcrest.Matchers.equalTo; | ||||||
|  | import static org.junit.Assert.assertThat; | ||||||
|  | 
 | ||||||
| /* | /* | ||||||
|  * NOTE : Need module spring-security-rest-basic-auth to be running |  * NOTE : Need module spring-security-rest-basic-auth to be running | ||||||
|  */ |  */ | ||||||
| @ -51,25 +49,13 @@ public class HttpClientAuthLiveTest { | |||||||
| 
 | 
 | ||||||
|     @After |     @After | ||||||
|     public final void after() throws IllegalStateException, IOException { |     public final void after() throws IllegalStateException, IOException { | ||||||
|         if (response == null) { |         ResponseUtil.closeResponse(response); | ||||||
|             return; |  | ||||||
|         } |  | ||||||
| 
 |  | ||||||
|         try { |  | ||||||
|             final HttpEntity entity = response.getEntity(); |  | ||||||
|             if (entity != null) { |  | ||||||
|                 final InputStream instream = entity.getContent(); |  | ||||||
|                 instream.close(); |  | ||||||
|             } |  | ||||||
|         } finally { |  | ||||||
|             response.close(); |  | ||||||
|         } |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     // tests |     // tests | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException { |     public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { | ||||||
|         client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build(); |         client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build(); | ||||||
| 
 | 
 | ||||||
|         response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION)); |         response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION)); | ||||||
| @ -79,7 +65,7 @@ public class HttpClientAuthLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException { |     public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { | ||||||
|         client = HttpClientBuilder.create().build(); |         client = HttpClientBuilder.create().build(); | ||||||
|         response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context()); |         response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context()); | ||||||
| 
 | 
 | ||||||
| @ -88,7 +74,7 @@ public class HttpClientAuthLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws ClientProtocolException, IOException { |     public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException { | ||||||
|         client = HttpClientBuilder.create().build(); |         client = HttpClientBuilder.create().build(); | ||||||
| 
 | 
 | ||||||
|         final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); |         final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); | ||||||
| @ -100,7 +86,7 @@ public class HttpClientAuthLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws ClientProtocolException, IOException { |     public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException { | ||||||
|         final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); |         final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); | ||||||
|         final String auth = DEFAULT_USER + ":" + DEFAULT_PASS; |         final String auth = DEFAULT_USER + ":" + DEFAULT_PASS; | ||||||
|         final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); |         final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); | ||||||
| @ -116,14 +102,14 @@ public class HttpClientAuthLiveTest { | |||||||
| 
 | 
 | ||||||
|     // UTILS |     // UTILS | ||||||
| 
 | 
 | ||||||
|     private final CredentialsProvider provider() { |     private CredentialsProvider provider() { | ||||||
|         final CredentialsProvider provider = new BasicCredentialsProvider(); |         final CredentialsProvider provider = new BasicCredentialsProvider(); | ||||||
|         final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); |         final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); | ||||||
|         provider.setCredentials(AuthScope.ANY, credentials); |         provider.setCredentials(AuthScope.ANY, credentials); | ||||||
|         return provider; |         return provider; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     private final HttpContext context() { |     private HttpContext context() { | ||||||
|         final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); |         final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); | ||||||
|         final CredentialsProvider credsProvider = new BasicCredentialsProvider(); |         final CredentialsProvider credsProvider = new BasicCredentialsProvider(); | ||||||
|         credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS)); |         credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS)); | ||||||
| @ -141,12 +127,11 @@ public class HttpClientAuthLiveTest { | |||||||
|         return context; |         return context; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     private final String authorizationHeader(final String username, final String password) { |     private String authorizationHeader(final String username, final String password) { | ||||||
|         final String auth = username + ":" + password; |         final String auth = username + ":" + password; | ||||||
|         final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); |         final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); | ||||||
|         final String authHeader = "Basic " + new String(encodedAuth); |  | ||||||
| 
 | 
 | ||||||
|         return authHeader; |         return "Basic " + new String(encodedAuth); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
| } | } | ||||||
|  | |||||||
| @ -1,13 +1,5 @@ | |||||||
| package org.baeldung.httpclient.sec; | package org.baeldung.httpclient.sec; | ||||||
| 
 | 
 | ||||||
| import static org.hamcrest.Matchers.equalTo; |  | ||||||
| import static org.junit.Assert.assertThat; |  | ||||||
| 
 |  | ||||||
| import java.io.IOException; |  | ||||||
| import java.io.InputStream; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.HttpEntity; |  | ||||||
| import org.apache.http.client.ClientProtocolException; |  | ||||||
| import org.apache.http.client.HttpClient; | import org.apache.http.client.HttpClient; | ||||||
| import org.apache.http.client.methods.CloseableHttpResponse; | import org.apache.http.client.methods.CloseableHttpResponse; | ||||||
| import org.apache.http.client.methods.HttpGet; | import org.apache.http.client.methods.HttpGet; | ||||||
| @ -18,10 +10,16 @@ import org.apache.http.impl.client.HttpClientBuilder; | |||||||
| import org.apache.http.impl.cookie.BasicClientCookie; | import org.apache.http.impl.cookie.BasicClientCookie; | ||||||
| import org.apache.http.protocol.BasicHttpContext; | import org.apache.http.protocol.BasicHttpContext; | ||||||
| import org.apache.http.protocol.HttpContext; | import org.apache.http.protocol.HttpContext; | ||||||
|  | import org.baeldung.httpclient.ResponseUtil; | ||||||
| import org.junit.After; | import org.junit.After; | ||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import java.io.IOException; | ||||||
|  | 
 | ||||||
|  | import static org.hamcrest.Matchers.equalTo; | ||||||
|  | import static org.junit.Assert.assertThat; | ||||||
|  | 
 | ||||||
| public class HttpClientCookieLiveTest { | public class HttpClientCookieLiveTest { | ||||||
| 
 | 
 | ||||||
|     private CloseableHttpClient instance; |     private CloseableHttpClient instance; | ||||||
| @ -35,25 +33,13 @@ public class HttpClientCookieLiveTest { | |||||||
| 
 | 
 | ||||||
|     @After |     @After | ||||||
|     public final void after() throws IllegalStateException, IOException { |     public final void after() throws IllegalStateException, IOException { | ||||||
|         if (response == null) { |         ResponseUtil.closeResponse(response); | ||||||
|             return; |  | ||||||
|         } |  | ||||||
| 
 |  | ||||||
|         try { |  | ||||||
|             final HttpEntity entity = response.getEntity(); |  | ||||||
|             if (entity != null) { |  | ||||||
|                 final InputStream instream = entity.getContent(); |  | ||||||
|                 instream.close(); |  | ||||||
|             } |  | ||||||
|         } finally { |  | ||||||
|             response.close(); |  | ||||||
|         } |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     // tests |     // tests | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException { |     public final void whenSettingCookiesOnARequest_thenCorrect() throws IOException { | ||||||
|         instance = HttpClientBuilder.create().build(); |         instance = HttpClientBuilder.create().build(); | ||||||
|         final HttpGet request = new HttpGet("http://www.github.com"); |         final HttpGet request = new HttpGet("http://www.github.com"); | ||||||
|         request.setHeader("Cookie", "JSESSIONID=1234"); |         request.setHeader("Cookie", "JSESSIONID=1234"); | ||||||
| @ -64,7 +50,7 @@ public class HttpClientCookieLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException { |     public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException { | ||||||
|         final BasicCookieStore cookieStore = new BasicCookieStore(); |         final BasicCookieStore cookieStore = new BasicCookieStore(); | ||||||
|         final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); |         final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); | ||||||
|         cookie.setDomain(".github.com"); |         cookie.setDomain(".github.com"); | ||||||
| @ -80,7 +66,7 @@ public class HttpClientCookieLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException { |     public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException { | ||||||
|         final BasicCookieStore cookieStore = new BasicCookieStore(); |         final BasicCookieStore cookieStore = new BasicCookieStore(); | ||||||
|         final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); |         final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); | ||||||
|         cookie.setDomain(".github.com"); |         cookie.setDomain(".github.com"); | ||||||
| @ -96,7 +82,7 @@ public class HttpClientCookieLiveTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException { |     public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException { | ||||||
|         final BasicCookieStore cookieStore = new BasicCookieStore(); |         final BasicCookieStore cookieStore = new BasicCookieStore(); | ||||||
|         final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); |         final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); | ||||||
|         cookie.setDomain(".github.com"); |         cookie.setDomain(".github.com"); | ||||||
|  | |||||||
| @ -39,7 +39,7 @@ | |||||||
| 
 | 
 | ||||||
|     <properties> |     <properties> | ||||||
|         <javax.servlet.version>3.1.0</javax.servlet.version> |         <javax.servlet.version>3.1.0</javax.servlet.version> | ||||||
|         <org.apache.httpcomponents.version>4.5.2</org.apache.httpcomponents.version> |         <org.apache.httpcomponents.version>4.5.3</org.apache.httpcomponents.version> | ||||||
|     </properties> |     </properties> | ||||||
| 
 | 
 | ||||||
| </project> | </project> | ||||||
| @ -1,24 +1,24 @@ | |||||||
| package com.baeldung.servlets; | package com.baeldung.servlets; | ||||||
| 
 | 
 | ||||||
| import static org.junit.Assert.assertEquals; |  | ||||||
| 
 |  | ||||||
| import java.util.ArrayList; |  | ||||||
| import java.util.List; |  | ||||||
| 
 |  | ||||||
| import org.apache.http.HttpResponse; | import org.apache.http.HttpResponse; | ||||||
| import org.apache.http.client.HttpClient; | import org.apache.http.client.HttpClient; | ||||||
| import org.apache.http.client.entity.UrlEncodedFormEntity; | import org.apache.http.client.entity.UrlEncodedFormEntity; | ||||||
| import org.apache.http.client.methods.HttpPost; | import org.apache.http.client.methods.HttpPost; | ||||||
| import org.apache.http.impl.client.DefaultHttpClient; | import org.apache.http.impl.client.HttpClientBuilder; | ||||||
| import org.apache.http.message.BasicNameValuePair; | import org.apache.http.message.BasicNameValuePair; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
|  | import java.util.ArrayList; | ||||||
|  | import java.util.List; | ||||||
|  | 
 | ||||||
|  | import static org.junit.Assert.assertEquals; | ||||||
|  | 
 | ||||||
| public class FormServletLiveTest { | public class FormServletLiveTest { | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenPostRequestUsingHttpClient_thenCorrect() throws Exception { |     public void whenPostRequestUsingHttpClient_thenCorrect() throws Exception { | ||||||
| 
 | 
 | ||||||
|         HttpClient client = new DefaultHttpClient(); |         HttpClient client = HttpClientBuilder.create().build(); | ||||||
|         HttpPost method = new HttpPost("http://localhost:8080/calculateServlet"); |         HttpPost method = new HttpPost("http://localhost:8080/calculateServlet"); | ||||||
| 
 | 
 | ||||||
|         List<BasicNameValuePair> nvps = new ArrayList<>(); |         List<BasicNameValuePair> nvps = new ArrayList<>(); | ||||||
|  | |||||||
							
								
								
									
										100
									
								
								jmh/pom.xml
									
									
									
									
									
								
							
							
						
						
									
										100
									
								
								jmh/pom.xml
									
									
									
									
									
								
							| @ -1,52 +1,60 @@ | |||||||
| <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | <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"> |          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | ||||||
| 	<modelVersion>4.0.0</modelVersion> |     <modelVersion>4.0.0</modelVersion> | ||||||
| 	<groupId>com.baeldung</groupId> |     <groupId>com.baeldung</groupId> | ||||||
| 	<artifactId>jmh</artifactId> |     <artifactId>jmh</artifactId> | ||||||
| 	<packaging>jar</packaging> |     <packaging>jar</packaging> | ||||||
| 	<version>1.0-SNAPSHOT</version> |     <version>1.0-SNAPSHOT</version> | ||||||
| 	<name>jmh</name> |     <name>jmh</name> | ||||||
| 	<url>http://maven.apache.org</url> |     <url>http://maven.apache.org</url> | ||||||
| 
 | 
 | ||||||
| 	<properties> |     <properties> | ||||||
| 		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> |         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||||
| 		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> |         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> | ||||||
| 		<java.version>1.8</java.version> |         <java.version>1.8</java.version> | ||||||
| 	</properties> |         <maven.compiler.source>1.6</maven.compiler.source> | ||||||
|  |         <maven.compiler.target>1.6</maven.compiler.target> | ||||||
|  |     </properties> | ||||||
| 
 | 
 | ||||||
| 	<dependencies> |     <dependencies> | ||||||
| 		<dependency> |         <dependency> | ||||||
| 			<groupId>org.openjdk.jmh</groupId> |             <groupId>org.openjdk.jmh</groupId> | ||||||
| 			<artifactId>jmh-core</artifactId> |             <artifactId>jmh-core</artifactId> | ||||||
| 			<version>1.19</version> |             <version>1.19</version> | ||||||
| 		</dependency> |         </dependency> | ||||||
| 		<dependency> |         <dependency> | ||||||
| 			<groupId>org.openjdk.jmh</groupId> |             <groupId>org.openjdk.jmh</groupId> | ||||||
| 			<artifactId>jmh-generator-annprocess</artifactId> |             <artifactId>jmh-generator-annprocess</artifactId> | ||||||
| 			<version>1.19</version> |             <version>1.19</version> | ||||||
| 		</dependency> |         </dependency> | ||||||
| 		<dependency> |         <dependency> | ||||||
| 			<groupId>junit</groupId> |             <groupId>junit</groupId> | ||||||
| 			<artifactId>junit</artifactId> |             <artifactId>junit</artifactId> | ||||||
| 			<version>3.8.1</version> |             <version>3.8.1</version> | ||||||
| 			<scope>test</scope> |             <scope>test</scope> | ||||||
| 		</dependency> |         </dependency> | ||||||
| 	</dependencies> |  | ||||||
| 
 | 
 | ||||||
| 	<build> |         <dependency> | ||||||
| 		<plugins> |             <groupId>com.google.guava</groupId> | ||||||
| 			<plugin> |             <artifactId>guava</artifactId> | ||||||
| 				<groupId>org.apache.maven.plugins</groupId> |             <version>21.0</version> | ||||||
| 				<artifactId>maven-jar-plugin</artifactId> |         </dependency> | ||||||
| 				<configuration> |     </dependencies> | ||||||
| 					<archive> | 
 | ||||||
| 						<manifest> |     <build> | ||||||
| 							<mainClass>com.baeldung.Application</mainClass> |         <plugins> | ||||||
| 						</manifest> |             <plugin> | ||||||
| 					</archive> |                 <groupId>org.apache.maven.plugins</groupId> | ||||||
| 				</configuration> |                 <artifactId>maven-jar-plugin</artifactId> | ||||||
| 			</plugin> |                 <configuration> | ||||||
| 		</plugins> |                     <archive> | ||||||
| 	</build> |                         <manifest> | ||||||
|  |                             <mainClass>com.baeldung.BenchmarkRunner</mainClass> | ||||||
|  |                         </manifest> | ||||||
|  |                     </archive> | ||||||
|  |                 </configuration> | ||||||
|  |             </plugin> | ||||||
|  |         </plugins> | ||||||
|  |     </build> | ||||||
| 
 | 
 | ||||||
| </project> | </project> | ||||||
| @ -1,14 +0,0 @@ | |||||||
| package com.baeldung; |  | ||||||
| 
 |  | ||||||
| import java.io.IOException; |  | ||||||
| 
 |  | ||||||
| import org.openjdk.jmh.Main; |  | ||||||
| import org.openjdk.jmh.runner.RunnerException; |  | ||||||
| 
 |  | ||||||
| public class Application { |  | ||||||
| 
 |  | ||||||
| 	public static void main(String[] args) throws RunnerException, IOException { |  | ||||||
| 		Main.main(args); |  | ||||||
| 	} |  | ||||||
| 
 |  | ||||||
| } |  | ||||||
| @ -1,12 +1,48 @@ | |||||||
| package com.baeldung; | package com.baeldung; | ||||||
| 
 | 
 | ||||||
| import org.openjdk.jmh.annotations.Benchmark; | import com.google.common.hash.HashFunction; | ||||||
|  | import com.google.common.hash.Hasher; | ||||||
|  | import com.google.common.hash.Hashing; | ||||||
|  | import org.openjdk.jmh.annotations.*; | ||||||
|  | 
 | ||||||
|  | import java.nio.charset.Charset; | ||||||
| 
 | 
 | ||||||
| public class BenchMark { | public class BenchMark { | ||||||
| 
 | 
 | ||||||
| 	@Benchmark |     @State(Scope.Benchmark) | ||||||
| 	public void init() { |     public static class ExecutionPlan { | ||||||
| 		 | 
 | ||||||
| 	} |         @Param({ "100", "200", "300", "500", "1000" }) | ||||||
|  |         public int iterations; | ||||||
|  | 
 | ||||||
|  |         public Hasher murmur3; | ||||||
|  | 
 | ||||||
|  |         public String password = "4v3rys3kur3p455w0rd"; | ||||||
|  | 
 | ||||||
|  |         @Setup(Level.Invocation) | ||||||
|  |         public void setUp() { | ||||||
|  |             murmur3 = Hashing.murmur3_128().newHasher(); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Fork(value = 1, warmups = 1) | ||||||
|  |     @Benchmark | ||||||
|  |     @BenchmarkMode(Mode.Throughput) | ||||||
|  |     @Warmup(iterations = 5) | ||||||
|  |     public void benchMurmur3_128(ExecutionPlan plan) { | ||||||
|  | 
 | ||||||
|  |         for (int i = plan.iterations; i > 0; i--) { | ||||||
|  |             plan.murmur3.putString(plan.password, Charset.defaultCharset()); | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|  |         plan.murmur3.hash(); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Benchmark | ||||||
|  |     @Fork(value = 1, warmups = 1) | ||||||
|  |     @BenchmarkMode(Mode.Throughput) | ||||||
|  |     public void init() { | ||||||
|  |         // Do nothing | ||||||
|  |     } | ||||||
| 
 | 
 | ||||||
| } | } | ||||||
|  | |||||||
							
								
								
									
										9
									
								
								jmh/src/main/java/com/baeldung/BenchmarkRunner.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										9
									
								
								jmh/src/main/java/com/baeldung/BenchmarkRunner.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,9 @@ | |||||||
|  | package com.baeldung; | ||||||
|  | 
 | ||||||
|  | public class BenchmarkRunner { | ||||||
|  | 
 | ||||||
|  |     public static void main(String[] args) throws Exception { | ||||||
|  |         org.openjdk.jmh.Main.main(args); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -1,38 +0,0 @@ | |||||||
| package com.baeldung; |  | ||||||
| 
 |  | ||||||
| import junit.framework.Test; |  | ||||||
| import junit.framework.TestCase; |  | ||||||
| import junit.framework.TestSuite; |  | ||||||
| 
 |  | ||||||
| /** |  | ||||||
|  * Unit test for simple App. |  | ||||||
|  */ |  | ||||||
| public class AppTest  |  | ||||||
|     extends TestCase |  | ||||||
| { |  | ||||||
|     /** |  | ||||||
|      * Create the test case |  | ||||||
|      * |  | ||||||
|      * @param testName name of the test case |  | ||||||
|      */ |  | ||||||
|     public AppTest( String testName ) |  | ||||||
|     { |  | ||||||
|         super( testName ); |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     /** |  | ||||||
|      * @return the suite of tests being tested |  | ||||||
|      */ |  | ||||||
|     public static Test suite() |  | ||||||
|     { |  | ||||||
|         return new TestSuite( AppTest.class ); |  | ||||||
|     } |  | ||||||
| 
 |  | ||||||
|     /** |  | ||||||
|      * Rigourous Test :-) |  | ||||||
|      */ |  | ||||||
|     public void testApp() |  | ||||||
|     { |  | ||||||
|         assertTrue( true ); |  | ||||||
|     } |  | ||||||
| } |  | ||||||
							
								
								
									
										2
									
								
								jooby/conf/application.conf
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										2
									
								
								jooby/conf/application.conf
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,2 @@ | |||||||
|  | #application.secret = 2o128940921eo298e21 | ||||||
|  | #db = /url/to/the/datastore | ||||||
							
								
								
									
										42
									
								
								jooby/conf/logback.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								jooby/conf/logback.xml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,42 @@ | |||||||
|  | <?xml version="1.0" encoding="UTF-8"?> | ||||||
|  | <configuration scan="true" scanPeriod="15 seconds" debug="false"> | ||||||
|  |   <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> | ||||||
|  |     <encoder> | ||||||
|  |       <pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern> | ||||||
|  |     </encoder> | ||||||
|  |   </appender> | ||||||
|  | 
 | ||||||
|  |   <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> | ||||||
|  |     <file>log/jooby.log</file> | ||||||
|  |     <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> | ||||||
|  |       <fileNamePattern>log/jooby.%d{yyyy-MM-dd}.log</fileNamePattern> | ||||||
|  |       <totalSizeCap>1mb</totalSizeCap> | ||||||
|  |       <maxHistory>7</maxHistory> | ||||||
|  |     </rollingPolicy> | ||||||
|  | 
 | ||||||
|  |     <encoder> | ||||||
|  |       <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern> | ||||||
|  |     </encoder> | ||||||
|  |   </appender> | ||||||
|  | 
 | ||||||
|  |   <appender name="ACCESS" class="ch.qos.logback.core.rolling.RollingFileAppender"> | ||||||
|  |     <file>log/access.log</file> | ||||||
|  |     <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> | ||||||
|  |       <fileNamePattern>log/access.%d{yyyy-MM-dd}.log</fileNamePattern> | ||||||
|  |       <totalSizeCap>1mb</totalSizeCap> | ||||||
|  |       <maxHistory>7</maxHistory> | ||||||
|  |     </rollingPolicy> | ||||||
|  | 
 | ||||||
|  |     <encoder> | ||||||
|  |       <pattern>%msg%n</pattern> | ||||||
|  |     </encoder> | ||||||
|  |   </appender> | ||||||
|  | 
 | ||||||
|  |   <logger name="org.jooby.RequestLogger" additivity="false"> | ||||||
|  |     <appender-ref ref="ACCESS" /> | ||||||
|  |   </logger> | ||||||
|  | 
 | ||||||
|  |   <root level="INFO"> | ||||||
|  |     <appender-ref ref="STDOUT" /> | ||||||
|  |   </root> | ||||||
|  | </configuration> | ||||||
							
								
								
									
										56
									
								
								jooby/pom.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										56
									
								
								jooby/pom.xml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,56 @@ | |||||||
|  | <?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/maven-v4_0_0.xsd"> | ||||||
|  | 	<modelVersion>4.0.0</modelVersion> | ||||||
|  | 	<artifactId>jooby</artifactId> | ||||||
|  | 	<groupId>com.baeldung.jooby</groupId> | ||||||
|  | 	<version>1.0</version> | ||||||
|  | 	<name>jooby</name> | ||||||
|  | 
 | ||||||
|  | 	<parent> | ||||||
|  | 		<groupId>org.jooby</groupId> | ||||||
|  | 		<artifactId>modules</artifactId> | ||||||
|  | 		<version>1.1.3</version> | ||||||
|  | 	</parent> | ||||||
|  | 
 | ||||||
|  | 	<properties> | ||||||
|  | 		<jooby.version>1.1.3</jooby.version> | ||||||
|  | 		<application.class>com.baeldung.jooby.App</application.class> | ||||||
|  | 	</properties> | ||||||
|  | 
 | ||||||
|  | 	<dependencies> | ||||||
|  | 		<dependency> | ||||||
|  | 			<groupId>org.jooby</groupId> | ||||||
|  | 			<artifactId>jooby-netty</artifactId> | ||||||
|  | 		</dependency> | ||||||
|  | 		<dependency> | ||||||
|  | 			<groupId>org.jooby</groupId> | ||||||
|  | 			<artifactId>jooby-jedis</artifactId> | ||||||
|  | 			<version>1.1.3</version> | ||||||
|  | 		</dependency> | ||||||
|  | 		<dependency> | ||||||
|  | 			<groupId>ch.qos.logback</groupId> | ||||||
|  | 			<artifactId>logback-classic</artifactId> | ||||||
|  | 		</dependency> | ||||||
|  | 		<dependency> | ||||||
|  | 			<groupId>junit</groupId> | ||||||
|  | 			<artifactId>junit</artifactId> | ||||||
|  | 			<scope>test</scope> | ||||||
|  | 		</dependency> | ||||||
|  | 		<dependency> | ||||||
|  | 			<groupId>io.rest-assured</groupId> | ||||||
|  | 			<artifactId>rest-assured</artifactId> | ||||||
|  | 			<scope>test</scope> | ||||||
|  | 		</dependency> | ||||||
|  | 	</dependencies> | ||||||
|  | 
 | ||||||
|  | 	<build> | ||||||
|  | 		<plugins> | ||||||
|  | 			<plugin> | ||||||
|  | 				<groupId>org.apache.maven.plugins</groupId> | ||||||
|  | 				<artifactId>maven-shade-plugin</artifactId> | ||||||
|  | 			</plugin> | ||||||
|  | 		</plugins> | ||||||
|  | 	</build> | ||||||
|  | 
 | ||||||
|  | </project> | ||||||
							
								
								
									
										17
									
								
								jooby/public/form.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										17
									
								
								jooby/public/form.html
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,17 @@ | |||||||
|  | <!DOCTYPE html> | ||||||
|  | <html> | ||||||
|  | <head> | ||||||
|  | <meta charset="UTF-8"> | ||||||
|  | <title>Insert title here</title> | ||||||
|  | </head> | ||||||
|  | <body> | ||||||
|  | 	<form enctype="application/x-www-form-urlencoded" action="/submitForm" method="post"> | ||||||
|  | 	  <input name="id" /> | ||||||
|  | 	  <input name="name" /> | ||||||
|  | 	  <input name="email" /> | ||||||
|  | 	  <input name="phone" /> | ||||||
|  | 	  <input name="address" /> | ||||||
|  | 	  <input type="submit" value="Submit"/> | ||||||
|  | 	</form> | ||||||
|  | </body> | ||||||
|  | </html> | ||||||
							
								
								
									
										10
									
								
								jooby/public/welcome.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										10
									
								
								jooby/public/welcome.html
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,10 @@ | |||||||
|  | <!DOCTYPE html> | ||||||
|  | <html> | ||||||
|  | <head> | ||||||
|  | <meta charset="UTF-8"> | ||||||
|  | <title>Insert title here</title> | ||||||
|  | </head> | ||||||
|  | <body> | ||||||
|  | i m welcomed | ||||||
|  | </body> | ||||||
|  | </html> | ||||||
							
								
								
									
										41
									
								
								jooby/src/etc/stork.yml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										41
									
								
								jooby/src/etc/stork.yml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,41 @@ | |||||||
|  | # Name of application (make sure it has no spaces) | ||||||
|  | name: "${project.artifactId}" | ||||||
|  | 
 | ||||||
|  | # Display name of application (can have spaces) | ||||||
|  | display_name: "${project.name}" | ||||||
|  | 
 | ||||||
|  | # Type of launcher (CONSOLE or DAEMON) | ||||||
|  | type: DAEMON | ||||||
|  | 
 | ||||||
|  | # Java class to run | ||||||
|  | main_class: "${application.class}" | ||||||
|  | 
 | ||||||
|  | domain: "${project.groupId}" | ||||||
|  | 
 | ||||||
|  | short_description: "${project.artifactId}" | ||||||
|  | 
 | ||||||
|  | # Platform launchers to generate (WINDOWS, LINUX, MAC_OSX) | ||||||
|  | # Linux launcher is suitable for Bourne shells (e.g. Linux/BSD) | ||||||
|  | platforms: [ LINUX ] | ||||||
|  | 
 | ||||||
|  | # Working directory for app | ||||||
|  | #  RETAIN will not change the working directory | ||||||
|  | #  APP_HOME will change the working directory to the home of the app | ||||||
|  | #    (where it was intalled) before running the main class | ||||||
|  | working_dir_mode: RETAIN | ||||||
|  | 
 | ||||||
|  | # Minimum version of java required (system will be searched for acceptable jvm) | ||||||
|  | min_java_version: "1.8" | ||||||
|  | 
 | ||||||
|  | # Min/max fixed memory (measured in MB) | ||||||
|  | min_java_memory: 512 | ||||||
|  | max_java_memory: 512 | ||||||
|  | 
 | ||||||
|  | # Min/max memory by percentage of system | ||||||
|  | #min_java_memory_pct: 10 | ||||||
|  | #max_java_memory_pct: 20 | ||||||
|  | 
 | ||||||
|  | # Try to create a symbolic link to java executable in <app_home>/run with | ||||||
|  | # the name of "<app_name>-java" so that commands like "ps" will make it | ||||||
|  | # easier to find your app | ||||||
|  | symlink_java: true | ||||||
							
								
								
									
										95
									
								
								jooby/src/main/java/com/baeldung/jooby/App.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										95
									
								
								jooby/src/main/java/com/baeldung/jooby/App.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,95 @@ | |||||||
|  | package com.baeldung.jooby; | ||||||
|  | 
 | ||||||
|  | import org.jooby.Jooby; | ||||||
|  | import org.jooby.Mutant; | ||||||
|  | import org.jooby.Session; | ||||||
|  | import org.jooby.jedis.Redis; | ||||||
|  | import org.jooby.jedis.RedisSessionStore; | ||||||
|  | 
 | ||||||
|  | import com.baeldung.jooby.bean.Employee; | ||||||
|  | 
 | ||||||
|  | public class App extends Jooby { | ||||||
|  | 
 | ||||||
|  | 	{ | ||||||
|  | 		port(8080); | ||||||
|  | 		securePort(8443); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	{ | ||||||
|  | 		get("/", () -> "Hello World!"); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	{ | ||||||
|  | 		get("/user/{id}", req -> "Hello user : " + req.param("id").value()); | ||||||
|  | 		get("/user/:id", req -> "Hello user: " + req.param("id").value()); | ||||||
|  | 		get("/uid:{id}", req -> "Hello User with id : uid" + req.param("id").value()); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	{ | ||||||
|  | 		onStart(() -> { | ||||||
|  | 			System.out.println("starting app"); | ||||||
|  | 		}); | ||||||
|  | 
 | ||||||
|  | 		onStop(() -> { | ||||||
|  | 			System.out.println("stopping app"); | ||||||
|  | 		}); | ||||||
|  | 
 | ||||||
|  | 		onStarted(() -> { | ||||||
|  | 			System.out.println("app started"); | ||||||
|  | 		}); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	{ | ||||||
|  | 		get("/login", () -> "Hello from Baeldung"); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	{ | ||||||
|  | 		post("/save", req -> { | ||||||
|  | 			Mutant token = req.param("token"); | ||||||
|  | 			return token.intValue(); | ||||||
|  | 		}); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	{ | ||||||
|  | 		{ | ||||||
|  | 			assets("/employee", "form.html"); | ||||||
|  | 		} | ||||||
|  | 
 | ||||||
|  | 		post("/submitForm", req -> { | ||||||
|  | 			Employee employee = req.params(Employee.class); | ||||||
|  | 			// TODO | ||||||
|  | 			return "empoyee data saved successfullly"; | ||||||
|  | 		}); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	{ | ||||||
|  | 		get("/filter", (req, resp, chain) -> { | ||||||
|  | 			// TODO | ||||||
|  | 			// resp.send(...); | ||||||
|  | 			chain.next(req, resp); | ||||||
|  | 		}); | ||||||
|  | 		get("/filter", (req, resp) -> { | ||||||
|  | 			resp.send("filter response"); | ||||||
|  | 		}); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	{ | ||||||
|  | //		cookieSession(); | ||||||
|  | 		 | ||||||
|  | //		use(new Redis()); | ||||||
|  | // | ||||||
|  | //		session(RedisSessionStore.class); | ||||||
|  | 
 | ||||||
|  | 		get("/session", req -> { | ||||||
|  | 			Session session = req.session(); | ||||||
|  | 			session.set("token", "value"); | ||||||
|  | 			return session.get("token").value(); | ||||||
|  | 		}); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	public static void main(final String[] args) { | ||||||
|  | 
 | ||||||
|  | 		run(App::new, args); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
							
								
								
									
										16
									
								
								jooby/src/main/java/com/baeldung/jooby/bean/Employee.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								jooby/src/main/java/com/baeldung/jooby/bean/Employee.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,16 @@ | |||||||
|  | package com.baeldung.jooby.bean; | ||||||
|  | 
 | ||||||
|  | public class Employee { | ||||||
|  | 
 | ||||||
|  | 	String id; | ||||||
|  | 	String name; | ||||||
|  | 	String email; | ||||||
|  | 
 | ||||||
|  | 	public Employee(String id, String name, String email) { | ||||||
|  | 		super(); | ||||||
|  | 		this.id = id; | ||||||
|  | 		this.name = name; | ||||||
|  | 		this.email = email; | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,22 @@ | |||||||
|  | package com.baeldung.jooby.mvc; | ||||||
|  | 
 | ||||||
|  | import org.jooby.Result; | ||||||
|  | import org.jooby.Results; | ||||||
|  | import org.jooby.mvc.GET; | ||||||
|  | import org.jooby.mvc.Path; | ||||||
|  | 
 | ||||||
|  | @Path("/hello") | ||||||
|  | public class GetController { | ||||||
|  | 
 | ||||||
|  | 	@GET | ||||||
|  | 	public String hello() { | ||||||
|  | 		return "Hello Baeldung"; | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	@GET | ||||||
|  | 	@Path("/home") | ||||||
|  | 	public Result home() { | ||||||
|  | 		return Results.html("welcome").put("model", new Object()); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,14 @@ | |||||||
|  | package com.baeldung.jooby.mvc; | ||||||
|  | 
 | ||||||
|  | import org.jooby.mvc.POST; | ||||||
|  | import org.jooby.mvc.Path; | ||||||
|  | 
 | ||||||
|  | @Path("/submit") | ||||||
|  | public class PostController { | ||||||
|  | 
 | ||||||
|  | 	@POST | ||||||
|  | 	public String hello() { | ||||||
|  | 		return "Submit Baeldung"; | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
							
								
								
									
										29
									
								
								jooby/src/test/java/com/baeldung/jooby/AppTest.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										29
									
								
								jooby/src/test/java/com/baeldung/jooby/AppTest.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,29 @@ | |||||||
|  | package com.baeldung.jooby; | ||||||
|  | 
 | ||||||
|  | import static io.restassured.RestAssured.get; | ||||||
|  | import static org.hamcrest.Matchers.equalTo; | ||||||
|  | import static org.junit.Assert.assertEquals; | ||||||
|  | 
 | ||||||
|  | import org.jooby.test.JoobyRule; | ||||||
|  | import org.jooby.test.MockRouter; | ||||||
|  | import org.junit.ClassRule; | ||||||
|  | import org.junit.Test; | ||||||
|  | 
 | ||||||
|  | public class AppTest { | ||||||
|  | 
 | ||||||
|  | 	@ClassRule | ||||||
|  | 	public static JoobyRule app = new JoobyRule(new App()); | ||||||
|  | 
 | ||||||
|  | 	@Test | ||||||
|  | 	public void given_defaultUrl_expect_fixedString() { | ||||||
|  | 		get("/").then().assertThat().body(equalTo("Hello World!")).statusCode(200) | ||||||
|  | 				.contentType("text/html;charset=UTF-8"); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	@Test | ||||||
|  | 	public void given_defaultUrl_with_mockrouter_expect_fixedString() throws Throwable { | ||||||
|  | 		String result = new MockRouter(new App()).get("/"); | ||||||
|  | 		assertEquals("Hello World!", result); | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -23,6 +23,6 @@ | |||||||
| 
 | 
 | ||||||
|     <properties> |     <properties> | ||||||
|         <!-- json-path --> |         <!-- json-path --> | ||||||
|         <json-path.version>2.2.0</json-path.version> |         <json-path.version>2.4.0</json-path.version> | ||||||
|     </properties> |     </properties> | ||||||
| </project> | </project> | ||||||
| @ -1,10 +1,10 @@ | |||||||
| package com.baeldung.jsonpath.introduction; | package com.baeldung.jsonpath.introduction; | ||||||
| 
 | 
 | ||||||
| import static org.junit.Assert.assertEquals; | import com.jayway.jsonpath.Criteria; | ||||||
| import static org.junit.Assert.assertThat; | import com.jayway.jsonpath.DocumentContext; | ||||||
| import static org.hamcrest.CoreMatchers.containsString; | import com.jayway.jsonpath.Filter; | ||||||
| import static org.hamcrest.CoreMatchers.not; | import com.jayway.jsonpath.JsonPath; | ||||||
| 
 | import com.jayway.jsonpath.Predicate; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
| import java.io.InputStream; | import java.io.InputStream; | ||||||
| @ -12,15 +12,14 @@ import java.util.List; | |||||||
| import java.util.Map; | import java.util.Map; | ||||||
| import java.util.Scanner; | import java.util.Scanner; | ||||||
| 
 | 
 | ||||||
| import com.jayway.jsonpath.Criteria; | import static org.hamcrest.CoreMatchers.containsString; | ||||||
| import com.jayway.jsonpath.DocumentContext; | import static org.hamcrest.CoreMatchers.not; | ||||||
| import com.jayway.jsonpath.Filter; | import static org.junit.Assert.assertEquals; | ||||||
| import com.jayway.jsonpath.JsonPath; | import static org.junit.Assert.assertThat; | ||||||
| import com.jayway.jsonpath.Predicate; |  | ||||||
| 
 | 
 | ||||||
| public class OperationIntegrationTest { | public class OperationIntegrationTest { | ||||||
|     InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json"); |     private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json"); | ||||||
|     String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); |     private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() { |     public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() { | ||||||
| @ -46,12 +45,7 @@ public class OperationIntegrationTest { | |||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() { |     public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() { | ||||||
|         Predicate expensivePredicate = new Predicate() { |         Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class).get("price").toString()) > 20.00; | ||||||
|             public boolean apply(PredicateContext context) { |  | ||||||
|                 String value = context.item(Map.class).get("price").toString(); |  | ||||||
|                 return Float.valueOf(value) > 20.00; |  | ||||||
|             } |  | ||||||
|         }; |  | ||||||
|         List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate); |         List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate); | ||||||
|         predicateUsageAssertionHelper(expensive); |         predicateUsageAssertionHelper(expensive); | ||||||
|     } |     } | ||||||
|  | |||||||
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