diff --git a/algorithms-miscellaneous-1/README.md b/algorithms-miscellaneous-1/README.md index 7ed805f7c4..ea6d6f379b 100644 --- a/algorithms-miscellaneous-1/README.md +++ b/algorithms-miscellaneous-1/README.md @@ -17,3 +17,4 @@ - [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique) - [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations) - [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine) +- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm) diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/relativelyprime/RelativelyPrime.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/relativelyprime/RelativelyPrime.java new file mode 100644 index 0000000000..fbea87be30 --- /dev/null +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/relativelyprime/RelativelyPrime.java @@ -0,0 +1,45 @@ +package com.baeldung.algorithms.relativelyprime; + +import java.math.BigInteger; + +class RelativelyPrime { + + static boolean iterativeRelativelyPrime(int a, int b) { + return iterativeGCD(a, b) == 1; + } + + static boolean recursiveRelativelyPrime(int a, int b) { + return recursiveGCD(a, b) == 1; + } + + static boolean bigIntegerRelativelyPrime(int a, int b) { + return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).equals(BigInteger.ONE); + } + + private static int iterativeGCD(int a, int b) { + int tmp; + while (b != 0) { + if (a < b) { + tmp = a; + a = b; + b = tmp; + } + tmp = b; + b = a % b; + a = tmp; + } + return a; + } + + private static int recursiveGCD(int a, int b) { + if (b == 0) { + return a; + } + if (a < b) { + return recursiveGCD(b, a); + } + return recursiveGCD(b, a % b); + } + + +} diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java new file mode 100644 index 0000000000..7905b752a9 --- /dev/null +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java @@ -0,0 +1,42 @@ +package com.baeldung.algorithms.reversingtree; + +public class TreeNode { + + private int value; + private TreeNode rightChild; + private TreeNode leftChild; + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public TreeNode getRightChild() { + return rightChild; + } + + public void setRightChild(TreeNode rightChild) { + this.rightChild = rightChild; + } + + public TreeNode getLeftChild() { + return leftChild; + } + + public void setLeftChild(TreeNode leftChild) { + this.leftChild = leftChild; + } + + public TreeNode(int value, TreeNode rightChild, TreeNode leftChild) { + this.value = value; + this.rightChild = rightChild; + this.leftChild = leftChild; + } + + public TreeNode(int value) { + this.value = value; + } +} diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java new file mode 100644 index 0000000000..6d3a9ddd31 --- /dev/null +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java @@ -0,0 +1,68 @@ +package com.baeldung.algorithms.reversingtree; + +import java.util.LinkedList; + +public class TreeReverser { + + public TreeNode createBinaryTree() { + + TreeNode leaf1 = new TreeNode(3); + TreeNode leaf2 = new TreeNode(1); + TreeNode leaf3 = new TreeNode(9); + TreeNode leaf4 = new TreeNode(6); + + TreeNode nodeLeft = new TreeNode(2, leaf1, leaf2); + TreeNode nodeRight = new TreeNode(7, leaf3, leaf4); + + TreeNode root = new TreeNode(4, nodeRight, nodeLeft); + + return root; + } + + public void reverseRecursive(TreeNode treeNode) { + if (treeNode == null) { + return; + } + + TreeNode temp = treeNode.getLeftChild(); + treeNode.setLeftChild(treeNode.getRightChild()); + treeNode.setRightChild(temp); + + reverseRecursive(treeNode.getLeftChild()); + reverseRecursive(treeNode.getRightChild()); + } + + public void reverseIterative(TreeNode treeNode) { + LinkedList queue = new LinkedList(); + + if (treeNode != null) { + queue.add(treeNode); + } + + while (!queue.isEmpty()) { + + TreeNode node = queue.poll(); + if (node.getLeftChild() != null) + queue.add(node.getLeftChild()); + if (node.getRightChild() != null) + queue.add(node.getRightChild()); + + TreeNode temp = node.getLeftChild(); + node.setLeftChild(node.getRightChild()); + node.setRightChild(temp); + } + } + + public String toString(TreeNode root) { + if (root == null) { + return ""; + } + + StringBuffer buffer = new StringBuffer(String.valueOf(root.getValue())).append(" "); + + buffer.append(toString(root.getLeftChild())); + buffer.append(toString(root.getRightChild())); + + return buffer.toString(); + } +} diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/relativelyprime/RelativelyPrimeUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/relativelyprime/RelativelyPrimeUnitTest.java new file mode 100644 index 0000000000..84bb2620af --- /dev/null +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/relativelyprime/RelativelyPrimeUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.algorithms.relativelyprime; + +import org.junit.Test; + +import static com.baeldung.algorithms.relativelyprime.RelativelyPrime.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class RelativelyPrimeUnitTest { + + @Test + public void givenNonRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnFalse() { + + boolean result = iterativeRelativelyPrime(45, 35); + assertThat(result).isFalse(); + } + + @Test + public void givenRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnTrue() { + + boolean result = iterativeRelativelyPrime(500, 501); + assertThat(result).isTrue(); + } + + @Test + public void givenNonRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnFalse() { + + boolean result = recursiveRelativelyPrime(45, 35); + assertThat(result).isFalse(); + } + + @Test + public void givenRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnTrue() { + + boolean result = recursiveRelativelyPrime(500, 501); + assertThat(result).isTrue(); + } + + @Test + public void givenNonRelativelyPrimeNumbers_whenCheckingUsingBigIntegers_shouldReturnFalse() { + + boolean result = bigIntegerRelativelyPrime(45, 35); + assertThat(result).isFalse(); + } + + @Test + public void givenRelativelyPrimeNumbers_whenCheckingBigIntegers_shouldReturnTrue() { + + boolean result = bigIntegerRelativelyPrime(500, 501); + assertThat(result).isTrue(); + } +} diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java new file mode 100644 index 0000000000..cbc265fae1 --- /dev/null +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.algorithms.reversingtree; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class TreeReverserUnitTest { + + @Test + public void givenTreeWhenReversingRecursivelyThenReversed() { + TreeReverser reverser = new TreeReverser(); + + TreeNode treeNode = reverser.createBinaryTree(); + + reverser.reverseRecursive(treeNode); + + assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode) + .trim()); + } + + @Test + public void givenTreeWhenReversingIterativelyThenReversed() { + TreeReverser reverser = new TreeReverser(); + + TreeNode treeNode = reverser.createBinaryTree(); + + reverser.reverseIterative(treeNode); + + assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode) + .trim()); + } + +} diff --git a/apache-fop/README.md b/apache-fop/README.md index 772681ad57..1e734a5f36 100644 --- a/apache-fop/README.md +++ b/apache-fop/README.md @@ -3,7 +3,3 @@ ## Core Java Cookbooks and Examples ### Relevant Articles: -- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list) -- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file) -- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string) - diff --git a/cloud-foundry-uaa/cf-uaa-config/uaa.yml b/cloud-foundry-uaa/cf-uaa-config/uaa.yml new file mode 100644 index 0000000000..ebaa99fb6c --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-config/uaa.yml @@ -0,0 +1,68 @@ +issuer: + uri: http://localhost:8080/uaa + +spring_profiles: default,hsqldb + +encryption: + active_key_label: CHANGE-THIS-KEY + encryption_keys: + - label: CHANGE-THIS-KEY + passphrase: CHANGEME + +login: + serviceProviderKey: | + -----BEGIN RSA PRIVATE KEY----- + MIICXQIBAAKBgQDHtC5gUXxBKpEqZTLkNvFwNGnNIkggNOwOQVNbpO0WVHIivig5 + L39WqS9u0hnA+O7MCA/KlrAR4bXaeVVhwfUPYBKIpaaTWFQR5cTR1UFZJL/OF9vA + fpOwznoD66DDCnQVpbCjtDYWX+x6imxn8HCYxhMol6ZnTbSsFW6VZjFMjQIDAQAB + AoGAVOj2Yvuigi6wJD99AO2fgF64sYCm/BKkX3dFEw0vxTPIh58kiRP554Xt5ges + 7ZCqL9QpqrChUikO4kJ+nB8Uq2AvaZHbpCEUmbip06IlgdA440o0r0CPo1mgNxGu + lhiWRN43Lruzfh9qKPhleg2dvyFGQxy5Gk6KW/t8IS4x4r0CQQD/dceBA+Ndj3Xp + ubHfxqNz4GTOxndc/AXAowPGpge2zpgIc7f50t8OHhG6XhsfJ0wyQEEvodDhZPYX + kKBnXNHzAkEAyCA76vAwuxqAd3MObhiebniAU3SnPf2u4fdL1EOm92dyFs1JxyyL + gu/DsjPjx6tRtn4YAalxCzmAMXFSb1qHfwJBAM3qx3z0gGKbUEWtPHcP7BNsrnWK + vw6By7VC8bk/ffpaP2yYspS66Le9fzbFwoDzMVVUO/dELVZyBnhqSRHoXQcCQQCe + A2WL8S5o7Vn19rC0GVgu3ZJlUrwiZEVLQdlrticFPXaFrn3Md82ICww3jmURaKHS + N+l4lnMda79eSp3OMmq9AkA0p79BvYsLshUJJnvbk76pCjR28PK4dV1gSDUEqQMB + qy45ptdwJLqLJCeNoR0JUcDNIRhOCuOPND7pcMtX6hI/ + -----END RSA PRIVATE KEY----- + serviceProviderKeyPassword: password + serviceProviderCertificate: | + -----BEGIN CERTIFICATE----- + MIIDSTCCArKgAwIBAgIBADANBgkqhkiG9w0BAQQFADB8MQswCQYDVQQGEwJhdzEO + MAwGA1UECBMFYXJ1YmExDjAMBgNVBAoTBWFydWJhMQ4wDAYDVQQHEwVhcnViYTEO + MAwGA1UECxMFYXJ1YmExDjAMBgNVBAMTBWFydWJhMR0wGwYJKoZIhvcNAQkBFg5h + cnViYUBhcnViYS5hcjAeFw0xNTExMjAyMjI2MjdaFw0xNjExMTkyMjI2MjdaMHwx + CzAJBgNVBAYTAmF3MQ4wDAYDVQQIEwVhcnViYTEOMAwGA1UEChMFYXJ1YmExDjAM + BgNVBAcTBWFydWJhMQ4wDAYDVQQLEwVhcnViYTEOMAwGA1UEAxMFYXJ1YmExHTAb + BgkqhkiG9w0BCQEWDmFydWJhQGFydWJhLmFyMIGfMA0GCSqGSIb3DQEBAQUAA4GN + ADCBiQKBgQDHtC5gUXxBKpEqZTLkNvFwNGnNIkggNOwOQVNbpO0WVHIivig5L39W + qS9u0hnA+O7MCA/KlrAR4bXaeVVhwfUPYBKIpaaTWFQR5cTR1UFZJL/OF9vAfpOw + znoD66DDCnQVpbCjtDYWX+x6imxn8HCYxhMol6ZnTbSsFW6VZjFMjQIDAQABo4Ha + MIHXMB0GA1UdDgQWBBTx0lDzjH/iOBnOSQaSEWQLx1syGDCBpwYDVR0jBIGfMIGc + gBTx0lDzjH/iOBnOSQaSEWQLx1syGKGBgKR+MHwxCzAJBgNVBAYTAmF3MQ4wDAYD + VQQIEwVhcnViYTEOMAwGA1UEChMFYXJ1YmExDjAMBgNVBAcTBWFydWJhMQ4wDAYD + VQQLEwVhcnViYTEOMAwGA1UEAxMFYXJ1YmExHTAbBgkqhkiG9w0BCQEWDmFydWJh + QGFydWJhLmFyggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAYvBJ + 0HOZbbHClXmGUjGs+GS+xC1FO/am2suCSYqNB9dyMXfOWiJ1+TLJk+o/YZt8vuxC + KdcZYgl4l/L6PxJ982SRhc83ZW2dkAZI4M0/Ud3oePe84k8jm3A7EvH5wi5hvCkK + RpuRBwn3Ei+jCRouxTbzKPsuCVB+1sNyxMTXzf0= + -----END CERTIFICATE----- + +#The secret that an external login server will use to authenticate to the uaa using the id `login` +LOGIN_SECRET: loginsecret + +jwt: + token: + signing-key: | + -----BEGIN RSA PRIVATE KEY----- + MIIEpAIBAAKCAQEAqUeygEfDGxI6c1VDQ6xIyUSLrP6iz1y97iHFbtXSxXaArL4a + ... + v6Mtt5LcRAAVP7pemunTdju4h8Q/noKYlVDVL30uLYUfKBL4UKfOBw== + -----END RSA PRIVATE KEY----- + verification-key: | + -----BEGIN PUBLIC KEY----- + MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqUeygEfDGxI6c1VDQ6xI + ... + AwIDAQAB + -----END PUBLIC KEY----- diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml new file mode 100644 index 0000000000..8e31cc41fb --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.3.RELEASE + + + com.example + cf-uaa-oauth2-client + 0.0.1-SNAPSHOT + uaa-client-webapp + Demo project for Spring Boot + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-oauth2-client + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java new file mode 100644 index 0000000000..c9e81fcd5d --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.cfuaa.oauth2.client; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CFUAAOAuth2ClientApplication { + + public static void main(String[] args) { + SpringApplication.run(CFUAAOAuth2ClientApplication.class, args); + } + +} diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java new file mode 100644 index 0000000000..b1631ed327 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java @@ -0,0 +1,80 @@ +package com.baeldung.cfuaa.oauth2.client; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; +import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; + +@RestController +public class CFUAAOAuth2ClientController { + + @Value("${resource.server.url}") + private String remoteResourceServer; + + private RestTemplate restTemplate; + + private OAuth2AuthorizedClientService authorizedClientService; + + public CFUAAOAuth2ClientController(OAuth2AuthorizedClientService authorizedClientService) { + this.authorizedClientService = authorizedClientService; + this.restTemplate = new RestTemplate(); + } + + @RequestMapping("/") + public String index(OAuth2AuthenticationToken authenticationToken) { + OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName()); + OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken(); + + String response = "Hello, " + authenticationToken.getPrincipal().getName(); + response += "

"; + response += "Here is your accees token :
" + oAuth2AccessToken.getTokenValue(); + response += "
"; + response += "
You can use it to call these Resource Server APIs:"; + response += "

"; + response += "Call Resource Server Read API"; + response += "
"; + response += "Call Resource Server Write API"; + return response; + } + + @RequestMapping("/read") + public String read(OAuth2AuthenticationToken authenticationToken) { + String url = remoteResourceServer + "/read"; + return callResourceServer(authenticationToken, url); + } + + @RequestMapping("/write") + public String write(OAuth2AuthenticationToken authenticationToken) { + String url = remoteResourceServer + "/write"; + return callResourceServer(authenticationToken, url); + } + + private String callResourceServer(OAuth2AuthenticationToken authenticationToken, String url) { + OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName()); + OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken(); + + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Bearer " + oAuth2AccessToken.getTokenValue()); + + HttpEntity entity = new HttpEntity<>("parameters", headers); + ResponseEntity responseEntity = null; + + String response = null; + try { + responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); + response = responseEntity.getBody(); + } catch (HttpClientErrorException e) { + response = e.getMessage(); + } + return response; + } +} \ No newline at end of file diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/application.properties b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/application.properties new file mode 100644 index 0000000000..8e8797ce54 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/application.properties @@ -0,0 +1,11 @@ +server.port=8081 + +resource.server.url=http://localhost:8082 + +spring.security.oauth2.client.registration.uaa.client-name=Web App Client +spring.security.oauth2.client.registration.uaa.client-id=webappclient +spring.security.oauth2.client.registration.uaa.client-secret=webappclientsecret +spring.security.oauth2.client.registration.uaa.scope=resource.read,resource.write,openid,profile + +spring.security.oauth2.client.provider.uaa.issuer-uri=http://localhost:8080/uaa/oauth/token + diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/templates/index.html b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/templates/index.html new file mode 100644 index 0000000000..eb6e267b94 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/templates/index.html @@ -0,0 +1 @@ +tintin \ No newline at end of file diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml new file mode 100644 index 0000000000..9cf8993cd2 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.3.RELEASE + + + com.baeldung.cfuaa + cf-uaa-oauth2-resource-server + 0.0.1-SNAPSHOT + cf-uaa-oauth2-resource-server + Demo project for Spring Boot + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + org.springframework.boot + spring-boot-starter-web + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java new file mode 100644 index 0000000000..51ad6e938d --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.cfuaa.oauth2.resourceserver; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CFUAAOAuth2ResourceServerApplication { + + public static void main(String[] args) { + SpringApplication.run(CFUAAOAuth2ResourceServerApplication.class, args); + } + +} diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java new file mode 100644 index 0000000000..c08f17d8d8 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java @@ -0,0 +1,28 @@ +package com.baeldung.cfuaa.oauth2.resourceserver; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.security.Principal; + +@RestController +public class CFUAAOAuth2ResourceServerRestController { + + @GetMapping("/") + public String index(@AuthenticationPrincipal Jwt jwt) { + return String.format("Hello, %s!", jwt.getSubject()); + } + + @GetMapping("/read") + public String read(JwtAuthenticationToken jwtAuthenticationToken) { + return "Hello write: " + jwtAuthenticationToken.getTokenAttributes(); + } + + @GetMapping("/write") + public String write(Principal principal) { + return "Hello write: " + principal.getName(); + } +} diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java new file mode 100644 index 0000000000..d04d51cda3 --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java @@ -0,0 +1,21 @@ +package com.baeldung.cfuaa.oauth2.resourceserver; + +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@EnableWebSecurity +public class CFUAAOAuth2ResourceServerSecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/read/**").hasAuthority("SCOPE_resource.read") + .antMatchers("/write/**").hasAuthority("SCOPE_resource.write") + .anyRequest().authenticated() + .and() + .oauth2ResourceServer() + .jwt(); + } +} \ No newline at end of file diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/resources/application.properties b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/resources/application.properties new file mode 100644 index 0000000000..a6e846a00f --- /dev/null +++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8082 + +spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/uaa/oauth/token diff --git a/core-groovy/README.md b/core-groovy/README.md index ec2fcfa574..606a317747 100644 --- a/core-groovy/README.md +++ b/core-groovy/README.md @@ -8,3 +8,6 @@ - [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings) - [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating) - [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits) +- [Lists in Groovy](https://www.baeldung.com/groovy-lists) +- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date) +- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io) diff --git a/core-groovy/src/main/groovy/com/baeldung/Person.groovy b/core-groovy/src/main/groovy/com/baeldung/Person.groovy new file mode 100644 index 0000000000..6a009aeee0 --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/Person.groovy @@ -0,0 +1,37 @@ +package com.baeldung + +class Person { + private String firstname + private String lastname + private Integer age + + Person(String firstname, String lastname, Integer age) { + this.firstname = firstname + this.lastname = lastname + this.age = age + } + + String getFirstname() { + return firstname + } + + void setFirstname(String firstname) { + this.firstname = firstname + } + + String getLastname() { + return lastname + } + + void setLastname(String lastname) { + this.lastname = lastname + } + + Integer getAge() { + return age + } + + void setAge(Integer age) { + this.age = age + } +} diff --git a/core-groovy/src/main/groovy/com/baeldung/closures/Closures.groovy b/core-groovy/src/main/groovy/com/baeldung/closures/Closures.groovy new file mode 100644 index 0000000000..607329ce88 --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/closures/Closures.groovy @@ -0,0 +1,87 @@ +package com.baeldung.closures + +class Closures { + + def printWelcome = { + println "Welcome to Closures!" + } + + def print = { name -> + println name + } + + def formatToLowerCase(name) { + return name.toLowerCase() + } + def formatToLowerCaseClosure = { name -> + return name.toLowerCase() + } + + def count=0 + + def increaseCount = { + count++ + } + + def greet = { + return "Hello! ${it}" + } + + def multiply = { x, y -> + return x*y + } + + def calculate = {int x, int y, String operation -> + + //log closure + def log = { + println "Performing $it" + } + + def result = 0 + switch(operation) { + case "ADD": + log("Addition") + result = x+y + break + case "SUB": + log("Subtraction") + result = x-y + break + case "MUL": + log("Multiplication") + result = x*y + break + case "DIV": + log("Division") + result = x/y + break + } + return result + } + + def addAll = { int... args -> + return args.sum() + } + + def volume(Closure areaCalculator, int... dimensions) { + if(dimensions.size() == 3) { + + //consider dimension[0] = length, dimension[1] = breadth, dimension[2] = height + //for cube and cuboid + return areaCalculator(dimensions[0], dimensions[1]) * dimensions[2] + } else if(dimensions.size() == 2) { + + //consider dimension[0] = radius, dimension[1] = height + //for cylinder and cone + return areaCalculator(dimensions[0]) * dimensions[1] + } else if(dimensions.size() == 1) { + + //consider dimension[0] = radius + //for sphere + return areaCalculator(dimensions[0]) * dimensions[0] + } + + } + +} \ No newline at end of file diff --git a/core-groovy/src/main/groovy/com/baeldung/closures/Employee.groovy b/core-groovy/src/main/groovy/com/baeldung/closures/Employee.groovy new file mode 100644 index 0000000000..78eb5aadeb --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/closures/Employee.groovy @@ -0,0 +1,6 @@ +package com.baeldung.closures + +class Employee { + + String fullName +} \ No newline at end of file diff --git a/core-groovy/src/test/groovy/com/baeldung/closures/ClosuresUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/closures/ClosuresUnitTest.groovy new file mode 100644 index 0000000000..32c67e99bc --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/closures/ClosuresUnitTest.groovy @@ -0,0 +1,80 @@ +package com.baeldung.closures + +import spock.lang.Specification + +class ClosuresUnitTest extends GroovyTestCase { + + Closures closures = new Closures() + + void testDeclaration() { + + closures.print("Hello! Closure") + closures.formatToLowerCaseClosure("Hello! Closure") + + closures.print.call("Hello! Closure") + closures.formatToLowerCaseClosure.call("Hello! Closure") + + } + + void testClosureVsMethods() { + assert closures.formatToLowerCase("TONY STARK") == closures.formatToLowerCaseClosure("Tony STark") + } + + void testParameters() { + //implicit parameter + assert closures.greet("Alex") == "Hello! Alex" + + //multiple parameters + assert closures.multiply(2, 4) == 8 + + assert closures.calculate(12, 4, "ADD") == 16 + assert closures.calculate(12, 4, "SUB") == 8 + assert closures.calculate(43, 8, "DIV") == 5.375 + + //varags + assert closures.addAll(12, 10, 14) == 36 + + } + + void testClosureAsAnArgument() { + assert closures.volume({ l, b -> return l*b }, 12, 6, 10) == 720 + + assert closures.volume({ radius -> return Math.PI*radius*radius/3 }, 5, 10) == Math.PI * 250/3 + } + + void testGStringsLazyEvaluation() { + def name = "Samwell" + def welcomeMsg = "Welcome! $name" + + assert welcomeMsg == "Welcome! Samwell" + + // changing the name does not affect original interpolated value + name = "Tarly" + assert welcomeMsg != "Welcome! Tarly" + + def fullName = "Tarly Samson" + def greetStr = "Hello! ${-> fullName}" + + assert greetStr == "Hello! Tarly Samson" + + // this time changing the variable affects the interpolated String's value + fullName = "Jon Smith" + assert greetStr == "Hello! Jon Smith" + } + + void testClosureInLists() { + def list = [10, 11, 12, 13, 14, true, false, "BUNTHER"] + list.each { + println it + } + + assert [13, 14] == list.findAll{ it instanceof Integer && it >= 13} + } + + void testClosureInMaps() { + def map = [1:10, 2:30, 4:5] + + assert [10, 60, 20] == map.collect{it.key * it.value} + } + +} \ No newline at end of file diff --git a/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy b/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy index f682503ed4..7771028132 100644 --- a/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy @@ -129,13 +129,13 @@ class ListTest{ assertTrue(filterList.findAll{it > 3} == [4, 5, 6, 76]) assertTrue(filterList.findAll{ it instanceof Number} == [2, 1, 3, 4, 5, 6, 76]) - + assertTrue(filterList.grep( Number )== [2, 1, 3, 4, 5, 6, 76]) - + assertTrue(filterList.grep{ it> 6 }== [76]) def conditionList = [2, 1, 3, 4, 5, 6, 76] - + assertFalse(conditionList.every{ it < 6}) assertTrue(conditionList.any{ it%2 == 0}) @@ -165,7 +165,7 @@ class ListTest{ def strList = ["na", "ppp", "as"] assertTrue(strList.max() == "ppp") - + Comparator minc = {a,b -> a == b? 0: a < b? -1 : 1} def numberList = [3, 2, 0, 7] assertTrue(numberList.min(minc) == 0) diff --git a/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy new file mode 100644 index 0000000000..9617c099ce --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy @@ -0,0 +1,58 @@ +package com.baeldung.lists + +import com.baeldung.Person +import org.junit.Test + +import static org.junit.Assert.* + +class ListUnitTest { + + private final personList = [ + new Person("Regina", "Fitzpatrick", 25), + new Person("Abagail", "Ballard", 26), + new Person("Lucian", "Walter", 30), + ] + + @Test + void whenListContainsElement_thenCheckReturnsTrue() { + def list = ['a', 'b', 'c'] + + assertTrue(list.indexOf('a') > -1) + assertTrue(list.contains('a')) + } + + @Test + void whenListContainsElement_thenCheckWithMembershipOperatorReturnsTrue() { + def list = ['a', 'b', 'c'] + + assertTrue('a' in list) + } + + @Test + void givenListOfPerson_whenUsingStreamMatching_thenShouldEvaluateList() { + assertTrue(personList.stream().anyMatch {it.age > 20}) + assertFalse(personList.stream().allMatch {it.age < 30}) + } + + @Test + void givenListOfPerson_whenUsingCollectionMatching_thenShouldEvaluateList() { + assertTrue(personList.any {it.age > 20}) + assertFalse(personList.every {it.age < 30}) + } + + @Test + void givenListOfPerson_whenUsingStreamFind_thenShouldReturnMatchingElements() { + assertTrue(personList.stream().filter {it.age > 20}.findAny().isPresent()) + assertFalse(personList.stream().filter {it.age > 30}.findAny().isPresent()) + assertTrue(personList.stream().filter {it.age > 20}.findAll().size() == 3) + assertTrue(personList.stream().filter {it.age > 30}.findAll().isEmpty()) + } + + @Test + void givenListOfPerson_whenUsingCollectionFind_thenShouldReturnMatchingElements() { + assertNotNull(personList.find {it.age > 20}) + assertNull(personList.find {it.age > 30}) + assertTrue(personList.findAll {it.age > 20}.size() == 3) + assertTrue(personList.findAll {it.age > 30}.isEmpty()) + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy index 97ffc50c76..0d6bbed04b 100644 --- a/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy @@ -1,10 +1,18 @@ package com.baeldung.map -import static org.junit.Assert.* +import com.baeldung.Person import org.junit.Test +import static org.junit.Assert.* + class MapUnitTest { + private final personMap = [ + Regina : new Person("Regina", "Fitzpatrick", 25), + Abagail: new Person("Abagail", "Ballard", 26), + Lucian : new Person("Lucian", "Walter", 30) + ] + @Test void whenUsingEach_thenMapIsIterated() { def map = [ @@ -63,7 +71,7 @@ class MapUnitTest { 'FF6347' : 'Tomato', 'FF4500' : 'Orange Red' ] - + map.eachWithIndex { key, val, index -> def indent = ((index == 0 || index % 2 == 0) ? " " : "") println "$indent Hex Code: $key = Color Name: $val" @@ -82,4 +90,65 @@ class MapUnitTest { println "Hex Code: $entry.key = Color Name: $entry.value" } } + + @Test + void whenMapContainsKeyElement_thenCheckReturnsTrue() { + def map = [a: 'd', b: 'e', c: 'f'] + + assertTrue(map.containsKey('a')) + assertFalse(map.containsKey('e')) + assertTrue(map.containsValue('e')) + } + + @Test + void whenMapContainsKeyElement_thenCheckByMembershipReturnsTrue() { + def map = [a: 'd', b: 'e', c: 'f'] + + assertTrue('a' in map) + assertFalse('f' in map) + } + + @Test + void whenMapContainsFalseBooleanValues_thenCheckReturnsFalse() { + def map = [a: true, b: false, c: null] + + assertTrue(map.containsKey('b')) + assertTrue('a' in map) + assertFalse('b' in map) + assertFalse('c' in map) + } + + @Test + void givenMapOfPerson_whenUsingStreamMatching_thenShouldEvaluateMap() { + assertTrue(personMap.keySet().stream().anyMatch {it == "Regina"}) + assertFalse(personMap.keySet().stream().allMatch {it == "Albert"}) + assertFalse(personMap.values().stream().allMatch {it.age < 30}) + assertTrue(personMap.entrySet().stream().anyMatch {it.key == "Abagail" && it.value.lastname == "Ballard"}) + } + + @Test + void givenMapOfPerson_whenUsingCollectionMatching_thenShouldEvaluateMap() { + assertTrue(personMap.keySet().any {it == "Regina"}) + assertFalse(personMap.keySet().every {it == "Albert"}) + assertFalse(personMap.values().every {it.age < 30}) + assertTrue(personMap.any {firstname, person -> firstname == "Abagail" && person.lastname == "Ballard"}) + } + + @Test + void givenMapOfPerson_whenUsingCollectionFind_thenShouldReturnElements() { + assertNotNull(personMap.find {it.key == "Abagail" && it.value.lastname == "Ballard"}) + assertTrue(personMap.findAll {it.value.age > 20}.size() == 3) + } + + @Test + void givenMapOfPerson_whenUsingStreamFind_thenShouldReturnElements() { + assertTrue( + personMap.entrySet().stream() + .filter {it.key == "Abagail" && it.value.lastname == "Ballard"} + .findAny().isPresent()) + assertTrue( + personMap.entrySet().stream() + .filter {it.value.age > 20} + .findAll().size() == 3) + } } diff --git a/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy new file mode 100644 index 0000000000..1248c9ac91 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy @@ -0,0 +1,16 @@ +package com.baeldung.set + +import org.junit.Test + +import static org.junit.Assert.assertTrue + +class SetUnitTest { + + @Test + void whenSetContainsElement_thenCheckReturnsTrue() { + def set = ['a', 'b', 'c'] as Set + + assertTrue(set.contains('a')) + assertTrue('a' in set) + } +} \ No newline at end of file diff --git a/core-java-11/README.md b/core-java-11/README.md index 3c8b94fa28..b09649f4f1 100644 --- a/core-java-11/README.md +++ b/core-java-11/README.md @@ -4,3 +4,5 @@ - [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params) - [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api) - [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control) +- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client) +- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector) diff --git a/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java b/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java new file mode 100644 index 0000000000..47fe62ba40 --- /dev/null +++ b/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java @@ -0,0 +1,12 @@ +package com.baeldung.jlink; + +import java.util.logging.Logger; + +public class HelloWorld { + + private static final Logger LOG = Logger.getLogger(HelloWorld.class.getName()); + + public static void main(String[] args) { + LOG.info("Hello World!"); + } +} diff --git a/core-java-11/src/modules/jlinkModule/module-info.java b/core-java-11/src/modules/jlinkModule/module-info.java new file mode 100644 index 0000000000..0587c65b53 --- /dev/null +++ b/core-java-11/src/modules/jlinkModule/module-info.java @@ -0,0 +1,3 @@ +module jlinkModule { + requires java.logging; +} \ No newline at end of file diff --git a/core-java-12/pom.xml b/core-java-12/pom.xml new file mode 100644 index 0000000000..defef5e9d3 --- /dev/null +++ b/core-java-12/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + com.baeldung + core-java-12 + 0.1.0-SNAPSHOT + core-java-12 + jar + http://maven.apache.org + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + + + + + 12 + 12 + 3.6.1 + + + \ No newline at end of file diff --git a/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java b/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java new file mode 100644 index 0000000000..7c4cb9e8f0 --- /dev/null +++ b/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java @@ -0,0 +1,71 @@ +package com.baeldung.collectors; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +import org.junit.Test; + +import static java.util.stream.Collectors.maxBy; +import static java.util.stream.Collectors.minBy; +import static java.util.stream.Collectors.teeing; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Unit tests for collectors additions in Java 12. + */ +public class CollectorsUnitTest { + + @Test + public void whenTeeing_ItShouldCombineTheResultsAsExpected() { + List numbers = Arrays.asList(42, 4, 2, 24); + Range range = numbers.stream() + .collect(teeing(minBy(Integer::compareTo), maxBy(Integer::compareTo), (min, max) -> new Range(min.orElse(null), max.orElse(null)))); + + assertThat(range).isEqualTo(new Range(2, 42)); + } + + /** + * Represents a closed range of numbers between {@link #min} and + * {@link #max}, both inclusive. + */ + private static class Range { + + private final Integer min; + + private final Integer max; + + Range(Integer min, Integer max) { + this.min = min; + this.max = max; + } + + Integer getMin() { + return min; + } + + Integer getMax() { + return max; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Range range = (Range) o; + return Objects.equals(getMin(), range.getMin()) && Objects.equals(getMax(), range.getMax()); + } + + @Override + public int hashCode() { + return Objects.hash(getMin(), getMax()); + } + + @Override + public String toString() { + return "Range{" + "min=" + min + ", max=" + max + '}'; + } + } +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index 71ec5b147f..57d9d8347b 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -124,11 +124,44 @@ public class Java8SortUnitTest { @Test public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { - final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); final Comparator nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName()); final List sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList()); Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12))); } + + @Test + public final void givenStreamComparatorOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { + final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); + + final List sortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName)).collect(Collectors.toList()); + Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12))); + } + + @Test + public final void givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { + final List letters = Lists.newArrayList("B", "A", "C"); + + final List reverseSortedLetters = letters.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()); + Assert.assertThat(reverseSortedLetters.get(0), equalTo("C")); + } + + @Test + public final void givenStreamCustomOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { + final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); + final Comparator reverseNameComparator = (h1, h2) -> h2.getName().compareTo(h1.getName()); + + final List reverseSortedHumans = humans.stream().sorted(reverseNameComparator).collect(Collectors.toList()); + Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10))); + } + + @Test + public final void givenStreamComparatorOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() { + final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); + + final List reverseSortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder())).collect(Collectors.toList()); + Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10))); + } + } diff --git a/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java new file mode 100644 index 0000000000..70ec324cb3 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java @@ -0,0 +1,110 @@ +package com.baeldung.java8.optional; + +import org.junit.Before; +import org.junit.Test; + +import java.util.Optional; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static org.junit.Assert.*; + +public class OptionalChainingUnitTest { + + private boolean getEmptyEvaluated; + private boolean getHelloEvaluated; + private boolean getByeEvaluated; + + @Before + public void setUp() { + getEmptyEvaluated = false; + getHelloEvaluated = false; + getByeEvaluated = false; + } + + @Test + public void givenThreeOptionals_whenChaining_thenFirstNonEmptyIsReturned() { + Optional found = Stream.of(getEmpty(), getHello(), getBye()) + .filter(Optional::isPresent) + .map(Optional::get) + .findFirst(); + + assertEquals(getHello(), found); + } + + @Test + public void givenTwoEmptyOptionals_whenChaining_thenEmptyOptionalIsReturned() { + Optional found = Stream.of(getEmpty(), getEmpty()) + .filter(Optional::isPresent) + .map(Optional::get) + .findFirst(); + + assertFalse(found.isPresent()); + } + + @Test + public void givenTwoEmptyOptionals_whenChaining_thenDefaultIsReturned() { + String found = Stream.>>of( + () -> createOptional("empty"), + () -> createOptional("empty") + ) + .map(Supplier::get) + .filter(Optional::isPresent) + .map(Optional::get) + .findFirst() + .orElseGet(() -> "default"); + + assertEquals("default", found); + } + + @Test + public void givenThreeOptionals_whenChaining_thenFirstNonEmptyIsReturnedAndRestNotEvaluated() { + Optional found = Stream.>>of(this::getEmpty, this::getHello, this::getBye) + .map(Supplier::get) + .filter(Optional::isPresent) + .map(Optional::get) + .findFirst(); + + assertTrue(this.getEmptyEvaluated); + assertTrue(this.getHelloEvaluated); + assertFalse(this.getByeEvaluated); + assertEquals(getHello(), found); + } + + @Test + public void givenTwoOptionalsReturnedByOneArgMethod_whenChaining_thenFirstNonEmptyIsReturned() { + Optional found = Stream.>>of( + () -> createOptional("empty"), + () -> createOptional("hello") + ) + .map(Supplier::get) + .filter(Optional::isPresent) + .map(Optional::get) + .findFirst(); + + assertEquals(createOptional("hello"), found); + } + + private Optional getEmpty() { + this.getEmptyEvaluated = true; + return Optional.empty(); + } + + private Optional getHello() { + this.getHelloEvaluated = true; + return Optional.of("hello"); + } + + private Optional getBye() { + this.getByeEvaluated = true; + return Optional.of("bye"); + } + + private Optional createOptional(String input) { + if (input == null || input == "" || input == "empty") { + return Optional.empty(); + } + + return Optional.of(input); + } +} \ No newline at end of file diff --git a/core-java-9/README.md b/core-java-9/README.md index 224306db19..a423f0cb14 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -9,7 +9,6 @@ - [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods) - [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors) - [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture) -- [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 Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) - [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional) @@ -25,7 +24,9 @@ - [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) - [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) -- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) - [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) - [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar) - [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation) +- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api) +- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) + diff --git a/core-java-collections-list/README.md b/core-java-collections-list/README.md index c5139074e9..bfe06581c0 100644 --- a/core-java-collections-list/README.md +++ b/core-java-collections-list/README.md @@ -30,3 +30,4 @@ - [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal) - [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int) - [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance) +- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list) diff --git a/core-java-collections/README.md b/core-java-collections/README.md index 80d4385c45..1e504ded65 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -33,3 +33,4 @@ - [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences) - [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector) - [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack) +- [Time Comparison of Arrays.sort(Object[]) and Arrays.sort(int[])](https://www.baeldung.com/arrays-sortobject-vs-sortint) diff --git a/core-java-concurrency-advanced/README.md b/core-java-concurrency-advanced/README.md index bcbec9d687..f48fd30c73 100644 --- a/core-java-concurrency-advanced/README.md +++ b/core-java-concurrency-advanced/README.md @@ -21,4 +21,5 @@ - [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch) - [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) - [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random) -- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join) \ No newline at end of file +- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join) +- [Passing Parameters to Java Threads](https://www.baeldung.com/java-thread-parameters) diff --git a/core-java-concurrency-basic/README.md b/core-java-concurrency-basic/README.md index ad3de4a758..7d106095e7 100644 --- a/core-java-concurrency-basic/README.md +++ b/core-java-concurrency-basic/README.md @@ -16,3 +16,4 @@ - [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle) - [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable) - [What is Thread-Safety and How to Achieve it](https://www.baeldung.com/java-thread-safety) +- [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread) diff --git a/core-java-io/README.md b/core-java-io/README.md index 5e0f7bfbd1..05b9165147 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -30,7 +30,6 @@ - [Download a File From an URL in Java](http://www.baeldung.com/java-download-file) - [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink) - [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter) -- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) - [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist) - [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream) - [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array) @@ -40,3 +39,4 @@ - [Create a Directory in Java](https://www.baeldung.com/java-create-directory) - [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv) - [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files) +- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes) diff --git a/core-java-jvm/README.md b/core-java-jvm/README.md new file mode 100644 index 0000000000..529453f3c4 --- /dev/null +++ b/core-java-jvm/README.md @@ -0,0 +1,6 @@ +========= + +## Core Java JVM Cookbooks and Examples + +### Relevant Articles: +- [Method Inlining in the JVM](http://www.baeldung.com/method-inlining-in-the-jvm/) diff --git a/core-java-jvm/pom.xml b/core-java-jvm/pom.xml new file mode 100644 index 0000000000..752b26f03f --- /dev/null +++ b/core-java-jvm/pom.xml @@ -0,0 +1,40 @@ + + 4.0.0 + com.baeldung + core-java-jvm + 0.1.0-SNAPSHOT + jar + core-java-jvm + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + junit + junit + ${junit.version} + test + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 3.5 + 3.6.1 + + diff --git a/core-java-jvm/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java b/core-java-jvm/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java new file mode 100644 index 0000000000..7de642f1c0 --- /dev/null +++ b/core-java-jvm/src/main/java/com/baeldung/inlining/ConsecutiveNumbersSum.java @@ -0,0 +1,19 @@ +package com.baeldung.inlining; + +public class ConsecutiveNumbersSum { + + private long totalSum; + private int totalNumbers; + + public ConsecutiveNumbersSum(int totalNumbers) { + this.totalNumbers = totalNumbers; + } + + public long getTotalSum() { + totalSum = 0; + for (int i = 1; i <= totalNumbers; i++) { + totalSum += i; + } + return totalSum; + } +} diff --git a/core-java-jvm/src/main/java/com/baeldung/inlining/InliningExample.java b/core-java-jvm/src/main/java/com/baeldung/inlining/InliningExample.java new file mode 100644 index 0000000000..4c1802d0e4 --- /dev/null +++ b/core-java-jvm/src/main/java/com/baeldung/inlining/InliningExample.java @@ -0,0 +1,16 @@ +package com.baeldung.inlining; + +public class InliningExample { + + public static final int NUMBERS_OF_ITERATIONS = 15000; + + public static void main(String[] args) { + for (int i = 1; i < NUMBERS_OF_ITERATIONS; i++) { + calculateSum(i); + } + } + + private static long calculateSum(int n) { + return new ConsecutiveNumbersSum(n).getTotalSum(); + } +} diff --git a/core-java-jvm/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java b/core-java-jvm/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java new file mode 100644 index 0000000000..8e4b0353e6 --- /dev/null +++ b/core-java-jvm/src/test/java/com/baeldung/inlining/ConsecutiveNumbersSumUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.inlining; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ConsecutiveNumbersSumUnitTest { + + private static final int TOTAL_NUMBERS = 10; + + @Test + public void givenTotalIntegersNumber_whenSumCalculated_thenEquals() { + ConsecutiveNumbersSum consecutiveNumbersSum = new ConsecutiveNumbersSum(TOTAL_NUMBERS); + long expectedSum = calculateExpectedSum(TOTAL_NUMBERS); + + assertEquals(expectedSum, consecutiveNumbersSum.getTotalSum()); + } + + private long calculateExpectedSum(int totalNumbers) { + return totalNumbers * (totalNumbers + 1) / 2; + } +} diff --git a/core-java-lang-oop/README.md b/core-java-lang-oop/README.md index 200415fe21..970a8d44b1 100644 --- a/core-java-lang-oop/README.md +++ b/core-java-lang-oop/README.md @@ -5,7 +5,6 @@ ### Relevant Articles: - [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode) - [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static) -- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) - [Polymorphism in Java](http://www.baeldung.com/java-polymorphism) - [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override) - [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy) diff --git a/core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md b/core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md deleted file mode 100644 index 6ccfa725f5..0000000000 --- a/core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums) diff --git a/core-java-lang-syntax/src/main/java/com/baeldung/generics/Generics.java b/core-java-lang-syntax/src/main/java/com/baeldung/generics/Generics.java index e0536ca02e..1c4082c58b 100644 --- a/core-java-lang-syntax/src/main/java/com/baeldung/generics/Generics.java +++ b/core-java-lang-syntax/src/main/java/com/baeldung/generics/Generics.java @@ -1,5 +1,6 @@ package com.baeldung.generics; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; @@ -28,4 +29,10 @@ public class Generics { buildings.forEach(Building::paint); } + public static List createList(int a) { + List list = new ArrayList<>(); + list.add(a); + return list; + } + } \ No newline at end of file diff --git a/core-java-lang-syntax/src/test/java/com/baeldung/generics/GenericsUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/generics/GenericsUnitTest.java index aca0b182a0..0bdf0afc15 100644 --- a/core-java-lang-syntax/src/test/java/com/baeldung/generics/GenericsUnitTest.java +++ b/core-java-lang-syntax/src/test/java/com/baeldung/generics/GenericsUnitTest.java @@ -6,6 +6,7 @@ import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; @@ -66,4 +67,12 @@ public class GenericsUnitTest { } } + @Test + public void givenAnInt_whenAddedToAGenericIntegerList_thenAListItemCanBeAssignedToAnInt() { + int number = 7; + List list = Generics.createList(number); + int otherNumber = list.get(0); + assertThat(otherNumber, is(number)); + } + } \ No newline at end of file diff --git a/core-java-networking/src/main/java/com/baeldung/socket/read/Client.java b/core-java-networking/src/main/java/com/baeldung/socket/read/Client.java new file mode 100644 index 0000000000..5e2a84a767 --- /dev/null +++ b/core-java-networking/src/main/java/com/baeldung/socket/read/Client.java @@ -0,0 +1,29 @@ +package com.baeldung.socket.read; + +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.io.*; + +public class Client { + + public void runClient(String ip, int port) { + try { + Socket socket = new Socket(ip, port); + System.out.println("Connected to server ..."); + DataInputStream in = new DataInputStream(System.in); + DataOutputStream out = new DataOutputStream(socket.getOutputStream()); + + char type = 's'; // s for string + int length = 29; + String data = "This is a string of length 29"; + byte[] dataInBytes = data.getBytes(StandardCharsets.UTF_8); + //Sending data in TLV format + out.writeChar(type); + out.writeInt(length); + out.write(dataInBytes); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/core-java-networking/src/main/java/com/baeldung/socket/read/Server.java b/core-java-networking/src/main/java/com/baeldung/socket/read/Server.java new file mode 100644 index 0000000000..2ab91c6cdc --- /dev/null +++ b/core-java-networking/src/main/java/com/baeldung/socket/read/Server.java @@ -0,0 +1,49 @@ +package com.baeldung.socket.read; + +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.io.*; + +public class Server { + + public void runServer(int port) { + //Start the server and wait for connection + try { + ServerSocket server = new ServerSocket(port); + System.out.println("Server Started. Waiting for connection ..."); + Socket socket = server.accept(); + System.out.println("Got connection from client."); + //Get input stream from socket variable and convert the same to DataInputStream + DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); + //Read type and length of data + char dataType = in.readChar(); + int length = in.readInt(); + System.out.println("Type : "+dataType); + System.out.println("Lenght :"+length); + if(dataType == 's') { + //Read String data in bytes + byte[] messageByte = new byte[length]; + boolean end = false; + StringBuilder dataString = new StringBuilder(length); + int totalBytesRead = 0; + //We need to run while loop, to read all data in that stream + while(!end) { + int currentBytesRead = in.read(messageByte); + totalBytesRead = currentBytesRead + totalBytesRead; + if(totalBytesRead <= length) { + dataString.append(new String(messageByte,0,currentBytesRead,StandardCharsets.UTF_8)); + } else { + dataString.append(new String(messageByte,0,length - totalBytesRead + currentBytesRead,StandardCharsets.UTF_8)); + } + if(dataString.length()>=length) { + end = true; + } + } + System.out.println("Read "+length+" bytes of message from client. Message = "+dataString); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/core-java-networking/src/test/java/com/baeldung/socket/read/SocketReadAllDataLiveTest.java b/core-java-networking/src/test/java/com/baeldung/socket/read/SocketReadAllDataLiveTest.java new file mode 100644 index 0000000000..da7f5b8d3f --- /dev/null +++ b/core-java-networking/src/test/java/com/baeldung/socket/read/SocketReadAllDataLiveTest.java @@ -0,0 +1,37 @@ +package com.baeldung.socket.read; + +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +public class SocketReadAllDataLiveTest { + + @Test + public void givenServerAndClient_whenClientSendsAndServerReceivesData_thenCorrect() { + //Run server in new thread + Runnable runnable1 = () -> { runServer(); }; + Thread thread1 = new Thread(runnable1); + thread1.start(); + //Wait for 10 seconds + try { + TimeUnit.SECONDS.sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //Run client in a new thread + Runnable runnable2 = () -> { runClient(); }; + Thread thread2 = new Thread(runnable2); + thread2.start(); + } + + public static void runServer() { + //Run Server + Server server = new Server(); + server.runServer(5555); + } + + public static void runClient() { + //Run Client + Client client = new Client(); + client.runClient("127.0.0.1", 5555); + } +} \ No newline at end of file diff --git a/core-java-os/.gitignore b/core-java-os/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/core-java-os/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-os/README.md b/core-java-os/README.md new file mode 100644 index 0000000000..5f5d373d9b --- /dev/null +++ b/core-java-os/README.md @@ -0,0 +1,10 @@ +========= + +This module uses Java 9, so make sure to have the JDK 9 installed to run it. + +## +### Relevant Articles: +- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api) +- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) +- [Guide to java.lang.ProcessBuilder API](https://www.baeldung.com/java-lang-processbuilder-api) + diff --git a/core-java-os/pom.xml b/core-java-os/pom.xml new file mode 100644 index 0000000000..c9097cb554 --- /dev/null +++ b/core-java-os/pom.xml @@ -0,0 +1,82 @@ + + 4.0.0 + com.baeldung + core-java-os + 0.1.0-SNAPSHOT + core-java-os + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + core-java-os + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + 3.5 + 4.1 + 4.01 + + + 3.6.1 + 1.8.9 + 1.9 + 1.9 + 25.1-jre + + diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java b/core-java-os/src/main/java/com/baeldung/java9/process/ChildProcess.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java rename to core-java-os/src/main/java/com/baeldung/java9/process/ChildProcess.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java b/core-java-os/src/main/java/com/baeldung/java9/process/OutputStreamExample.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java rename to core-java-os/src/main/java/com/baeldung/java9/process/OutputStreamExample.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java b/core-java-os/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java similarity index 87% rename from core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java rename to core-java-os/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java index 8b6ae0b441..73eacddc4c 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java +++ b/core-java-os/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java @@ -3,5 +3,5 @@ package com.baeldung.java9.process; public class ProcessCompilationError { //This method has been written to generate error to display //how process errorStream() can consume error - public static void(); + //public static void(); } diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java b/core-java-os/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java rename to core-java-os/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java b/core-java-os/src/main/java/com/baeldung/java9/process/ProcessUtils.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java rename to core-java-os/src/main/java/com/baeldung/java9/process/ProcessUtils.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java b/core-java-os/src/main/java/com/baeldung/java9/process/ServiceMain.java similarity index 100% rename from core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java rename to core-java-os/src/main/java/com/baeldung/java9/process/ServiceMain.java diff --git a/core-java-os/src/main/resources/logback.xml b/core-java-os/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-os/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java similarity index 89% rename from core-java-9/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java rename to core-java-os/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java index 9a227a9c8f..8cefceef1d 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java +++ b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessAPIEnhancementsUnitTest.java @@ -18,13 +18,13 @@ import org.slf4j.LoggerFactory; public class ProcessAPIEnhancementsUnitTest { - Logger log = LoggerFactory.getLogger(ProcessAPIEnhancementsTest.class); + Logger log = LoggerFactory.getLogger(ProcessAPIEnhancementsUnitTest.class); @Test public void givenCurrentProcess_whenInvokeGetInfo_thenSuccess() throws IOException { ProcessHandle processHandle = ProcessHandle.current(); ProcessHandle.Info processInfo = processHandle.info(); - assertNotNull(processHandle.getPid()); + assertNotNull(processHandle.pid()); assertEquals(false, processInfo.arguments() .isPresent()); assertEquals(true, processInfo.command() @@ -51,7 +51,7 @@ public class ProcessAPIEnhancementsUnitTest { .start(); ProcessHandle processHandle = process.toHandle(); ProcessHandle.Info processInfo = processHandle.info(); - assertNotNull(processHandle.getPid()); + assertNotNull(processHandle.pid()); assertEquals(false, processInfo.arguments() .isPresent()); assertEquals(true, processInfo.command() @@ -72,7 +72,7 @@ public class ProcessAPIEnhancementsUnitTest { Stream liveProcesses = ProcessHandle.allProcesses(); liveProcesses.filter(ProcessHandle::isAlive) .forEach(ph -> { - assertNotNull(ph.getPid()); + assertNotNull(ph.pid()); assertEquals(true, ph.info() .command() .isPresent()); @@ -102,12 +102,12 @@ public class ProcessAPIEnhancementsUnitTest { Stream children = ProcessHandle.current() .children(); children.filter(ProcessHandle::isAlive) - .forEach(ph -> log.info("PID: {}, Cmd: {}", ph.getPid(), ph.info() + .forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info() .command())); Stream descendants = ProcessHandle.current() .descendants(); descendants.filter(ProcessHandle::isAlive) - .forEach(ph -> log.info("PID: {}, Cmd: {}", ph.getPid(), ph.info() + .forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info() .command())); } @@ -121,12 +121,12 @@ public class ProcessAPIEnhancementsUnitTest { .start(); ProcessHandle processHandle = process.toHandle(); - log.info("PID: {} has started", processHandle.getPid()); + log.info("PID: {} has started", processHandle.pid()); CompletableFuture onProcessExit = processHandle.onExit(); onProcessExit.get(); assertEquals(false, processHandle.isAlive()); onProcessExit.thenAccept(ph -> { - log.info("PID: {} has stopped", ph.getPid()); + log.info("PID: {} has stopped", ph.pid()); }); } diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java similarity index 85% rename from core-java-9/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java rename to core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java index e125f10da7..8bdf8cb09f 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java +++ b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java @@ -30,7 +30,7 @@ public class ProcessApiUnitTest { @Test public void processInfoExample() throws NoSuchAlgorithmException { ProcessHandle self = ProcessHandle.current(); - long PID = self.getPid(); + long PID = self.pid(); ProcessHandle.Info procInfo = self.info(); Optional args = procInfo.arguments(); Optional cmd = procInfo.commandLine(); @@ -45,7 +45,7 @@ public class ProcessApiUnitTest { Stream allProc = ProcessHandle.current().children(); allProc.forEach(p -> { - System.out.println("Proc " + p.getPid()); + System.out.println("Proc " + p.pid()); }); } @@ -54,7 +54,7 @@ public class ProcessApiUnitTest { public void createAndDestroyProcess() throws IOException, InterruptedException { int numberOfChildProcesses = 5; for (int i = 0; i < numberOfChildProcesses; i++) { - createNewJVM(ServiceMain.class, i).getPid(); + createNewJVM(ServiceMain.class, i).pid(); } Stream childProc = ProcessHandle.current().children(); @@ -62,10 +62,10 @@ public class ProcessApiUnitTest { childProc = ProcessHandle.current().children(); childProc.forEach(processHandle -> { - assertTrue("Process " + processHandle.getPid() + " should be alive!", processHandle.isAlive()); + assertTrue("Process " + processHandle.pid() + " should be alive!", processHandle.isAlive()); CompletableFuture onProcExit = processHandle.onExit(); onProcExit.thenAccept(procHandle -> { - System.out.println("Process with PID " + procHandle.getPid() + " has stopped"); + System.out.println("Process with PID " + procHandle.pid() + " has stopped"); }); }); @@ -73,14 +73,14 @@ public class ProcessApiUnitTest { childProc = ProcessHandle.current().children(); childProc.forEach(procHandle -> { - assertTrue("Could not kill process " + procHandle.getPid(), procHandle.destroy()); + assertTrue("Could not kill process " + procHandle.pid(), procHandle.destroy()); }); Thread.sleep(5000); childProc = ProcessHandle.current().children(); childProc.forEach(procHandle -> { - assertFalse("Process " + procHandle.getPid() + " should not be alive!", procHandle.isAlive()); + assertFalse("Process " + procHandle.pid() + " should not be alive!", procHandle.isAlive()); }); } diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessUnderstandingUnitTest.java similarity index 99% rename from core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java rename to core-java-os/src/test/java/com/baeldung/java9/process/ProcessUnderstandingUnitTest.java index 2c5525b9ed..6ad07c5c3a 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java +++ b/core-java-os/src/test/java/com/baeldung/java9/process/ProcessUnderstandingUnitTest.java @@ -14,7 +14,7 @@ import java.lang.Integer; import org.junit.jupiter.api.Test; -class ProcessUnderstandingTest { +class ProcessUnderstandingUnitTest { @Test public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException { diff --git a/core-java-9/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java b/core-java-os/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java similarity index 100% rename from core-java-9/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java rename to core-java-os/src/test/java/com/baeldung/processbuilder/ProcessBuilderUnitTest.java diff --git a/core-java-os/src/test/resources/.gitignore b/core-java-os/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-os/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/core-java/README.md b/core-java/README.md index 67538a3895..cbc9251b0b 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -29,7 +29,6 @@ - [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid) - [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) - [Class Loaders in Java](http://www.baeldung.com/java-classloaders) -- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) - [Guide to Java Clock Class](http://www.baeldung.com/java-clock) - [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class) - [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) @@ -51,3 +50,4 @@ - [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year) - [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) +- [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post) diff --git a/core-kotlin-2/README.md b/core-kotlin-2/README.md index 8d22c4f1a8..4ac1c2c7bb 100644 --- a/core-kotlin-2/README.md +++ b/core-kotlin-2/README.md @@ -2,3 +2,5 @@ - [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type) - [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges) +- [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) +- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison) diff --git a/core-kotlin-2/pom.xml b/core-kotlin-2/pom.xml index 81df3cee81..e329611593 100644 --- a/core-kotlin-2/pom.xml +++ b/core-kotlin-2/pom.xml @@ -13,4 +13,66 @@ ../parent-kotlin - + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + 1.8 + + + + + + + 1.2.71 + 1.1.1 + 5.2.0 + 3.10.0 + + + \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Annotations.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Annotations.kt new file mode 100644 index 0000000000..a8f83446dc --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Annotations.kt @@ -0,0 +1,7 @@ +package com.baeldung.annotations + +@Target(AnnotationTarget.FIELD) +annotation class Positive + +@Target(AnnotationTarget.FIELD) +annotation class AllowedNames(val names: Array) diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Item.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Item.kt new file mode 100644 index 0000000000..6864fe416e --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Item.kt @@ -0,0 +1,3 @@ +package com.baeldung.annotations + +class Item(@Positive val amount: Float, @AllowedNames(["Alice", "Bob"]) val name: String) \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Main.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Main.kt new file mode 100644 index 0000000000..2b7f2c5590 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Main.kt @@ -0,0 +1,7 @@ +package com.baeldung.annotations + +fun main(args: Array) { + val item = Item(amount = 1.0f, name = "Bob") + val validator = Validator() + println("Is instance valid? ${validator.isValid(item)}") +} diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Validator.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Validator.kt new file mode 100644 index 0000000000..40139048ab --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Validator.kt @@ -0,0 +1,38 @@ +package com.baeldung.annotations + +/** + * Naive annotation-based validator. + * @author A.Shcherbakov + */ +class Validator() { + + /** + * Return true if every item's property annotated with @Positive is positive and if + * every item's property annotated with @AllowedNames has a value specified in that annotation. + */ + fun isValid(item: Item): Boolean { + val fields = item::class.java.declaredFields + for (field in fields) { + field.isAccessible = true + for (annotation in field.annotations) { + val value = field.get(item) + if (field.isAnnotationPresent(Positive::class.java)) { + val amount = value as Float + if (amount < 0) { + return false + } + } + if (field.isAnnotationPresent(AllowedNames::class.java)) { + val allowedNames = field.getAnnotation(AllowedNames::class.java)?.names + val name = value as String + allowedNames?.let { + if (!it.contains(name)) { + return false + } + } + } + } + } + return true + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/CharRange.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/range/CharRange.kt new file mode 100644 index 0000000000..3151674d61 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/range/CharRange.kt @@ -0,0 +1,13 @@ +package com.baeldung.range + +fun main(args: Array) { + + for (ch in 'a'..'f') { + print(ch) + } + println() + + for (ch in 'f' downTo 'a') { + print(ch) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/Color.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/range/Color.kt new file mode 100644 index 0000000000..ef7adf06b5 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/range/Color.kt @@ -0,0 +1,21 @@ +package com.baeldung.range + +enum class Color(val rgb: Int) { + BLUE(0x0000FF), + GREEN(0x008000), + RED(0xFF0000), + MAGENTA(0xFF00FF), + YELLOW(0xFFFF00); +} + +fun main(args: Array) { + + println(Color.values().toList()); + val red = Color.RED + val yellow = Color.YELLOW + val range = red..yellow + + println(range.contains(Color.MAGENTA)) + println(range.contains(Color.BLUE)) + println(range.contains(Color.GREEN)) +} \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/CustomColor.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/range/CustomColor.kt new file mode 100644 index 0000000000..b4fed13b18 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/range/CustomColor.kt @@ -0,0 +1,56 @@ +package com.baeldung.range + +import java.lang.IllegalStateException + +class CustomColor(val rgb: Int): Comparable { + + override fun compareTo(other: CustomColor): Int { + return this.rgb.compareTo(other.rgb) + } + + operator fun rangeTo(that: CustomColor) = ColorRange(this,that) + + operator fun inc(): CustomColor { + return CustomColor(rgb + 1) + } + + init { + if(rgb < 0x000000 || rgb > 0xFFFFFF){ + throw IllegalStateException("RGB must be between 0 and 16777215") + } + } + + override fun toString(): String { + return "CustomColor(rgb=$rgb)" + } +} +class ColorRange(override val start: CustomColor, + override val endInclusive: CustomColor) : ClosedRange, Iterable{ + + override fun iterator(): Iterator { + return ColorIterator(start, endInclusive) + } +} + +class ColorIterator(val start: CustomColor, val endInclusive: CustomColor) : Iterator { + + var initValue = start + + override fun hasNext(): Boolean { + return initValue <= endInclusive + } + + override fun next(): CustomColor { + return initValue++ + } +} + +fun main(args: Array) { + val a = CustomColor(0xABCDEF) + val b = CustomColor(-1) + val c = CustomColor(0xABCDFF) + + for(color in a..c){ + println(color) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/Filter.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/range/Filter.kt new file mode 100644 index 0000000000..0e611b14cf --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/range/Filter.kt @@ -0,0 +1,18 @@ +package com.baeldung.range + +fun main(args: Array) { + val r = 1..10 + + //Apply filter + val f = r.filter { it -> it % 2 == 0 } + println(f) + + //Map + val m = r.map { it -> it * it } + println(m) + + //Reduce + val rdc = r.reduce { a, b -> a + b } + println(rdc) + +} \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/FirstLast.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/range/FirstLast.kt new file mode 100644 index 0000000000..b82f5a8b9b --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/range/FirstLast.kt @@ -0,0 +1,8 @@ +package com.baeldung.range + +fun main(args: Array) { + + println((1..9).first) + println((1..9 step 2).step) + println((3..9).reversed().last) +} \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/OtherRangeFunctions.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/range/OtherRangeFunctions.kt new file mode 100644 index 0000000000..19dcab89b2 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/range/OtherRangeFunctions.kt @@ -0,0 +1,14 @@ +package com.baeldung.range + +fun main(args: Array) { + + val r = 1..20 + println(r.min()) + println(r.max()) + println(r.sum()) + println(r.average()) + println(r.count()) + + val repeated = listOf(1, 1, 2, 4, 4, 6, 10) + println(repeated.distinct()) +} \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/Range.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/range/Range.kt new file mode 100644 index 0000000000..c313181599 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/range/Range.kt @@ -0,0 +1,28 @@ +package com.baeldung.range + +fun main(args: Array) { + + for (i in 1..9) { + print(i) + } + println() + + for (i in 9 downTo 1) { + print(i) + } + println() + + for (i in 1.rangeTo(9)) { + print(i) + } + println() + + for (i in 9.downTo(1)) { + print(i) + } + println() + + for (i in 1 until 9) { + print(i) + } +} diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/ReverseRange.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/range/ReverseRange.kt new file mode 100644 index 0000000000..875cf62200 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/range/ReverseRange.kt @@ -0,0 +1,14 @@ +package com.baeldung.range + +fun main(args: Array) { + + (1..9).reversed().forEach { + print(it) + } + + println() + + (1..9).reversed().step(3).forEach { + print(it) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/Step.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/range/Step.kt new file mode 100644 index 0000000000..b9c5d48588 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/range/Step.kt @@ -0,0 +1,15 @@ +package com.baeldung.range + +fun main(args: Array) { + + for(i in 1..9 step 2){ + print(i) + } + + println() + + for (i in 9 downTo 1 step 2){ + print(i) + } + +} \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/range/UntilRange.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/range/UntilRange.kt new file mode 100644 index 0000000000..2c116a286f --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/range/UntilRange.kt @@ -0,0 +1,8 @@ +package com.baeldung.range + +fun main(args: Array) { + + for (i in 1 until 9) { + print(i) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt new file mode 100644 index 0000000000..37ad8c65e2 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt @@ -0,0 +1,25 @@ +package com.baeldung.scope + +data class Student(var studentId: String = "", var name: String = "", var surname: String = "") { +} + +data class Teacher(var teacherId: Int = 0, var name: String = "", var surname: String = "") { + fun setId(anId: Int): Teacher = apply { teacherId = anId } + fun setName(aName: String): Teacher = apply { name = aName } + fun setSurname(aSurname: String): Teacher = apply { surname = aSurname } +} + +data class Headers(val headerInfo: String) + +data class Response(val headers: Headers) + +data class RestClient(val url: String) { + fun getResponse() = Response(Headers("some header info")) +} + +data class BankAccount(val id: Int) { + fun checkAuthorization(username: String) = Unit + fun addPayee(payee: String) = Unit + fun makePayment(paymentDetails: String) = Unit + +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt new file mode 100644 index 0000000000..5c2b6ef47f --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt @@ -0,0 +1,41 @@ +package com.baeldung.annotations + +import org.junit.Test +import kotlin.test.assertTrue +import kotlin.test.assertFalse + +class ValidationTest { + + @Test + fun whenAmountIsOneAndNameIsAlice_thenTrue() { + assertTrue(Validator().isValid(Item(1f, "Alice"))) + } + + @Test + fun whenAmountIsOneAndNameIsBob_thenTrue() { + assertTrue(Validator().isValid(Item(1f, "Bob"))) + } + + + @Test + fun whenAmountIsMinusOneAndNameIsAlice_thenFalse() { + assertFalse(Validator().isValid(Item(-1f, "Alice"))) + } + + @Test + fun whenAmountIsMinusOneAndNameIsBob_thenFalse() { + assertFalse(Validator().isValid(Item(-1f, "Bob"))) + } + + @Test + fun whenAmountIsOneAndNameIsTom_thenFalse() { + assertFalse(Validator().isValid(Item(1f, "Tom"))) + } + + @Test + fun whenAmountIsMinusOneAndNameIsTom_thenFalse() { + assertFalse(Validator().isValid(Item(-1f, "Tom"))) + } + + +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/CharRangeTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/CharRangeTest.kt new file mode 100644 index 0000000000..0e23f508b6 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/CharRangeTest.kt @@ -0,0 +1,17 @@ +package com.baeldung.range + +import org.junit.Test +import kotlin.test.assertEquals + +class CharRangeTest { + + @Test + fun testCharRange() { + assertEquals(listOf('a', 'b', 'c'), ('a'..'c').toList()) + } + + @Test + fun testCharDownRange() { + assertEquals(listOf('c', 'b', 'a'), ('c'.downTo('a')).toList()) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/ColorTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/ColorTest.kt new file mode 100644 index 0000000000..4ac3270fcc --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/ColorTest.kt @@ -0,0 +1,20 @@ +package com.baeldung.range + +import org.junit.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ColorTest { + + @Test + fun testEnumRange() { + + println(Color.values().toList()); + val red = Color.RED + val yellow = Color.YELLOW + val range = red..yellow + + assertTrue { range.contains(Color.MAGENTA) } + assertFalse { range.contains(Color.BLUE) } + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/CustomColorTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/CustomColorTest.kt new file mode 100644 index 0000000000..8c8795ac42 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/CustomColorTest.kt @@ -0,0 +1,41 @@ +package com.baeldung.range + +import org.junit.Test +import java.lang.IllegalStateException +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue + +class CustomColorTest { + + @Test + fun testInvalidConstructor(){ + assertFailsWith(IllegalStateException::class){ + CustomColor(-1) + } + } + + @Test + fun assertHas10Colors(){ + assertTrue { + val a = CustomColor(1) + val b = CustomColor(10) + val range = a..b + for(cc in range){ + println(cc) + } + range.toList().size == 10 + } + } + + @Test + fun assertContains0xCCCCCC(){ + assertTrue { + val a = CustomColor(0xBBBBBB) + val b = CustomColor(0xDDDDDD) + val range = a..b + range.contains(CustomColor(0xCCCCCC)) + } + } + +} + diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/FilterTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/FilterTest.kt new file mode 100644 index 0000000000..d0e2df8860 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/FilterTest.kt @@ -0,0 +1,24 @@ +package com.baeldung.range + +import org.junit.Test +import kotlin.test.assertEquals + +class FilterTest { + + val r = 1..10 + + @Test + fun filterTest() { + assertEquals(listOf(2, 4, 6, 8, 10), r.filter { it -> it % 2 == 0 }.toList()) + } + + @Test + fun mapTest() { + assertEquals(listOf(1, 4, 9, 16, 25, 36, 49, 64, 81, 100), r.map { it -> it * it }.toList()) + } + + @Test + fun reduceTest() { + assertEquals(55, r.reduce { a, b -> a + b }) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/FirstLastTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/FirstLastTest.kt new file mode 100644 index 0000000000..ca797e9c9b --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/FirstLastTest.kt @@ -0,0 +1,22 @@ +package com.baeldung.range + +import org.junit.Test +import kotlin.test.assertEquals + +class FirstLastTest { + + @Test + fun testFirst() { + assertEquals(1, (1..9).first) + } + + @Test + fun testLast() { + assertEquals(9, (1..9).last) + } + + @Test + fun testStep() { + assertEquals(2, (1..9 step 2).step) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/OtherRangeFunctionsTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/OtherRangeFunctionsTest.kt new file mode 100644 index 0000000000..d2d36bbfae --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/OtherRangeFunctionsTest.kt @@ -0,0 +1,40 @@ +package com.baeldung.range + +import org.junit.Test +import kotlin.test.assertEquals + +class OtherRangeFunctionsTest { + + val r = 1..20 + val repeated = listOf(1, 1, 2, 4, 4, 6, 10) + + @Test + fun testMin() { + assertEquals(1, r.min()) + } + + @Test + fun testMax() { + assertEquals(20, r.max()) + } + + @Test + fun testSum() { + assertEquals(210, r.sum()) + } + + @Test + fun testAverage() { + assertEquals(10.5, r.average()) + } + + @Test + fun testCount() { + assertEquals(20, r.count()) + } + + @Test + fun testDistinct() { + assertEquals(listOf(1, 2, 4, 6, 10), repeated.distinct()) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/RangeTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/RangeTest.kt new file mode 100644 index 0000000000..48fa483924 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/RangeTest.kt @@ -0,0 +1,22 @@ +package com.baeldung.range + +import org.junit.Test +import kotlin.test.assertEquals + +class RangeTest { + + @Test + fun testRange() { + assertEquals(listOf(1,2,3), (1.rangeTo(3).toList())) + } + + @Test + fun testDownTo(){ + assertEquals(listOf(3,2,1), (3.downTo(1).toList())) + } + + @Test + fun testUntil(){ + assertEquals(listOf(1,2), (1.until(3).toList())) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/ReverseRangeTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/ReverseRangeTest.kt new file mode 100644 index 0000000000..7e1c7badb7 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/ReverseRangeTest.kt @@ -0,0 +1,12 @@ +package com.baeldung.range + +import org.junit.Test +import kotlin.test.assertEquals + +class ReverseRangeTest { + + @Test + fun reversedTest() { + assertEquals(listOf(9, 6, 3), (1..9).reversed().step(3).toList()) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/StepTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/StepTest.kt new file mode 100644 index 0000000000..4570ceeb0a --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/StepTest.kt @@ -0,0 +1,17 @@ +package com.baeldung.range + +import org.junit.Test +import kotlin.test.assertEquals + +class StepTest { + + @Test + fun testStep() { + assertEquals(listOf(1, 3, 5, 7, 9), (1..9 step 2).toList()) + } + + @Test + fun testStepDown() { + assertEquals(listOf(9, 7, 5, 3, 1), (9 downTo 1 step 2).toList()) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/UntilRangeTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/UntilRangeTest.kt new file mode 100644 index 0000000000..f941c7f1e6 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/UntilRangeTest.kt @@ -0,0 +1,12 @@ +package com.baeldung.range + +import org.junit.Test +import kotlin.test.assertEquals + +class UntilRangeTest { + + @Test + fun testUntil() { + assertEquals(listOf(1, 2, 3, 4), (1 until 5).toList()) + } +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt new file mode 100644 index 0000000000..cb3ed98006 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt @@ -0,0 +1,143 @@ +package com.baeldung.scope + +import org.junit.Test +import kotlin.test.assertTrue + + +class ScopeFunctionsUnitTest { + + class Logger { + + var called : Boolean = false + + fun info(message: String) { + called = true + } + + fun wasCalled() = called + } + + @Test + fun shouldTransformWhenLetFunctionUsed() { + val stringBuider = StringBuilder() + val numberOfCharacters = stringBuider.let { + it.append("This is a transformation function.") + it.append("It takes a StringBuilder instance and returns the number of characters in the generated String") + it.length + } + + assertTrue { + numberOfCharacters == 128 + } + } + + @Test + fun shouldHandleNullabilityWhenLetFunctionUsed() { + + val message: String? = "hello there!" + val charactersInMessage = message?.let { + "At this point is safe to reference the variable. Let's print the message: $it" + } ?: "default value" + + assertTrue { + charactersInMessage.equals("At this point is safe to reference the variable. Let's print the message: hello there!") + } + + val aNullMessage = null + val thisIsNull = aNullMessage?.let { + "At this point it would be safe to reference the variable. But it will not really happen because it is null. Let's reference: $it" + } ?: "default value" + + assertTrue { + thisIsNull.equals("default value") + } + } + + @Test + fun shouldInitializeObjectWhenUsingApply() { + val aStudent = Student().apply { + studentId = "1234567" + name = "Mary" + surname = "Smith" + } + + assertTrue { + aStudent.name.equals("Mary") + } + } + + @Test + fun shouldAllowBuilderStyleObjectDesignWhenApplyUsedInClassMethods() { + val teacher = Teacher() + .setId(1000) + .setName("Martha") + .setSurname("Spector") + + assertTrue { + teacher.surname.equals("Spector") + } + } + + @Test + fun shouldAllowSideEffectWhenUsingAlso() { + val restClient = RestClient("http://www.someurl.com") + + val logger = Logger() + + val headers = restClient + .getResponse() + .also { logger.info(it.toString()) } + .headers + + assertTrue { + logger.wasCalled() && headers.headerInfo.equals("some header info") + } + + } + + @Test + fun shouldInitializeFieldWhenAlsoUsed() { + val aStudent = Student().also { it.name = "John"} + + assertTrue { + aStudent.name.equals("John") + } + } + + @Test + fun shouldLogicallyGroupObjectCallsWhenUsingWith() { + val bankAccount = BankAccount(1000) + with (bankAccount) { + checkAuthorization("someone") + addPayee("some payee") + makePayment("payment information") + } + } + + @Test + fun shouldConvertObjectWhenRunUsed() { + val stringBuider = StringBuilder() + val numberOfCharacters = stringBuider.run { + append("This is a transformation function.") + append("It takes a StringBuilder instance and returns the number of characters in the generated String") + length + } + + assertTrue { + numberOfCharacters == 128 + } + } + + @Test + fun shouldHandleNullabilityWhenRunIsUsed() { + val message: String? = "hello there!" + val charactersInMessage = message?.run { + "At this point is safe to reference the variable. Let's print the message: $this" + } ?: "default value" + + assertTrue { + charactersInMessage.equals("At this point is safe to reference the variable. Let's print the message: hello there!") + } + } + +} \ No newline at end of file diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt new file mode 100644 index 0000000000..a9ddc99992 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/splitting/SplittingTest.kt @@ -0,0 +1,99 @@ +package com.baeldung.lambda + +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class SplittingTest { + private val evenList = listOf(0, "a", 1, "b", 2, "c"); + + private val unevenList = listOf(0, "a", 1, "b", 2, "c", 3); + + private fun verifyList(resultList: List>) { + assertEquals("[[0, a], [1, b], [2, c]]", resultList.toString()) + } + + private fun verifyPartialList(resultList: List>) { + assertEquals("[[0, a], [1, b], [2, c], [3]]", resultList.toString()) + } + + @Test + fun whenChunked_thenListIsSplit() { + val resultList = evenList.chunked(2) + verifyList(resultList) + } + + @Test + fun whenUnevenChunked_thenListIsSplit() { + val resultList = unevenList.chunked(2) + verifyPartialList(resultList) + } + + @Test + fun whenWindowed_thenListIsSplit() { + val resultList = evenList.windowed(2, 2) + verifyList(resultList) + } + + @Test + fun whenUnevenPartialWindowed_thenListIsSplit() { + val resultList = unevenList.windowed(2, 2, partialWindows = true) + verifyPartialList(resultList) + } + + @Test + fun whenUnevenWindowed_thenListIsSplit() { + val resultList = unevenList.windowed(2, 2, partialWindows = false) + verifyList(resultList) + } + + @Test + fun whenGroupByWithAscendingNumbers_thenListIsSplit() { + val numberList = listOf(1, 2, 3, 4, 5, 6); + val resultList = numberList.groupBy { (it + 1) / 2 } + assertEquals("[[1, 2], [3, 4], [5, 6]]", resultList.values.toString()) + assertEquals("[1, 2, 3]", resultList.keys.toString()) + } + + @Test + fun whenGroupByWithAscendingNumbersUneven_thenListIsSplit() { + val numberList = listOf(1, 2, 3, 4, 5, 6, 7); + val resultList = numberList.groupBy { (it + 1) / 2 }.values + assertEquals("[[1, 2], [3, 4], [5, 6], [7]]", resultList.toString()) + } + + @Test + fun whenGroupByWithRandomNumbers_thenListIsSplitInWrongWay() { + val numberList = listOf(1, 3, 8, 20, 23, 30); + val resultList = numberList.groupBy { (it + 1) / 2 } + assertEquals("[[1], [3], [8], [20], [23], [30]]", resultList.values.toString()) + assertEquals("[1, 2, 4, 10, 12, 15]", resultList.keys.toString()) + } + + @Test + fun whenWithIndexGroupBy_thenListIsSplit() { + val resultList = evenList.withIndex() + .groupBy { it.index / 2 } + .map { it.value.map { it.value } } + verifyList(resultList) + } + + @Test + fun whenWithIndexGroupByUneven_thenListIsSplit() { + val resultList = unevenList.withIndex() + .groupBy { it.index / 2 } + .map { it.value.map { it.value } } + verifyPartialList(resultList) + } + + @Test + fun whenFoldIndexed_thenListIsSplit() { + val resultList = evenList.foldIndexed(ArrayList>(evenList.size / 2)) { index, acc, item -> + if (index % 2 == 0) { + acc.add(ArrayList(2)) + } + acc.last().add(item) + acc + } + verifyList(resultList) + } +} \ No newline at end of file diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 7d8001d667..73a78eccff 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -54,3 +54,5 @@ - [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach) - [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl) - [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods) +- [Inline Functions in Kotlin](https://www.baeldung.com/kotlin-inline-functions) +- [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern) diff --git a/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt b/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt index ef56009c71..20eda4e64f 100644 --- a/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt +++ b/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt @@ -5,6 +5,15 @@ class Country(val name : String, val cities : List) class City(val name : String, val streets : List) +fun City.getStreetsWithCityName() : List { + return streets.map { "$name, $it" }.toList() +} + +fun Country.getCitiesWithCountryName() : List { + return cities.flatMap { it.getStreetsWithCityName() } + .map { "$name, $it" } +} + class World { private val streetsOfAmsterdam = listOf("Herengracht", "Prinsengracht") @@ -45,6 +54,19 @@ class World { } } } + + fun allStreetsFlatMap() { + + countries.flatMap { it.cities} + .flatMap { it.streets} + .forEach { println(it) } + } + + fun allFlatMapTable() { + + countries.flatMap { it.getCitiesWithCountryName() } + .forEach { println(it) } + } } fun main(args : Array) { @@ -56,6 +78,10 @@ fun main(args : Array) { world.allNested() world.allTable() + + world.allStreetsFlatMap() + + world.allFlatMapTable() } diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt new file mode 100644 index 0000000000..8e261aacf2 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt @@ -0,0 +1,64 @@ +package com.baeldung.kotlin.delegates + +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.withLock + +interface Producer { + + fun produce(): String +} + +class ProducerImpl : Producer { + + override fun produce() = "ProducerImpl" +} + +class EnhancedProducer(private val delegate: Producer) : Producer by delegate { + + override fun produce() = "${delegate.produce()} and EnhancedProducer" +} + +interface MessageService { + + fun processMessage(message: String): String +} + +class MessageServiceImpl : MessageService { + override fun processMessage(message: String): String { + return "MessageServiceImpl: $message" + } +} + +interface UserService { + + fun processUser(userId: String): String +} + +class UserServiceImpl : UserService { + + override fun processUser(userId: String): String { + return "UserServiceImpl: $userId" + } +} + +class CompositeService : UserService by UserServiceImpl(), MessageService by MessageServiceImpl() + +interface Service { + + val seed: Int + + fun serve(action: (Int) -> Unit) +} + +class ServiceImpl : Service { + + override val seed = 1 + + override fun serve(action: (Int) -> Unit) { + action(seed) + } +} + +class ServiceDecorator : Service by ServiceImpl() { + override val seed = 2 +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt new file mode 100644 index 0000000000..e65032acd4 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt @@ -0,0 +1,28 @@ +package com.baeldung.kotlin.delegates + +import org.assertj.core.api.Assertions.assertThat +import org.junit.Test + +class InterfaceDelegationTest { + + @Test + fun `when delegated implementation is used then it works as expected`() { + val producer = EnhancedProducer(ProducerImpl()) + assertThat(producer.produce()).isEqualTo("ProducerImpl and EnhancedProducer") + } + + @Test + fun `when composite delegation is used then it works as expected`() { + val service = CompositeService() + assertThat(service.processMessage("message")).isEqualTo("MessageServiceImpl: message") + assertThat(service.processUser("user")).isEqualTo("UserServiceImpl: user") + } + + @Test + fun `when decoration is used then delegate knows nothing about it`() { + val service = ServiceDecorator() + service.serve { + assertThat(it).isEqualTo(1) + } + } +} \ No newline at end of file diff --git a/google-web-toolkit/README.md b/google-web-toolkit/README.md index 65264375bc..3526fe9962 100644 --- a/google-web-toolkit/README.md +++ b/google-web-toolkit/README.md @@ -1,3 +1,2 @@ ### Relevant Articles: - [Introduction to GWT](http://www.baeldung.com/gwt) -- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter) diff --git a/gradle/README.md b/gradle/README.md index a1f5c74c57..14e460f225 100644 --- a/gradle/README.md +++ b/gradle/README.md @@ -3,5 +3,4 @@ - [Writing Custom Gradle Plugins](http://www.baeldung.com/gradle-create-plugin) - [Creating a Fat Jar in Gradle](http://www.baeldung.com/gradle-fat-jar) - [A Custom Task in Gradle](http://www.baeldung.com/gradle-custom-task) -- [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection) - [Using JUnit 5 with Gradle](https://www.baeldung.com/junit-5-gradle) diff --git a/gson/README.md b/gson/README.md index 02b06eac20..fec0506488 100644 --- a/gson/README.md +++ b/gson/README.md @@ -11,3 +11,6 @@ - [Convert JSON to a Map Using Gson](https://www.baeldung.com/gson-json-to-map) - [Working with Primitive Values in Gson](https://www.baeldung.com/java-gson-primitives) - [Convert String to JsonObject with Gson](https://www.baeldung.com/gson-string-to-jsonobject) +- [Mapping Multiple JSON Fields to One Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field) +- [Serializing and Deserializing a List with Gson](https://www.baeldung.com/gson-list) + diff --git a/gson/src/main/java/org/baeldung/gson/entities/Animal.java b/gson/src/main/java/org/baeldung/gson/entities/Animal.java new file mode 100644 index 0000000000..2eec5f8704 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/Animal.java @@ -0,0 +1,5 @@ +package org.baeldung.gson.entities; + +public abstract class Animal { + public String type = "Animal"; +} diff --git a/gson/src/main/java/org/baeldung/gson/entities/Cow.java b/gson/src/main/java/org/baeldung/gson/entities/Cow.java new file mode 100644 index 0000000000..020bcd5860 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/Cow.java @@ -0,0 +1,19 @@ +package org.baeldung.gson.entities; + +public class Cow extends Animal { + private String breed; + + public Cow() { + breed = "Jersey"; + type = "Cow"; + } + + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } +} + diff --git a/gson/src/main/java/org/baeldung/gson/entities/Dog.java b/gson/src/main/java/org/baeldung/gson/entities/Dog.java new file mode 100644 index 0000000000..042d73adcf --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/Dog.java @@ -0,0 +1,18 @@ +package org.baeldung.gson.entities; + +public class Dog extends Animal { + private String petName; + + public Dog() { + petName = "Milo"; + type = "Dog"; + } + + public String getPetName() { + return petName; + } + + public void setPetName(String petName) { + this.petName = petName; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/entities/MyClass.java b/gson/src/main/java/org/baeldung/gson/entities/MyClass.java new file mode 100644 index 0000000000..4e717e72c3 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/MyClass.java @@ -0,0 +1,49 @@ +package org.baeldung.gson.entities; + +import java.util.Objects; + +public class MyClass { + private int id; + private String name; + + public MyClass(int id, String name) { + this.id = id; + this.name = name; + } + + public MyClass() { } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MyClass myClass = (MyClass) o; + return id == myClass.id && Objects.equals(name, myClass.name); + } + + @Override + public int hashCode() { + + return Objects.hash(id, name); + } +} diff --git a/gson/src/main/java/org/baeldung/gson/entities/Weather.java b/gson/src/main/java/org/baeldung/gson/entities/Weather.java new file mode 100644 index 0000000000..383e9ef41c --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/Weather.java @@ -0,0 +1,40 @@ +package org.baeldung.gson.entities; + +import com.google.gson.annotations.SerializedName; + +public class Weather { + + @SerializedName(value = "location", alternate = "place") + private String location; + + @SerializedName(value = "temp", alternate = "temperature") + private int temp; + + @SerializedName(value = "outlook", alternate = "weather") + private String outlook; + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public int getTemp() { + return temp; + } + + public void setTemp(int temp) { + this.temp = temp; + } + + public String getOutlook() { + return outlook; + } + + public void setOutlook(String outlook) { + this.outlook = outlook; + } + +} diff --git a/gson/src/main/java/org/baeldung/gson/serialization/AnimalDeserializer.java b/gson/src/main/java/org/baeldung/gson/serialization/AnimalDeserializer.java new file mode 100644 index 0000000000..9dcef0e10b --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serialization/AnimalDeserializer.java @@ -0,0 +1,35 @@ +package org.baeldung.gson.serialization; + +import com.google.gson.Gson; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; +import org.baeldung.gson.entities.Animal; + +public class AnimalDeserializer implements JsonDeserializer { + private String animalTypeElementName; + private Gson gson; + private Map> animalTypeRegistry; + + public AnimalDeserializer(String animalTypeElementName) { + this.animalTypeElementName = animalTypeElementName; + this.gson = new Gson(); + this.animalTypeRegistry = new HashMap<>(); + } + + public void registerBarnType(String animalTypeName, Class animalType) { + animalTypeRegistry.put(animalTypeName, animalType); + } + + public Animal deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { + JsonObject animalObject = json.getAsJsonObject(); + JsonElement animalTypeElement = animalObject.get(animalTypeElementName); + + Class animalType = animalTypeRegistry.get(animalTypeElement.getAsString()); + return gson.fromJson(animalObject, animalType); + } +} \ No newline at end of file diff --git a/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java b/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java new file mode 100644 index 0000000000..5b787f1956 --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/advance/GsonAdvanceUnitTest.java @@ -0,0 +1,117 @@ +package org.baeldung.gson.advance; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.baeldung.gson.entities.Animal; +import org.baeldung.gson.entities.Cow; +import org.baeldung.gson.entities.Dog; +import org.baeldung.gson.entities.MyClass; +import org.baeldung.gson.serialization.AnimalDeserializer; +import org.junit.Test; + +public class GsonAdvanceUnitTest { + + @Test + public void givenListOfMyClass_whenSerializing_thenCorrect() { + List list = Arrays.asList(new MyClass(1, "name1"), new MyClass(2, "name2")); + + Gson gson = new Gson(); + String jsonString = gson.toJson(list); + String expectedString = "[{\"id\":1,\"name\":\"name1\"},{\"id\":2,\"name\":\"name2\"}]"; + + assertEquals(expectedString, jsonString); + } + + @Test(expected = ClassCastException.class) + public void givenJsonString_whenIncorrectDeserializing_thenThrowClassCastException() { + String inputString = "[{\"id\":1,\"name\":\"name1\"},{\"id\":2,\"name\":\"name2\"}]"; + + Gson gson = new Gson(); + List outputList = gson.fromJson(inputString, ArrayList.class); + + assertEquals(1, outputList.get(0).getId()); + } + + @Test + public void givenJsonString_whenDeserializing_thenReturnListOfMyClass() { + String inputString = "[{\"id\":1,\"name\":\"name1\"},{\"id\":2,\"name\":\"name2\"}]"; + List inputList = Arrays.asList(new MyClass(1, "name1"), new MyClass(2, "name2")); + + Type listOfMyClassObject = new TypeToken>() {}.getType(); + + Gson gson = new Gson(); + List outputList = gson.fromJson(inputString, listOfMyClassObject); + + assertEquals(inputList, outputList); + } + + @Test + public void givenPolymorphicList_whenSerializeWithTypeAdapter_thenCorrect() { + String expectedString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; + + List inList = new ArrayList<>(); + inList.add(new Dog()); + inList.add(new Cow()); + + String jsonString = new Gson().toJson(inList); + + assertEquals(expectedString, jsonString); + } + + @Test + public void givenPolymorphicList_whenDeserializeWithTypeAdapter_thenCorrect() { + String inputString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; + + AnimalDeserializer deserializer = new AnimalDeserializer("type"); + deserializer.registerBarnType("Dog", Dog.class); + deserializer.registerBarnType("Cow", Cow.class); + Gson gson = new GsonBuilder() + .registerTypeAdapter(Animal.class, deserializer) + .create(); + + List outList = gson.fromJson(inputString, new TypeToken>(){}.getType()); + + assertEquals(2, outList.size()); + assertTrue(outList.get(0) instanceof Dog); + assertTrue(outList.get(1) instanceof Cow); + } + + @Test + public void givenPolymorphicList_whenSerializeWithRuntimeTypeAdapter_thenCorrect() { + String expectedString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; + + List inList = new ArrayList<>(); + inList.add(new Dog()); + inList.add(new Cow()); + String jsonString = new Gson().toJson(inList); + + assertEquals(expectedString, jsonString); + } + + @Test + public void givenPolymorphicList_whenDeserializeWithRuntimeTypeAdapter_thenCorrect() { + String inputString = "[{\"petName\":\"Milo\",\"type\":\"Dog\"},{\"breed\":\"Jersey\",\"type\":\"Cow\"}]"; + + Type listOfAnimals = new TypeToken>() {}.getType(); + + RuntimeTypeAdapterFactory adapter = RuntimeTypeAdapterFactory.of(Animal.class, "type") + .registerSubtype(Dog.class) + .registerSubtype(Cow.class); + + Gson gson = new GsonBuilder().registerTypeAdapterFactory(adapter).create(); + + List outList = gson.fromJson(inputString, listOfAnimals); + + assertEquals(2, outList.size()); + assertTrue(outList.get(0) instanceof Dog); + assertTrue(outList.get(1) instanceof Cow); + } +} \ No newline at end of file diff --git a/gson/src/test/java/org/baeldung/gson/advance/RuntimeTypeAdapterFactory.java b/gson/src/test/java/org/baeldung/gson/advance/RuntimeTypeAdapterFactory.java new file mode 100644 index 0000000000..739dd889c7 --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/advance/RuntimeTypeAdapterFactory.java @@ -0,0 +1,265 @@ +package org.baeldung.gson.advance; + +/* + * Copyright (C) 2011 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.internal.Streams; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Adapts values whose runtime type may differ from their declaration type. This + * is necessary when a field's type is not the same type that GSON should create + * when deserializing that field. For example, consider these types: + *
   {@code
+ *   abstract class Shape {
+ *     int x;
+ *     int y;
+ *   }
+ *   class Circle extends Shape {
+ *     int radius;
+ *   }
+ *   class Rectangle extends Shape {
+ *     int width;
+ *     int height;
+ *   }
+ *   class Diamond extends Shape {
+ *     int width;
+ *     int height;
+ *   }
+ *   class Drawing {
+ *     Shape bottomShape;
+ *     Shape topShape;
+ *   }
+ * }
+ *

Without additional type information, the serialized JSON is ambiguous. Is + * the bottom shape in this drawing a rectangle or a diamond?

   {@code
+ *   {
+ *     "bottomShape": {
+ *       "width": 10,
+ *       "height": 5,
+ *       "x": 0,
+ *       "y": 0
+ *     },
+ *     "topShape": {
+ *       "radius": 2,
+ *       "x": 4,
+ *       "y": 1
+ *     }
+ *   }}
+ * This class addresses this problem by adding type information to the + * serialized JSON and honoring that type information when the JSON is + * deserialized:
   {@code
+ *   {
+ *     "bottomShape": {
+ *       "type": "Diamond",
+ *       "width": 10,
+ *       "height": 5,
+ *       "x": 0,
+ *       "y": 0
+ *     },
+ *     "topShape": {
+ *       "type": "Circle",
+ *       "radius": 2,
+ *       "x": 4,
+ *       "y": 1
+ *     }
+ *   }}
+ * Both the type field name ({@code "type"}) and the type labels ({@code + * "Rectangle"}) are configurable. + * + *

Registering Types

+ * Create a {@code RuntimeTypeAdapterFactory} by passing the base type and type field + * name to the {@link #of} factory method. If you don't supply an explicit type + * field name, {@code "type"} will be used.
   {@code
+ *   RuntimeTypeAdapterFactory shapeAdapterFactory
+ *       = RuntimeTypeAdapterFactory.of(Shape.class, "type");
+ * }
+ * Next register all of your subtypes. Every subtype must be explicitly + * registered. This protects your application from injection attacks. If you + * don't supply an explicit type label, the type's simple name will be used. + *
   {@code
+ *   shapeAdapterFactory.registerSubtype(Rectangle.class, "Rectangle");
+ *   shapeAdapterFactory.registerSubtype(Circle.class, "Circle");
+ *   shapeAdapterFactory.registerSubtype(Diamond.class, "Diamond");
+ * }
+ * Finally, register the type adapter factory in your application's GSON builder: + *
   {@code
+ *   Gson gson = new GsonBuilder()
+ *       .registerTypeAdapterFactory(shapeAdapterFactory)
+ *       .create();
+ * }
+ * Like {@code GsonBuilder}, this API supports chaining:
   {@code
+ *   RuntimeTypeAdapterFactory shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class)
+ *       .registerSubtype(Rectangle.class)
+ *       .registerSubtype(Circle.class)
+ *       .registerSubtype(Diamond.class);
+ * }
+ */ +public final class RuntimeTypeAdapterFactory implements TypeAdapterFactory { + private final Class baseType; + private final String typeFieldName; + private final Map> labelToSubtype = new LinkedHashMap>(); + private final Map, String> subtypeToLabel = new LinkedHashMap, String>(); + private final boolean maintainType; + + private RuntimeTypeAdapterFactory(Class baseType, String typeFieldName, boolean maintainType) { + if (typeFieldName == null || baseType == null) { + throw new NullPointerException(); + } + this.baseType = baseType; + this.typeFieldName = typeFieldName; + this.maintainType = maintainType; + } + + /** + * Creates a new runtime type adapter using for {@code baseType} using {@code + * typeFieldName} as the type field name. Type field names are case sensitive. + * {@code maintainType} flag decide if the type will be stored in pojo or not. + */ + public static RuntimeTypeAdapterFactory of(Class baseType, String typeFieldName, boolean maintainType) { + return new RuntimeTypeAdapterFactory(baseType, typeFieldName, maintainType); + } + + /** + * Creates a new runtime type adapter using for {@code baseType} using {@code + * typeFieldName} as the type field name. Type field names are case sensitive. + */ + public static RuntimeTypeAdapterFactory of(Class baseType, String typeFieldName) { + return new RuntimeTypeAdapterFactory(baseType, typeFieldName, false); + } + + /** + * Creates a new runtime type adapter for {@code baseType} using {@code "type"} as + * the type field name. + */ + public static RuntimeTypeAdapterFactory of(Class baseType) { + return new RuntimeTypeAdapterFactory(baseType, "type", false); + } + + /** + * Registers {@code type} identified by {@code label}. Labels are case + * sensitive. + * + * @throws IllegalArgumentException if either {@code type} or {@code label} + * have already been registered on this type adapter. + */ + public RuntimeTypeAdapterFactory registerSubtype(Class type, String label) { + if (type == null || label == null) { + throw new NullPointerException(); + } + if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) { + throw new IllegalArgumentException("types and labels must be unique"); + } + labelToSubtype.put(label, type); + subtypeToLabel.put(type, label); + return this; + } + + /** + * Registers {@code type} identified by its {@link Class#getSimpleName simple + * name}. Labels are case sensitive. + * + * @throws IllegalArgumentException if either {@code type} or its simple name + * have already been registered on this type adapter. + */ + public RuntimeTypeAdapterFactory registerSubtype(Class type) { + return registerSubtype(type, type.getSimpleName()); + } + + public TypeAdapter create(Gson gson, TypeToken type) { + if (type.getRawType() != baseType) { + return null; + } + + final Map> labelToDelegate + = new LinkedHashMap>(); + final Map, TypeAdapter> subtypeToDelegate + = new LinkedHashMap, TypeAdapter>(); + for (Map.Entry> entry : labelToSubtype.entrySet()) { + TypeAdapter delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); + labelToDelegate.put(entry.getKey(), delegate); + subtypeToDelegate.put(entry.getValue(), delegate); + } + + return new TypeAdapter() { + @Override public R read(JsonReader in) throws IOException { + JsonElement jsonElement = Streams.parse(in); + JsonElement labelJsonElement; + if (maintainType) { + labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); + } else { + labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); + } + + if (labelJsonElement == null) { + throw new JsonParseException("cannot deserialize " + baseType + + " because it does not define a field named " + typeFieldName); + } + String label = labelJsonElement.getAsString(); + @SuppressWarnings("unchecked") // registration requires that subtype extends T + TypeAdapter delegate = (TypeAdapter) labelToDelegate.get(label); + if (delegate == null) { + throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + + label + "; did you forget to register a subtype?"); + } + return delegate.fromJsonTree(jsonElement); + } + + @Override public void write(JsonWriter out, R value) throws IOException { + Class srcType = value.getClass(); + String label = subtypeToLabel.get(srcType); + @SuppressWarnings("unchecked") // registration requires that subtype extends T + TypeAdapter delegate = (TypeAdapter) subtypeToDelegate.get(srcType); + if (delegate == null) { + throw new JsonParseException("cannot serialize " + srcType.getName() + + "; did you forget to register a subtype?"); + } + JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); + + if (maintainType) { + Streams.write(jsonObject, out); + return; + } + + JsonObject clone = new JsonObject(); + + if (jsonObject.has(typeFieldName)) { + throw new JsonParseException("cannot serialize " + srcType.getName() + + " because it already defines a field named " + typeFieldName); + } + clone.add(typeFieldName, new JsonPrimitive(label)); + + for (Map.Entry e : jsonObject.entrySet()) { + clone.add(e.getKey(), e.getValue()); + } + Streams.write(clone, out); + } + }.nullSafe(); + } +} diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/GsonAlternateUnitTest.java b/gson/src/test/java/org/baeldung/gson/deserialization/GsonAlternateUnitTest.java new file mode 100644 index 0000000000..f3a5d24e3e --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/deserialization/GsonAlternateUnitTest.java @@ -0,0 +1,39 @@ +package org.baeldung.gson.deserialization; + +import static org.junit.Assert.assertEquals; + +import org.baeldung.gson.entities.Weather; +import org.junit.Test; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class GsonAlternateUnitTest { + + @Test + public void givenTwoJsonFormats_whenDeserialized_thenWeatherObjectsCreated() throws Exception { + + Gson gson = new GsonBuilder().create(); + + Weather weather = gson.fromJson("{" + + "\"location\": \"London\"," + + "\"temp\": 15," + + "\"weather\": \"Cloudy\"" + + "}", Weather.class); + + assertEquals("London", weather.getLocation()); + assertEquals("Cloudy", weather.getOutlook()); + assertEquals(15, weather.getTemp()); + + weather = gson.fromJson("{" + + "\"place\": \"Lisbon\"," + + "\"temperature\": 35," + + "\"outlook\": \"Sunny\"" + + "}", Weather.class); + + assertEquals("Lisbon", weather.getLocation()); + assertEquals("Sunny", weather.getOutlook()); + assertEquals(35, weather.getTemp()); + + } +} diff --git a/guava-modules/guava-18/README.md b/guava-modules/guava-18/README.md index 9924d7c16f..fd5de4170a 100644 --- a/guava-modules/guava-18/README.md +++ b/guava-modules/guava-18/README.md @@ -4,9 +4,5 @@ ### Relevant Articles: -- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections) -- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order) - [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates) -- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays) -- [Partition a List in Java](http://www.baeldung.com/java-list-split) - [Guava 18: What’s New?](http://www.baeldung.com/whats-new-in-guava-18) diff --git a/httpclient/README.md b/httpclient/README.md index 7c5122c5b8..87fb38706d 100644 --- a/httpclient/README.md +++ b/httpclient/README.md @@ -12,7 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [HttpClient 4 – Cancel / Abort Request](http://www.baeldung.com/httpclient-cancel-request) - [HttpClient 4 Cookbook](http://www.baeldung.com/httpclient4) - [Unshorten URLs with HttpClient](http://www.baeldung.com/unshorten-url-httpclient) -- [HttpClient with SSL](http://www.baeldung.com/httpclient-ssl) - [HttpClient 4 – Follow Redirects for POST](http://www.baeldung.com/httpclient-redirect-on-http-post) - [Custom HTTP Header with the HttpClient](http://www.baeldung.com/httpclient-custom-http-header) - [HttpClient Basic Authentication](http://www.baeldung.com/httpclient-4-basic-authentication) diff --git a/jackson-2/.gitignore b/jackson-2/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/jackson-2/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/jackson-2/README.md b/jackson-2/README.md new file mode 100644 index 0000000000..ec147f5fd9 --- /dev/null +++ b/jackson-2/README.md @@ -0,0 +1,9 @@ +========= + +## Jackson Cookbooks and Examples + +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: +- [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field) diff --git a/jackson-2/pom.xml b/jackson-2/pom.xml new file mode 100644 index 0000000000..ddbcb81dcc --- /dev/null +++ b/jackson-2/pom.xml @@ -0,0 +1,52 @@ + + 4.0.0 + jackson-2 + 0.1-SNAPSHOT + jackson-2 + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + jackson-2 + + + src/main/resources + true + + + + + + + + 3.11.0 + + + diff --git a/jackson-2/src/main/java/com/baeldung/jackson/entities/Weather.java b/jackson-2/src/main/java/com/baeldung/jackson/entities/Weather.java new file mode 100644 index 0000000000..4a8cea052f --- /dev/null +++ b/jackson-2/src/main/java/com/baeldung/jackson/entities/Weather.java @@ -0,0 +1,44 @@ +package com.baeldung.jackson.entities; + +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Weather { + + @JsonProperty("location") + @JsonAlias("place") + private String location; + + @JsonProperty("temp") + @JsonAlias("temperature") + private int temp; + + @JsonProperty("outlook") + @JsonAlias("weather") + private String outlook; + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public int getTemp() { + return temp; + } + + public void setTemp(int temp) { + this.temp = temp; + } + + public String getOutlook() { + return outlook; + } + + public void setOutlook(String outlook) { + this.outlook = outlook; + } + +} diff --git a/jackson-2/src/main/resources/logback.xml b/jackson-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jackson-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jackson-2/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java b/jackson-2/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java new file mode 100644 index 0000000000..b5940a7bd7 --- /dev/null +++ b/jackson-2/src/test/java/com/baeldung/jackson/deserialization/jsonalias/JsonAliasUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.jackson.deserialization.jsonalias; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.jackson.entities.Weather; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonAliasUnitTest { + + @Test + public void givenTwoJsonFormats_whenDeserialized_thenWeatherObjectsCreated() throws Exception { + + ObjectMapper mapper = new ObjectMapper(); + + Weather weather = mapper.readValue("{" + + "\"location\": \"London\"," + + "\"temp\": 15," + + "\"weather\": \"Cloudy\"" + + "}", Weather.class); + + assertEquals("London", weather.getLocation()); + assertEquals("Cloudy", weather.getOutlook()); + assertEquals(15, weather.getTemp()); + + weather = mapper.readValue("{" + + "\"place\": \"Lisbon\"," + + "\"temperature\": 35," + + "\"outlook\": \"Sunny\"" + + "}", Weather.class); + + assertEquals("Lisbon", weather.getLocation()); + assertEquals("Sunny", weather.getOutlook()); + assertEquals(35, weather.getTemp()); + + } +} diff --git a/jackson/README.md b/jackson/README.md index 25194c7255..e9cf6f212c 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -38,3 +38,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Mapping Nested Values with Jackson](http://www.baeldung.com/jackson-nested-values) - [Convert XML to JSON Using Jackson](https://www.baeldung.com/jackson-convert-xml-json) - [Deserialize Immutable Objects with Jackson](https://www.baeldung.com/jackson-deserialize-immutable-objects) +- [Mapping a Dynamic JSON Object with Jackson](https://www.baeldung.com/jackson-mapping-dynamic-object) + diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java deleted file mode 100644 index db8b594509..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.jackson.deserialization.jacksoninject; - -import com.baeldung.jackson.domain.Item; - -import java.util.ArrayList; -import java.util.List; - -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author() { - } - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java index c4daf68bd6..d9748e2997 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonanysetter/Inventory.java @@ -1,24 +1,14 @@ package com.baeldung.jackson.deserialization.jsonanysetter; -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; - import java.util.HashMap; import java.util.Map; +import com.fasterxml.jackson.annotation.JsonAnySetter; + public class Inventory { - private Map stock = new HashMap<>(); - private Map countryDeliveryCost = new HashMap<>(); - @JsonIgnore - public Map getStock() { - return stock; - } - public Map getCountryDeliveryCost() { return countryDeliveryCost; } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java deleted file mode 100644 index d48c95b255..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.jackson.deserialization.jsoncreator; - -import com.baeldung.jackson.domain.Person; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.ArrayList; -import java.util.List; - -public class Author extends Person { - - List items = new ArrayList<>(); - - @JsonCreator - public Author(@JsonProperty("christianName") String firstName, @JsonProperty("surname") String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Author.java deleted file mode 100644 index 62e108facb..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Author.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.jackson.deserialization.jsondeserialize; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; - -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java index dc0d0ee623..1e411da64e 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Book.java @@ -1,12 +1,16 @@ package com.baeldung.jackson.deserialization.jsondeserialize; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - import java.math.BigDecimal; import java.util.Date; +import java.util.UUID; -public class Book extends Item { +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +public class Book { + + private UUID id; + private String title; + private float price; private String ISBN; @JsonDeserialize(using = CustomDateDeserializer.class) @@ -16,8 +20,9 @@ public class Book extends Item { public Book() { } - public Book(String title, Author author) { - super(title, author); + public Book(String title) { + this.id = UUID.randomUUID(); + this.title = title; } public String getISBN() { @@ -43,4 +48,28 @@ public class Book extends Item { public void setPages(BigDecimal pages) { this.pages = pages; } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public float getPrice() { + return price; + } + + public void setPrice(float price) { + this.price = price; + } } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java deleted file mode 100644 index fc27a586ac..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.jackson.deserialization.jsondeserialize; - -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java deleted file mode 100644 index 3f9ae70a88..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.jackson.deserialization.jsonsetter; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonSetter; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author() { - } - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - @JsonIgnore - public List getItems() { - return items; - } - - @JsonSetter("publications") - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Author.java b/jackson/src/main/java/com/baeldung/jackson/domain/Author.java deleted file mode 100644 index 9000c00f21..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Author.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Book.java b/jackson/src/main/java/com/baeldung/jackson/domain/Book.java deleted file mode 100644 index a5963e33ba..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Book.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.math.BigDecimal; -import java.util.Date; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Book extends Item { - - private String ISBN; - private Date published; - private BigDecimal pages; - - public Book() { - } - - public Book(String title, Author author) { - super(title, author); - } - - public String getISBN() { - return ISBN; - } - - public void setISBN(String ISBN) { - this.ISBN = ISBN; - } - - public Date getPublished() { - return published; - } - - public void setPublished(Date published) { - this.published = published; - } - - public BigDecimal getPages() { - return pages; - } - - public void setPages(BigDecimal pages) { - this.pages = pages; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Course.java b/jackson/src/main/java/com/baeldung/jackson/domain/Course.java deleted file mode 100644 index 672b0bc250..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Course.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Customer.java b/jackson/src/main/java/com/baeldung/jackson/domain/Customer.java deleted file mode 100644 index 1e03ff9a13..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Customer.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.jackson.domain; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Customer extends Person { - - private String configuration; - - public Customer(String firstName, String lastName) { - super(firstName, lastName); - } - - public String getConfiguration() { - return configuration; - } - - public void setConfiguration(String configuration) { - this.configuration = configuration; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Inventory.java b/jackson/src/main/java/com/baeldung/jackson/domain/Inventory.java deleted file mode 100644 index 41b7dc51da..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Inventory.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.util.HashMap; -import java.util.Map; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Inventory { - - private Map stock; - - private Map countryDeliveryCost = new HashMap<>(); - - public Map getStock() { - return stock; - } - - public void setStock(Map stock) { - this.stock = stock; - } - - public Map getCountryDeliveryCost() { - return countryDeliveryCost; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Item.java b/jackson/src/main/java/com/baeldung/jackson/domain/Item.java deleted file mode 100644 index d9d1350a8e..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Item.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Order.java b/jackson/src/main/java/com/baeldung/jackson/domain/Order.java deleted file mode 100644 index 91f87f74df..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Order.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.jackson.domain; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Order { - - private UUID id; - private Type type; - private int internalAudit; - - public static class Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public Order(int internalAudit) { - this(); - this.type = new Type(); - this.type.id = 20; - this.type.name = "Order"; - this.internalAudit = internalAudit; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Person.java b/jackson/src/main/java/com/baeldung/jackson/domain/Person.java index 785efff755..f11ba41113 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Person.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Person.java @@ -1,24 +1,12 @@ package com.baeldung.jackson.domain; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ public class Person { - private UUID id; private String firstName; private String lastName; - - public Person() { - } - + public Person(String firstName, String lastName) { - this.id = UUID.randomUUID(); + super(); this.firstName = firstName; this.lastName = lastName; } @@ -38,8 +26,5 @@ public class Person { public void setLastName(String lastName) { this.lastName = lastName; } - - public UUID getId() { - return id; - } } + diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonautodetect/Order.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonautodetect/Order.java deleted file mode 100644 index f2ff5eeb08..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonautodetect/Order.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonautodetect; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonAutoDetect(fieldVisibility = Visibility.ANY) -public class Order { - - private UUID id; - private Type type; - private int internalAudit; - - public static class Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public Order(int internalAudit) { - this(); - this.type = new Type(); - this.type.id = 20; - this.type.name = "Order"; - this.internalAudit = internalAudit; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Author.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Author.java deleted file mode 100644 index a7801493bf..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Author.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignore; - -import com.baeldung.jackson.domain.Item; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java deleted file mode 100644 index 0037d83148..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignore; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Person { - - @JsonIgnore - private UUID id; - private String firstName; - private String lastName; - - public Person() { - } - - public Person(String firstName, String lastName) { - this.id = UUID.randomUUID(); - this.firstName = firstName; - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public UUID getId() { - return id; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java deleted file mode 100644 index 70b4dd9842..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignoreproperties; - -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonIgnoreProperties({ "medium" }) -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoretype/Order.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoretype/Order.java deleted file mode 100644 index 0d8867933f..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoretype/Order.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignoretype; - -import com.fasterxml.jackson.annotation.JsonIgnoreType; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Order { - - private UUID id; - private Type type; - - @JsonIgnoreType - public static class Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsoninclude/Author.java b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsoninclude/Author.java deleted file mode 100644 index 30cb2735c2..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsoninclude/Author.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.jackson.inclusion.jsoninclude; - -import com.baeldung.jackson.domain.Person; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonInclude; - -import java.util.ArrayList; -import java.util.List; - -import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonInclude(NON_NULL) -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java deleted file mode 100644 index a44492b9f7..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.jackson.miscellaneous.custom; - -import com.baeldung.jackson.domain.Author; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@CustomCourseAnnotation -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java deleted file mode 100644 index d7f72ca6ec..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.jackson.miscellaneous.custom; - -import com.fasterxml.jackson.annotation.*; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@Retention(RetentionPolicy.RUNTIME) -@JacksonAnnotationsInside -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ "title", "price", "id", "duration", "authors", "level" }) -@JsonIgnoreProperties({ "prerequisite" }) -public @interface CustomCourseAnnotation { -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java deleted file mode 100644 index 6625283dec..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.jackson.miscellaneous.custom; - -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java deleted file mode 100644 index 0638e32925..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.jackson.miscellaneous.disable; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ "lastName", "items", "firstName", "id" }) -public class Author extends Person { - - @JsonIgnore - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/Author.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/Author.java deleted file mode 100644 index 26e3e4b647..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/Author.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.jackson.miscellaneous.mixin; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/IgnoreListMixIn.java b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/IgnoreListMixIn.java deleted file mode 100644 index 418c09c251..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/mixin/IgnoreListMixIn.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.jackson.miscellaneous.mixin; - -import com.fasterxml.jackson.annotation.JsonIgnoreType; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonIgnoreType -public class IgnoreListMixIn { -} diff --git a/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java b/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java deleted file mode 100644 index 1813148b2b..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.jackson.polymorphism; - -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Order { - - private UUID id; - private Type type; - private int internalAudit; - - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ordertype") - @JsonSubTypes({ @JsonSubTypes.Type(value = InternalType.class, name = "internal") }) - public static class Type { - public long id; - public String name; - } - - @JsonTypeName("internal") - public static class InternalType extends Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public Order(int internalAudit) { - this(); - this.type = new Type(); - this.type.id = 20; - this.type.name = "Order"; - this.internalAudit = internalAudit; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonanygetter/Inventory.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonanygetter/Inventory.java deleted file mode 100644 index 52f586d93b..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonanygetter/Inventory.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.jackson.serialization.jsonanygetter; - -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.HashMap; -import java.util.Map; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Inventory { - - private String location; - - private Map stock = new HashMap<>(); - - private Map countryDeliveryCost = new HashMap<>(); - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - @JsonIgnore - public Map getStock() { - return stock; - } - - @JsonAnyGetter - public Map getCountryDeliveryCost() { - return countryDeliveryCost; - } - -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java deleted file mode 100644 index 8d89fefce7..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.jackson.serialization.jsongetter; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; -import com.fasterxml.jackson.annotation.JsonGetter; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - @JsonGetter("publications") - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java deleted file mode 100644 index dadf893cf9..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.jackson.serialization.jsonpropertyorder; - -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonPropertyOrder({ "items", "firstName", "lastName", "id" }) -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Person.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Person.java deleted file mode 100644 index 519e48aada..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Person.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.jackson.serialization.jsonpropertyorder; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Person { - - private UUID id; - private String firstName; - private String lastName; - - public Person(String firstName, String lastName) { - this.id = UUID.randomUUID(); - this.firstName = firstName; - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public UUID getId() { - return id; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrawvalue/Customer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrawvalue/Customer.java deleted file mode 100644 index f19c5314d2..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrawvalue/Customer.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.jackson.serialization.jsonrawvalue; - -import com.baeldung.jackson.domain.Person; -import com.fasterxml.jackson.annotation.JsonRawValue; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Customer extends Person { - - @JsonRawValue - private String configuration; - - public Customer(String firstName, String lastName) { - super(firstName, lastName); - } - - public String getConfiguration() { - return configuration; - } - - public void setConfiguration(String configuration) { - this.configuration = configuration; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrootname/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrootname/Author.java deleted file mode 100644 index c6ebfd10fb..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonrootname/Author.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.jackson.serialization.jsonrootname; - -import com.baeldung.jackson.domain.Item; -import com.baeldung.jackson.domain.Person; -import com.fasterxml.jackson.annotation.JsonRootName; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonRootName("writer") -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Author.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Author.java deleted file mode 100644 index 5a6e90d712..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Author.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.jackson.serialization.jsonserialize; - -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java deleted file mode 100644 index 0ecc4e72ce..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.jackson.serialization.jsonserialize; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import java.math.BigDecimal; -import java.util.Date; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Book extends Item { - - private String ISBN; - - @JsonSerialize(using = CustomDateSerializer.class) - private Date published; - private BigDecimal pages; - - public Book() { - } - - public Book(String title, Author author) { - super(title, author); - } - - public String getISBN() { - return ISBN; - } - - public void setISBN(String ISBN) { - this.ISBN = ISBN; - } - - public Date getPublished() { - return published; - } - - public void setPublished(Date published) { - this.published = published; - } - - public BigDecimal getPages() { - return pages; - } - - public void setPages(BigDecimal pages) { - this.pages = pages; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java deleted file mode 100644 index 131f4f3695..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.jackson.serialization.jsonserialize; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class CustomDateSerializer extends StdSerializer { - - private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); - - public CustomDateSerializer() { - this(null); - } - - public CustomDateSerializer(Class t) { - super(t); - } - - @Override - public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException { - gen.writeString(formatter.format(value)); - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java deleted file mode 100644 index 56cfa85793..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.jackson.serialization.jsonserialize; - -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java deleted file mode 100644 index a3fdc2d8eb..0000000000 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.baeldung.jackson.serialization.jsonvalue; - -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonValue; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - @JsonValue - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/AliasBean.java b/jackson/src/test/java/com/baeldung/jackson/annotation/AliasBean.java new file mode 100644 index 0000000000..1842b2b6f5 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/AliasBean.java @@ -0,0 +1,31 @@ +package com.baeldung.jackson.annotation; + +import com.fasterxml.jackson.annotation.JsonAlias; + +public class AliasBean { + + @JsonAlias({ "fName", "f_name" }) + private String firstName; + + private String lastName; + + public AliasBean() { + + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } +} diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java deleted file mode 100644 index 96dbff6f3c..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.jackson.deserialization.jacksoninject; - -import com.fasterxml.jackson.databind.InjectableValues; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; -import java.util.UUID; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JacksonInjectUnitTest { - - @Test - public void whenDeserializingUsingJacksonInject_thenCorrect() throws IOException { - - UUID id = UUID.fromString("9616dc8c-bad3-11e6-a4a6-cec0c932ce01"); - - // arrange - String authorJson = "{\"firstName\": \"Alex\", \"lastName\": \"Theedom\"}"; - - // act - InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id); - Author author = new ObjectMapper().reader(inject) - .forType(Author.class) - .readValue(authorJson); - - // assert - assertThat(author.getId()).isEqualTo(id); - - /* - { - "firstName": "Alex", - "lastName": "Theedom", - "publications": [] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java deleted file mode 100644 index 2e1f94bc3c..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.jackson.deserialization.jsonanysetter; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonAnySetterUnitTest { - - @Test - public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException { - - // arrange - String json = "{\"USA\":10.00,\"UK\":15.00,\"China\":23.00,\"Brazil\":12.00,\"France\":8.00,\"Russia\":18.00}"; - - // act - Inventory inventory = new ObjectMapper().readerFor(Inventory.class) - .readValue(json); - - // assert - assertThat(from(json).getMap(".") - .get("USA")).isEqualTo(inventory.getCountryDeliveryCost() - .get("USA")); - assertThat(from(json).getMap(".") - .get("UK")).isEqualTo(inventory.getCountryDeliveryCost() - .get("UK")); - assertThat(from(json).getMap(".") - .get("China")).isEqualTo(inventory.getCountryDeliveryCost() - .get("China")); - assertThat(from(json).getMap(".") - .get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost() - .get("Brazil")); - assertThat(from(json).getMap(".") - .get("France")).isEqualTo(inventory.getCountryDeliveryCost() - .get("France")); - assertThat(from(json).getMap(".") - .get("Russia")).isEqualTo(inventory.getCountryDeliveryCost() - .get("Russia")); - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java deleted file mode 100644 index cc245dab66..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.jackson.deserialization.jsoncreator; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonCreatorUnitTest { - - @Test - public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { - - // arrange - String authorJson = "{" + " \"christianName\": \"Alex\"," + " \"surname\": \"Theedom\"" + "}"; - - // act - final Author author = new ObjectMapper().readerFor(Author.class) - .readValue(authorJson); - - // assert - assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName()); - assertThat(from(authorJson).getString("surname")).isEqualTo(author.getLastName()); - - /* - { - "christianName": "Alex", - "surname": "Theedom" - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java deleted file mode 100644 index 1bcde998d6..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.jackson.deserialization.jsondeserialize; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; -import java.text.SimpleDateFormat; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonDeserializeUnitTest { - - @Test - public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws IOException { - - // arrange - String bookJson = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"title\":\"Effective Java\",\"authors\":[{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"firstName\":\"Joshua\",\"lastName\":\"Bloch\"}],\"price\":0,\"published\":\"25-12-2017 13:30:25\",\"pages\":null,\"isbn\":null}"; - - // act - Book book = new ObjectMapper().readerFor(Book.class) - .readValue(bookJson); - - // assert - SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); - assertThat(from(bookJson).getString("published")).isEqualTo(df.format(book.getPublished())); - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java deleted file mode 100644 index 4379fe376c..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.jackson.deserialization.jsonsetter; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonSetterUnitTest { - - @Test - public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException { - - // arrange - String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}"; - - // act - Author author = new ObjectMapper().readerFor(Author.class) - .readValue(json); - - // assert - assertThat(from(json).getList("publications") - .size()).isEqualTo(author.getItems() - .size()); - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/exception/UserWithRootNamespace.java b/jackson/src/test/java/com/baeldung/jackson/exception/UserWithRootNamespace.java new file mode 100644 index 0000000000..bf8c85efba --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/exception/UserWithRootNamespace.java @@ -0,0 +1,18 @@ +package com.baeldung.jackson.exception; + +import com.fasterxml.jackson.annotation.JsonRootName; + +@JsonRootName(value = "user", namespace="users") +public class UserWithRootNamespace { + public int id; + public String name; + + public UserWithRootNamespace() { + super(); + } + + public UserWithRootNamespace(final int id, final String name) { + this.id = id; + this.name = name; + } +} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/Author.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/Author.java deleted file mode 100644 index 3d5a9c907c..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/Author.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.jackson.general.jsonfilter; - -import com.baeldung.jackson.domain.Person; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonFilter; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonFilter("authorFilter") -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java deleted file mode 100644 index 6fcc57faa7..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.jackson.general.jsonfilter; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ser.FilterProvider; -import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; -import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonFilterUnitTest { - - @Test - public void whenSerializingUsingJsonFilter_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - FilterProvider filters = new SimpleFilterProvider().addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); - - // act - String result = new ObjectMapper().writer(filters) - .writeValueAsString(author); - - // assert - assertThat(from(result).getList("items")).isNull(); - - /* - { - "lastName": "Theedom" - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java deleted file mode 100644 index e2eb4aa48a..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.jackson.general.jsonformat; - -import com.baeldung.jackson.domain.Author; -import com.baeldung.jackson.domain.Item; -import com.fasterxml.jackson.annotation.JsonFormat; - -import java.math.BigDecimal; -import java.util.Date; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Book extends Item { - - private String ISBN; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss") - private Date published; - private BigDecimal pages; - - public Book() { - } - - public Book(String title, Author author) { - super(title, author); - } - - public String getISBN() { - return ISBN; - } - - public void setISBN(String ISBN) { - this.ISBN = ISBN; - } - - public Date getPublished() { - return published; - } - - public void setPublished(Date published) { - this.published = published; - } - - public BigDecimal getPages() { - return pages; - } - - public void setPages(BigDecimal pages) { - this.pages = pages; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java deleted file mode 100644 index 1fe217cef6..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.jackson.general.jsonformat; - -import com.baeldung.jackson.domain.Author; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonFormatUnitTest { - - @Test - public void whenSerializingUsingJsonFormat_thenCorrect() throws JsonProcessingException, ParseException { - - // arrange - SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - - String toParse = "20-12-2014 14:30:00"; - Date date = df.parse(toParse); - - Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF")); - book.setPublished(date); - - // act - String result = new ObjectMapper().writeValueAsString(book); - - // assert - assertThat(from(result).getString("published")).isEqualTo(toParse); - - /* - { - "id": "762b39be-fd5b-489e-8688-aeb3b9bbf019", - "title": "Design Patterns: Elements of Reusable Object-oriented Software", - "authors": [ - { - "id": "6941b780-0f54-4259-adcb-85523c8f25f4", - "firstName": "The", - "lastName": "GoF", - "items": [] - } - ], - "price": 0, - "published": "20-12-2014 02:30:00", - "pages": null, - "isbn": null - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java deleted file mode 100644 index 1f36b95b2a..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.jackson.general.jsonidentityinfo; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java deleted file mode 100644 index 80dd9c275e..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.jackson.general.jsonidentityinfo; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java deleted file mode 100644 index bad6562122..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.jackson.general.jsonidentityinfo; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/JsonIdentityInfoUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/JsonIdentityInfoUnitTest.java deleted file mode 100644 index 014f1a8f69..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/JsonIdentityInfoUnitTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.jackson.general.jsonidentityinfo; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.util.Collections; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonIdentityInfoUnitTest { - - @Test - public void whenSerializingUsingJsonIdentityInfo_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - Course course = new Course("Java EE Introduction", author); - author.setItems(Collections.singletonList(course)); - course.setAuthors(Collections.singletonList(author)); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getString("items[0].authors")).isNotNull(); - - /* - Authors are included. - { - "id": "1b408bf9-5946-4a14-a112-fde2953a7fe7", - "firstName": "Alex", - "lastName": "Theedom", - "items": [ - { - "id": "5ed30530-f0a5-42eb-b786-be2c655da968", - "title": "Java EE Introduction", - "authors": [ - "1b408bf9-5946-4a14-a112-fde2953a7fe7" - ], - "price": 0, - "duration": 0, - "medium": null, - "level": null, - "prerequisite": null - } - ] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java deleted file mode 100644 index ea80814124..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.jackson.general.jsonidentityinfo; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Person { - - private UUID id; - private String firstName; - private String lastName; - - public Person() { - } - - public Person(String firstName, String lastName) { - this.id = UUID.randomUUID(); - this.firstName = firstName; - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public UUID getId() { - return id; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Author.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Author.java deleted file mode 100644 index 01552df729..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Author.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.jackson.general.jsonproperty; - -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Book.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Book.java deleted file mode 100644 index 100d9634f5..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Book.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.jackson.general.jsonproperty; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.math.BigDecimal; -import java.util.Date; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Book extends Item { - - private String ISBN; - private Date published; - private BigDecimal pages; - private String binding; - - public Book() { - } - - public Book(String title, Author author) { - super(title, author); - } - - public String getISBN() { - return ISBN; - } - - public void setISBN(String ISBN) { - this.ISBN = ISBN; - } - - public Date getPublished() { - return published; - } - - public void setPublished(Date published) { - this.published = published; - } - - public BigDecimal getPages() { - return pages; - } - - public void setPages(BigDecimal pages) { - this.pages = pages; - } - - @JsonProperty("binding") - public String coverBinding() { - return binding; - } - - @JsonProperty("binding") - public void configureBinding(String binding) { - this.binding = binding; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java deleted file mode 100644 index d7ee430d51..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.jackson.general.jsonproperty; - -import com.baeldung.jackson.domain.Person; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java deleted file mode 100644 index 0b88e7fc47..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.jackson.general.jsonproperty; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonPropertyUnitTest { - - @Test - public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException { - - // arrange - Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF")); - book.configureBinding("Hardback"); - - // act - String result = new ObjectMapper().writeValueAsString(book); - - // assert - assertThat(from(result).getString("binding")).isEqualTo("Hardback"); - - /* - { - "id": "cd941587-d1ae-4c2a-9a36-29533bf50411", - "title": "Design Patterns: Elements of Reusable Object-oriented Software", - "authors": [ - { - "id": "c8e26318-2f5b-4fa2-9fdc-6e99be021fca", - "firstName": "The", - "lastName": "GoF", - "items": [] - } - ], - "price": 0, - "published": null, - "pages": null, - "isbn": null, - "binding": "Hardback" - } - */ - - } - - @Test - public void whenDeserializingUsingJsonProperty_thenCorrect() throws IOException { - - // arrange - String result = "{\"id\":\"cd941587-d1ae-4c2a-9a36-29533bf50411\",\"title\":\"Design Patterns: Elements of Reusable Object-oriented Software\",\"authors\":[{\"id\":\"c8e26318-2f5b-4fa2-9fdc-6e99be021fca\",\"firstName\":\"The\",\"lastName\":\"GoF\"}],\"binding\":\"Hardback\"}"; - - // act - Book book = new ObjectMapper().readerFor(Book.class) - .readValue(result); - - // assert - assertThat(book.coverBinding()).isEqualTo("Hardback"); - - } - -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java deleted file mode 100644 index 5130e037d5..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.jackson.general.jsonunwrapped; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonUnwrappedUnitTest { - - @Test - public void whenSerializingUsingJsonUnwrapped_thenCorrect() throws JsonProcessingException { - - // arrange - Order.Type preorderType = new Order.Type(); - preorderType.id = 10; - preorderType.name = "pre-order"; - - Order order = new Order(preorderType); - - // act - String result = new ObjectMapper().writeValueAsString(order); - - // assert - assertThat(from(result).getInt("id")).isEqualTo(10); - assertThat(from(result).getString("name")).isEqualTo("pre-order"); - - /* - { - "id": 10, - "name": "pre-order" - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/Order.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/Order.java deleted file mode 100644 index b1c5b832c3..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/Order.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.jackson.general.jsonunwrapped; - -import com.fasterxml.jackson.annotation.JsonUnwrapped; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Order { - - private UUID id; - - @JsonUnwrapped - private Type type; - private int internalAudit; - - public static class Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public Order(int internalAudit) { - this(); - this.type = new Type(); - this.type.id = 20; - this.type.name = "Order"; - this.internalAudit = internalAudit; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java deleted file mode 100644 index ab609008ce..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.jackson.general.jsonview; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonViewUnitTest { - - @Test - public void whenSerializingUsingJsonView_andInternalView_thenCorrect() throws JsonProcessingException { - - // arrange - Order order = new Order(120); - - // act - String result = new ObjectMapper().writerWithView(Views.Internal.class) - .writeValueAsString(order); - - // assert - assertThat(from(result).getUUID("id")).isNotNull(); - assertThat(from(result).getObject("type", Order.Type.class)).isNotNull(); - assertThat(from(result).getInt("internalAudit")).isEqualTo(120); - - /* - { - "id": "33806388-795b-4812-b90a-60292111bc5c", - "type": { - "id": 20, - "name": "Order" - }, - "internalAudit": 120 - } - */ - - } - - @Test - public void whenSerializingUsingJsonView_andPublicView_thenCorrect() throws JsonProcessingException { - - // arrange - Order order = new Order(120); - - // act - String result = new ObjectMapper().writerWithView(Views.Public.class) - .writeValueAsString(order); - - // assert - assertThat(from(result).getUUID("id")).isNotNull(); - assertThat(from(result).getObject("type", Order.Type.class)).isNotNull(); - assertThat(result).doesNotContain("internalAudit"); - - /* - { - "id": "5184d5fc-e359-4cdf-93fa-4054025bef4e", - "type": { - "id": 20, - "name": "Order" - } - } - */ - - } - -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Order.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Order.java deleted file mode 100644 index 69adf1b59d..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Order.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.jackson.general.jsonview; - -import com.fasterxml.jackson.annotation.JsonView; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Order { - - @JsonView(Views.Public.class) - private UUID id; - - @JsonView(Views.Public.class) - private Type type; - - @JsonView(Views.Internal.class) - private int internalAudit; - - public static class Type { - public long id; - public String name; - } - - public Order() { - this.id = UUID.randomUUID(); - } - - public Order(Type type) { - this(); - this.type = type; - } - - public Order(int internalAudit) { - this(); - this.type = new Type(); - this.type.id = 20; - this.type.name = "Order"; - this.internalAudit = internalAudit; - } - - public UUID getId() { - return id; - } - - public Type getType() { - return type; - } - - public void setType(Type type) { - this.type = type; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Views.java b/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Views.java deleted file mode 100644 index b55997554d..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/Views.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.jackson.general.jsonview; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Views { - public static class Public { - } - - public static class Internal extends Public { - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Author.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Author.java deleted file mode 100644 index 02dd9470d7..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Author.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.jackson.general.reference; - -import com.fasterxml.jackson.annotation.JsonManagedReference; - -import java.util.ArrayList; -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Author extends Person { - - private List items = new ArrayList<>(); - - public Author(String firstName, String lastName) { - super(firstName, lastName); - } - - @JsonManagedReference - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java deleted file mode 100644 index 251d25a517..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.jackson.general.reference; - -import java.util.List; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Course extends Item { - - public enum Medium { - CLASSROOM, ONLINE - } - - public enum Level { - BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); - - private String name; - private int number; - - Level(String name, int number) { - this.name = name; - this.number = number; - } - - public String getName() { - return name; - } - } - - private float duration; - private Medium medium; - private Level level; - private List prerequisite; - - public Course(String title, Author author) { - super(title, author); - } - - public float getDuration() { - return duration; - } - - public void setDuration(float duration) { - this.duration = duration; - } - - public Medium getMedium() { - return medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public List getPrerequisite() { - return prerequisite; - } - - public void setPrerequisite(List prerequisite) { - this.prerequisite = prerequisite; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java deleted file mode 100644 index 5dd66a8ca3..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.jackson.general.reference; - -import com.fasterxml.jackson.annotation.JsonBackReference; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Item { - - private UUID id; - private String title; - - @JsonBackReference - private List authors = new ArrayList<>(); - private float price; - - public Item() { - } - - public Item(String title, Author author) { - this.id = UUID.randomUUID(); - this.title = title; - this.authors.add(author); - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java deleted file mode 100644 index 95c0b35b8b..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.jackson.general.reference; - -import java.util.UUID; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class Person { - - private UUID id; - private String firstName; - private String lastName; - - public Person() { - } - - public Person(String firstName, String lastName) { - this.id = UUID.randomUUID(); - this.firstName = firstName; - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public UUID getId() { - return id; - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java deleted file mode 100644 index 7a52a69656..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.jackson.general.reference; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.util.Collections; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class ReferenceUnitTest { - - @Test - public void whenSerializingUsingReference_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - Course course = new Course("Java EE Introduction", author); - author.setItems(Collections.singletonList(course)); - course.setAuthors(Collections.singletonList(author)); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getString("items[0].authors")).isNull(); - - /* - Without references defined it throws StackOverflowError. - Authors excluded. - - { - "id": "9c45d9b3-4888-4c24-8b74-65ef35627cd7", - "firstName": "Alex", - "lastName": "Theedom", - "items": [ - { - "id": "f8309629-d178-4d67-93a4-b513ec4a7f47", - "title": "Java EE Introduction", - "price": 0, - "duration": 0, - "medium": null, - "level": null, - "prerequisite": null - } - ] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java deleted file mode 100644 index a3e29776a9..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonautodetect; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonAutoDetectUnitTest { - - @Test - public void whenSerializingUsingJsonAutoDetect_thenCorrect() throws JsonProcessingException { - - // arrange - Order order = new Order(1234567890); - - // act - String result = new ObjectMapper().writeValueAsString(order); - - // assert - assertThat(from(result).getInt("internalAudit")).isEqualTo(1234567890); - - /* - With @JsonAutoDetect - { - "id": "c94774d9-de8f-4244-85d5-624bd3a4567a", - "type": { - "id": 20, - "name": "Order" - }, - "internalAudit": 1234567890 - } - - Without @JsonAutoDetect - { - "id": "c94774d9-de8f-4244-85d5-624bd3a4567a", - "type": { - "id": 20, - "name": "Order" - } - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignore/JsonIgnoreUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignore/JsonIgnoreUnitTest.java deleted file mode 100644 index 89e3c15f04..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignore/JsonIgnoreUnitTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignore; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonIgnoreUnitTest { - - @Test - public void whenSerializingUsingJsonIgnore_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getString("firstName")).isEqualTo("Alex"); - assertThat(from(result).getString("lastName")).isEqualTo("Theedom"); - assertThat(from(result).getString("id")).isNull(); - - /* - { - "firstName": "Alex", - "lastName": "Theedom", - "items": [] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoreproperties/JsonIgnorePropertiesUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoreproperties/JsonIgnorePropertiesUnitTest.java deleted file mode 100644 index be20d242c9..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoreproperties/JsonIgnorePropertiesUnitTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignoreproperties; - -import com.baeldung.jackson.domain.Author; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonIgnorePropertiesUnitTest { - - @Test - public void whenSerializingUsingJsonIgnoreProperties_thenCorrect() throws JsonProcessingException { - - // arrange - Course course = new Course("Spring Security", new Author("Eugen", "Paraschiv")); - course.setMedium(Course.Medium.ONLINE); - - // act - String result = new ObjectMapper().writeValueAsString(course); - - // assert - assertThat(from(result).getString("medium")).isNull(); - - /* - { - "id": "ef0c8d2b-b088-409e-905c-95ac88dc0ed0", - "title": "Spring Security", - "authors": [ - { - "id": "47a4f498-b0f3-4daf-909f-d2c35a0fe3c2", - "firstName": "Eugen", - "lastName": "Paraschiv", - "items": [] - } - ], - "price": 0, - "duration": 0, - "level": null, - "prerequisite": null - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoretype/JsonIgnoreTypeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoretype/JsonIgnoreTypeUnitTest.java deleted file mode 100644 index e8917ff526..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonignoretype/JsonIgnoreTypeUnitTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.jackson.inclusion.jsonignoretype; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonIgnoreTypeUnitTest { - - @Test - public void whenSerializingUsingJsonIgnoreType_thenCorrect() throws JsonProcessingException { - - // arrange - Order.Type type = new Order.Type(); - type.id = 10; - type.name = "Pre-order"; - - Order order = new Order(type); - - // act - String result = new ObjectMapper().writeValueAsString(order); - - // assert - assertThat(from(result).getString("id")).isNotNull(); - assertThat(from(result).getString("type")).isNull(); - - /* - {"id":"ac2428da-523e-443c-a18a-4ea4d2791fea"} - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java deleted file mode 100644 index ca4c4b751a..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.jackson.inclusion.jsoninclude; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonIncludeUnitTest { - - @Test - public void whenSerializingUsingJsonInclude_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", null); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getString("firstName")).isEqualTo("Alex"); - assertThat(result).doesNotContain("lastName"); - - /* - { - "id": "e8bb4802-6e0c-4fa5-9f68-c233272399cd", - "firstName": "Alex", - "items": [] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/custom/CustomUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/miscellaneous/custom/CustomUnitTest.java deleted file mode 100644 index 8f90c02875..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/custom/CustomUnitTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.jackson.miscellaneous.custom; - -import com.baeldung.jackson.domain.Author; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class CustomUnitTest { - - @Test - public void whenSerializingUsingCustom_thenCorrect() throws JsonProcessingException { - - // arrange - Course course = new Course("Spring Security", new Author("Eugen", "Paraschiv")); - course.setMedium(Course.Medium.ONLINE); - - // act - String result = new ObjectMapper().writeValueAsString(course); - - // assert - assertThat(from(result).getString("title")).isEqualTo("Spring Security"); - - /* - { - "title": "Spring Security", - "price": 0, - "id": "7dfd4db9-1175-432f-a53b-687423f7bb9b", - "duration": 0, - "authors": [ - { - "id": "da0738f6-033c-4974-8d87-92820e5ccf27", - "firstName": "Eugen", - "lastName": "Paraschiv", - "items": [] - } - ], - "medium": "ONLINE" - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/disable/DisableUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/miscellaneous/disable/DisableUnitTest.java deleted file mode 100644 index f9bc14291e..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/disable/DisableUnitTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.jackson.miscellaneous.disable; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class DisableUnitTest { - - @Test - public void whenSerializingUsingDisable_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(author); - - // assert - assertThat(from(result).getList("items")).isNull(); - - /* - { - "lastName": "Theedom", - "firstName": "Alex", - "id": "de4afbb4-b24d-45c8-bb00-fd6b9acb42f1" - } - */ - - // act - mapper = new ObjectMapper(); - mapper.disable(MapperFeature.USE_ANNOTATIONS); - result = mapper.writeValueAsString(author); - - // assert - assertThat(from(result).getList("items")).isNotNull(); - - /* - { - "id": "81e6ed72-6b27-4fe9-a36f-e3171c5b55ef", - "firstName": "Alex", - "lastName": "Theedom", - "items": [] - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/mixin/MixInUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/miscellaneous/mixin/MixInUnitTest.java deleted file mode 100644 index 732cda58d0..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/miscellaneous/mixin/MixInUnitTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.jackson.miscellaneous.mixin; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.util.List; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class MixInUnitTest { - - @Test - public void whenSerializingUsingMixIn_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getList("items")).isNotNull(); - - /* - { - "id": "f848b076-00a4-444a-a50b-328595dd9bf5", - "firstName": "Alex", - "lastName": "Theedom", - "items": [] - } - */ - - ObjectMapper mapper = new ObjectMapper(); - mapper.addMixIn(List.class, IgnoreListMixIn.class); - - result = mapper.writeValueAsString(author); - - // assert - assertThat(from(result).getList("items")).isNull(); - - /* - { - "id": "9ffefb7d-e56f-447c-9009-e92e142f8347", - "firstName": "Alex", - "lastName": "Theedom" - } - */ - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java deleted file mode 100644 index e922cf9976..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.baeldung.jackson.polymorphism; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class PolymorphismUnitTest { - - @Test - public void whenSerializingUsingPolymorphism_thenCorrect() throws JsonProcessingException { - - // arrange - Order.InternalType internalType = new Order.InternalType(); - internalType.id = 250; - internalType.name = "staff"; - - Order order = new Order(internalType); - - // act - String result = new ObjectMapper().writeValueAsString(order); - - // assert - assertThat(from(result).getString("type.ordertype")).isEqualTo("internal"); - - /* - { - "id": "7fc898e3-b4e7-41b0-8ffa-664cf3663f2e", - "type": { - "ordertype": "internal", - "id": 250, - "name": "staff" - } - } - */ - - } - - @Test - public void whenDeserializingPolymorphic_thenCorrect() throws IOException { - - // arrange - String orderJson = "{\"type\":{\"ordertype\":\"internal\",\"id\":100,\"name\":\"directors\"}}"; - - // act - Order order = new ObjectMapper().readerFor(Order.class) - .readValue(orderJson); - - // assert - assertThat(from(orderJson).getString("type.ordertype")).isEqualTo("internal"); - assertThat(((Order.InternalType) order.getType()).name).isEqualTo("directors"); - assertThat(((Order.InternalType) order.getType()).id).isEqualTo(100); - assertThat(order.getType() - .getClass()).isEqualTo(Order.InternalType.class); - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonanygetter/JsonAnyGetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonanygetter/JsonAnyGetterUnitTest.java deleted file mode 100644 index 7a786e0bd6..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonanygetter/JsonAnyGetterUnitTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.jackson.serialization.jsonanygetter; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.util.Map; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonAnyGetterUnitTest { - - @Test - public void whenSerializingUsingJsonAnyGetter_thenCorrect() throws JsonProcessingException { - - // arrange - Inventory inventory = new Inventory(); - Map countryDeliveryCost = inventory.getCountryDeliveryCost(); - inventory.setLocation("France"); - - countryDeliveryCost.put("USA", 10.00f); - countryDeliveryCost.put("UK", 15.00f); - - // act - String result = new ObjectMapper().writeValueAsString(inventory); - - // assert - assertThat(from(result).getString("location")).isEqualTo("France"); - assertThat(from(result).getFloat("USA")).isEqualTo(10.00f); - assertThat(from(result).getFloat("UK")).isEqualTo(15.00f); - - /* - { - "location": "France", - "USA": 10, - "UK": 15 - } - */ - - } - -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsongetter/JsonGetterUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsongetter/JsonGetterUnitTest.java deleted file mode 100644 index 4bc9c51e83..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsongetter/JsonGetterUnitTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.jackson.serialization.jsongetter; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonGetterUnitTest { - - @Test - public void whenSerializingUsingJsonGetter_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(from(result).getList("publications")).isNotNull(); - assertThat(from(result).getList("items")).isNull(); - - /* - { - "firstName": "Alex", - "lastName": "Theedom", - "publications": [] - } - */ - - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonpropertyorder/JsonPropertyOrderUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonpropertyorder/JsonPropertyOrderUnitTest.java deleted file mode 100644 index 77ef85ed73..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonpropertyorder/JsonPropertyOrderUnitTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.jackson.serialization.jsonpropertyorder; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; -import static org.hamcrest.MatcherAssert.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonPropertyOrderUnitTest { - - @Test - public void whenSerializingUsingJsonPropertyOrder_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - String result = new ObjectMapper().writeValueAsString(author); - - // assert - assertThat(result, matchesJsonSchemaInClasspath("author-jsonpropertyorder-schema.json")); - - // NOTE: property order is not enforced by the JSON specification. - - /* - { - "items": [], - "firstName": "Alex", - "lastName": "Theedom", - "id": "fd277638-9b6e-49f7-81c1-bc52f165245b" - } - */ - - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java deleted file mode 100644 index f0f0913aee..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.jackson.serialization.jsonrawvalue; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonRawValueUnitTest { - - @Test - public void whenSerializingUsingJsonRawValue_thenCorrect() throws JsonProcessingException { - - // arrange - String customerConfig = "{\"colour\":\"red\",\"device\":\"mobile\",\"orientation\":\"landscape\"}"; - Customer customer = new Customer("Alex", "Theedom"); - customer.setConfiguration("{\"colour\":\"red\",\"device\":\"mobile\",\"orientation\":\"landscape\"}"); - - // act - String result = new ObjectMapper().writeValueAsString(customer); - - // assert - assertThat(result.contains(customerConfig)); - - /* - { - "firstName": "Alex", - "lastName": "Theedom", - "publications": [] - } - */ - - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrootname/JsonRootNameUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrootname/JsonRootNameUnitTest.java deleted file mode 100644 index cb54e63079..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrootname/JsonRootNameUnitTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.jackson.serialization.jsonrootname; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonRootNameUnitTest { - - @Test - public void whenSerializingUsingJsonRootName_thenCorrect() throws JsonProcessingException { - - // arrange - Author author = new Author("Alex", "Theedom"); - - // act - ObjectMapper mapper = new ObjectMapper(); - mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); - String result = mapper.writeValueAsString(author); - - // assert - assertThat(from(result).getString("writer.firstName")).isEqualTo("Alex"); - assertThat(from(result).getString("author.firstName")).isNull(); - - /* - { - "writer": { - "id": "0f50dca6-3dd7-4801-a334-fd1614276389", - "firstName": "Alex", - "lastName": "Theedom", - "items": [] - } - } - */ - - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonserialize/JsonSerializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonserialize/JsonSerializeUnitTest.java deleted file mode 100644 index cca018e78d..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonserialize/JsonSerializeUnitTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.jackson.serialization.jsonserialize; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.text.ParseException; -import java.text.SimpleDateFormat; - -import static io.restassured.path.json.JsonPath.from; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonSerializeUnitTest { - - @Test - public void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingException, ParseException { - - // arrange - Author joshuaBloch = new Author("Joshua", "Bloch"); - Book book = new Book("Effective Java", joshuaBloch); - - SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); - String toParse = "25-12-2017 13:30:25"; - book.setPublished(df.parse(toParse)); - - // act - String result = new ObjectMapper().writeValueAsString(book); - - // assert - assertThat(from(result).getString("published")).isEqualTo(toParse); - - /* - { - "id": "957c43f2-fa2e-42f9-bf75-6e3d5bb6960a", - "title": "Effective Java", - "authors": [ - { - "id": "9bcd817d-0141-42e6-8f04-e5aaab0980b6", - "firstName": "Joshua", - "lastName": "Bloch", - "items": [] - } - ], - "price": 0, - "published": "25-12-2017 13:30:25", - "pages": null, - "isbn": null - } - */ - - } -} diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonvalue/JsonValueUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonvalue/JsonValueUnitTest.java deleted file mode 100644 index 465daf13f5..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonvalue/JsonValueUnitTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.jackson.serialization.jsonvalue; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Source code github.com/readlearncode - * - * @author Alex Theedom www.readlearncode.com - * @version 1.0 - */ -public class JsonValueUnitTest { - - @Test - public void whenSerializingUsingJsonValue_thenCorrect() throws JsonProcessingException { - - // act - String result = new ObjectMapper().writeValueAsString(Course.Level.ADVANCED); - - // assert - assertThat(result).isEqualTo("\"Advanced\""); - - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java index 935777bad1..ee11f8f20e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java @@ -14,6 +14,7 @@ import java.util.TimeZone; import org.junit.Test; +import com.baeldung.jackson.annotation.AliasBean; import com.baeldung.jackson.annotation.BeanWithCreator; import com.baeldung.jackson.annotation.BeanWithCustomAnnotation; import com.baeldung.jackson.annotation.BeanWithFilter; @@ -36,6 +37,7 @@ import com.baeldung.jackson.date.EventWithSerializer; import com.baeldung.jackson.dtos.MyMixInForIgnoreType; import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue; import com.baeldung.jackson.exception.UserWithRoot; +import com.baeldung.jackson.exception.UserWithRootNamespace; import com.baeldung.jackson.jsonview.Item; import com.baeldung.jackson.jsonview.Views; import com.fasterxml.jackson.core.JsonProcessingException; @@ -46,6 +48,7 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class JacksonAnnotationUnitTest { @@ -372,5 +375,45 @@ public class JacksonAnnotationUnitTest { assertThat(result, containsString("1")); assertThat(result, containsString("name")); } + + @Test + public void whenDeserializingUsingJsonAlias_thenCorrect() throws IOException { + + // arrange + String json = "{\"fName\": \"John\", \"lastName\": \"Green\"}"; + + // act + AliasBean aliasBean = new ObjectMapper().readerFor(AliasBean.class).readValue(json); + + // assert + assertThat(aliasBean.getFirstName(), is("John")); + } + + @Test + public void whenSerializingUsingXMLRootNameWithNameSpace_thenCorrect() throws JsonProcessingException { + + // arrange + UserWithRootNamespace author = new UserWithRootNamespace(1, "John"); + + // act + ObjectMapper mapper = new XmlMapper(); + mapper = mapper.enable(SerializationFeature.WRAP_ROOT_VALUE).enable(SerializationFeature.INDENT_OUTPUT); + String result = mapper.writeValueAsString(author); + + // assert + assertThat(result, containsString("")); + + /* + + 3006b44a-cf62-4cfe-b3d8-30dc6c46ea96 + 1 + John + + + */ + + } + + } diff --git a/java-collections-maps-2/pom.xml b/java-collections-maps-2/pom.xml new file mode 100644 index 0000000000..b025c5e32d --- /dev/null +++ b/java-collections-maps-2/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + java-collections-maps-2 + 0.1.0-SNAPSHOT + java-collections-maps-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.eclipse.collections + eclipse-collections + ${eclipse-collections.version} + + + net.sf.trove4j + trove4j + 3.0.2 + + + it.unimi.dsi + fastutil + 8.1.0 + + + colt + colt + 1.2.0 + + + + + 8.2.0 + + + \ No newline at end of file diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/PrimitiveMaps.java b/java-collections-maps-2/src/main/java/com/baeldung/map/PrimitiveMaps.java new file mode 100644 index 0000000000..d835950c68 --- /dev/null +++ b/java-collections-maps-2/src/main/java/com/baeldung/map/PrimitiveMaps.java @@ -0,0 +1,69 @@ +package com.baeldung.map; + +import cern.colt.map.AbstractIntDoubleMap; +import cern.colt.map.OpenIntDoubleHashMap; +import gnu.trove.map.TDoubleIntMap; +import gnu.trove.map.hash.TDoubleIntHashMap; +import it.unimi.dsi.fastutil.ints.Int2BooleanMap; +import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap; +import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMap; +import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMaps; +import org.eclipse.collections.api.map.primitive.ImmutableIntIntMap; +import org.eclipse.collections.api.map.primitive.MutableIntIntMap; +import org.eclipse.collections.api.map.primitive.MutableObjectDoubleMap; +import org.eclipse.collections.impl.factory.primitive.IntIntMaps; +import org.eclipse.collections.impl.factory.primitive.ObjectDoubleMaps; + +public class PrimitiveMaps { + + public static void main(String[] args) { + + eclipseCollectionsMap(); + troveMap(); + coltMap(); + fastutilMap(); + } + + private static void fastutilMap() { + Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap(); + int2BooleanMap.put(1, true); + int2BooleanMap.put(7, false); + int2BooleanMap.put(4, true); + + boolean value = int2BooleanMap.get(1); + + Int2BooleanSortedMap int2BooleanSorted = Int2BooleanSortedMaps.EMPTY_MAP; + } + + private static void coltMap() { + AbstractIntDoubleMap map = new OpenIntDoubleHashMap(); + map.put(1, 4.5); + double value = map.get(1); + } + + private static void eclipseCollectionsMap() { + MutableIntIntMap mutableIntIntMap = IntIntMaps.mutable.empty(); + mutableIntIntMap.addToValue(1, 1); + + ImmutableIntIntMap immutableIntIntMap = IntIntMaps.immutable.empty(); + + MutableObjectDoubleMap dObject = ObjectDoubleMaps.mutable.empty(); + dObject.addToValue("price", 150.5); + dObject.addToValue("quality", 4.4); + dObject.addToValue("stability", 0.8); + } + + private static void troveMap() { + double[] doubles = new double[] {1.2, 4.5, 0.3}; + int[] ints = new int[] {1, 4, 0}; + + TDoubleIntMap doubleIntMap = new TDoubleIntHashMap(doubles, ints); + + doubleIntMap.put(1.2, 22); + doubleIntMap.put(4.5, 16); + + doubleIntMap.adjustValue(1.2, 1); + doubleIntMap.adjustValue(4.5, 4); + doubleIntMap.adjustValue(0.3, 7); + } +} diff --git a/java-dates-2/.gitignore b/java-dates-2/.gitignore new file mode 100644 index 0000000000..6471aabbcf --- /dev/null +++ b/java-dates-2/.gitignore @@ -0,0 +1,29 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml + +#jenv +.java-version \ No newline at end of file diff --git a/java-dates-2/pom.xml b/java-dates-2/pom.xml new file mode 100644 index 0000000000..c2464ed47f --- /dev/null +++ b/java-dates-2/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + com.baeldung + java-dates-2 + 0.1.0-SNAPSHOT + jar + java-dates-2 + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + java-dates-2 + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + 3.6.1 + 1.9 + 1.9 + + diff --git a/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java b/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java new file mode 100644 index 0000000000..b221c04199 --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.xmlgregoriancalendar; + +import org.junit.Test; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeConstants; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; + +public class XmlGregorianCalendarConverterUnitTest { + + @Test + public void fromLocalDateToXMLGregorianCalendar() throws DatatypeConfigurationException { + LocalDate localDate = LocalDate.of(2017, 4, 25); + XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(localDate.toString()); + + assertThat(xmlGregorianCalendar.getYear()).isEqualTo(localDate.getYear()); + assertThat(xmlGregorianCalendar.getMonth()).isEqualTo(localDate.getMonthValue()); + assertThat(xmlGregorianCalendar.getDay()).isEqualTo(localDate.getDayOfMonth()); + assertThat(xmlGregorianCalendar.getTimezone()).isEqualTo(DatatypeConstants.FIELD_UNDEFINED); + } + + @Test + public void fromXMLGregorianCalendarToLocalDate() throws DatatypeConfigurationException { + XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-04-25"); + LocalDate localDate = LocalDate.of(xmlGregorianCalendar.getYear(), xmlGregorianCalendar.getMonth(), xmlGregorianCalendar.getDay()); + + assertThat(localDate.getYear()).isEqualTo(xmlGregorianCalendar.getYear()); + assertThat(localDate.getMonthValue()).isEqualTo(xmlGregorianCalendar.getMonth()); + assertThat(localDate.getDayOfMonth()).isEqualTo(xmlGregorianCalendar.getDay()); + } + +} diff --git a/java-streams-2/README.md b/java-streams-2/README.md new file mode 100644 index 0000000000..83ef97686f --- /dev/null +++ b/java-streams-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) + diff --git a/java-streams-2/pom.xml b/java-streams-2/pom.xml new file mode 100644 index 0000000000..cd89a1a80f --- /dev/null +++ b/java-streams-2/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + com.baeldung.javastreams2 + javastreams2 + 1.0 + jar + + + org.openjdk.jmh + jmh-core + 1.21 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.21 + + + junit + junit + 4.12 + test + jar + + + org.assertj + assertj-core + 3.11.1 + test + + + Stream Reduce + + UTF-8 + 1.8 + 1.8 + + \ No newline at end of file diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java b/java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java new file mode 100644 index 0000000000..79c557524d --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java @@ -0,0 +1,39 @@ +package com.baeldung.reduce.application; + +import com.baeldung.reduce.entities.User; +import com.baeldung.reduce.utilities.NumberUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Application { + + public static void main(String[] args) { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); + System.out.println(result1); + + int result2 = numbers.stream().reduce(0, Integer::sum); + System.out.println(result2); + + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element); + System.out.println(result3); + + String result4 = letters.stream().reduce("", String::concat); + System.out.println(result4); + + String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); + System.out.println(result5); + + List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); + int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + System.out.println(result6); + + String result7 = letters.parallelStream().reduce("", String::concat); + System.out.println(result7); + + int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + System.out.println(result8); + } +} diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java b/java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java new file mode 100644 index 0000000000..af4a9276a9 --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java @@ -0,0 +1,52 @@ +package com.baeldung.reduce.benchmarks; + +import com.baeldung.reduce.entities.User; +import java.util.ArrayList; +import java.util.List; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +public class JMHStreamReduceBenchMark { + + private final List userList = createUsers(); + + public static void main(String[] args) throws RunnerException { + + Options options = new OptionsBuilder() + .include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true).shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } + + private List createUsers() { + List users = new ArrayList<>(); + for (int i = 0; i <= 1000000; i++) { + users.add(new User("John" + i, i)); + } + return users; + } + + @Benchmark + public Integer executeReduceOnParallelizedStream() { + return this.userList + .parallelStream() + .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + } + + @Benchmark + public Integer executeReduceOnSequentialStream() { + return this.userList + .stream() + .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + } +} diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java b/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java new file mode 100644 index 0000000000..a17c6a02b6 --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java @@ -0,0 +1,25 @@ +package com.baeldung.reduce.entities; + +public class User { + + private final String name; + private final int age; + + public User(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return "User{" + "name=" + name + ", age=" + age + '}'; + } +} diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java b/java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java new file mode 100644 index 0000000000..a7a4b8df29 --- /dev/null +++ b/java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java @@ -0,0 +1,52 @@ +package com.baeldung.reduce.utilities; + +import java.util.List; +import java.util.function.BiFunction; +import java.util.logging.Level; +import java.util.logging.Logger; + +public abstract class NumberUtils { + + private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName()); + + public static int divideListElements(List values, Integer divider) { + return values.stream() + .reduce(0, (a, b) -> { + try { + return a / divider + b / divider; + } catch (ArithmeticException e) { + LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); + } + return 0; + }); + } + + public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) { + return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider)); + } + + public static int divideListElementsWithApplyFunctionMethod(List values, int divider) { + BiFunction division = (a, b) -> a / b; + return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider)); + } + + private static int divide(int value, int factor) { + int result = 0; + try { + result = value / factor; + } catch (ArithmeticException e) { + LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); + } + return result; + } + + private static int applyFunction(BiFunction function, int a, int b) { + try { + return function.apply(a, b); + } + catch(Exception e) { + LOGGER.log(Level.INFO, "Exception thrown!"); + } + return 0; + } +} diff --git a/java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java b/java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java new file mode 100644 index 0000000000..564d614017 --- /dev/null +++ b/java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java @@ -0,0 +1,79 @@ +package com.baeldung.reduce.tests; + +import com.baeldung.reduce.entities.User; +import com.baeldung.reduce.utilities.NumberUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class StreamReduceUnitTest { + + @Test + public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); + assertThat(result).isEqualTo(21); + } + + @Test + public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result = numbers.stream().reduce(0, Integer::sum); + assertThat(result).isEqualTo(21); + } + + @Test + public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", (partialString, element) -> partialString + element); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", String::concat); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); + assertThat(result).isEqualTo("ABCDE"); + } + + @Test + public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() { + List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); + int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + assertThat(result).isEqualTo(65); + } + + @Test + public void givenStringList_whenReduceWithParallelStream_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.parallelStream().reduce("", String::concat); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21); + } + + @Test + public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); + } + + @Test + public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21); + } +} diff --git a/java-streams/README.md b/java-streams/README.md index b931c0d7d9..e294e5aee1 100644 --- a/java-streams/README.md +++ b/java-streams/README.md @@ -17,3 +17,4 @@ - [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda) - [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count) - [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api) +- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams) diff --git a/javax-servlets/src/main/java/com/baeldung/filters/EmptyParamFilter.java b/javax-servlets/src/main/java/com/baeldung/filters/EmptyParamFilter.java new file mode 100644 index 0000000000..b0b5392237 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/filters/EmptyParamFilter.java @@ -0,0 +1,35 @@ +package com.baeldung.filters; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import java.io.IOException; + +@WebFilter(urlPatterns = "/uppercase") +public class EmptyParamFilter implements Filter { + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, + FilterChain filterChain) throws IOException, ServletException { + String inputString = servletRequest.getParameter("input"); + + if (inputString != null && inputString.matches("[A-Za-z0-9]+")) { + filterChain.doFilter(servletRequest, servletResponse); + } else { + servletResponse.getWriter().println("Missing input parameter"); + } + } + + @Override + public void destroy() { + } + +} diff --git a/javax-servlets/src/main/java/com/baeldung/listeners/AppListener.java b/javax-servlets/src/main/java/com/baeldung/listeners/AppListener.java new file mode 100644 index 0000000000..ed16dd1654 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/listeners/AppListener.java @@ -0,0 +1,21 @@ +package com.baeldung.listeners; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +@WebListener +public class AppListener implements ServletContextListener { + + @Override + public void contextInitialized(ServletContextEvent event) { + ServletContext context = event.getServletContext(); + context.setAttribute("counter", 0); + } + + @Override + public void contextDestroyed(ServletContextEvent event) { + + } +} diff --git a/javax-servlets/src/main/java/com/baeldung/listeners/RequestListener.java b/javax-servlets/src/main/java/com/baeldung/listeners/RequestListener.java new file mode 100644 index 0000000000..7f0c37b666 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/listeners/RequestListener.java @@ -0,0 +1,24 @@ +package com.baeldung.listeners; + +import javax.servlet.ServletContext; +import javax.servlet.ServletRequestEvent; +import javax.servlet.ServletRequestListener; +import javax.servlet.annotation.WebListener; +import javax.servlet.http.HttpServletRequest; + +@WebListener +public class RequestListener implements ServletRequestListener { + + @Override + public void requestInitialized(ServletRequestEvent event) { + } + + @Override + public void requestDestroyed(ServletRequestEvent event) { + HttpServletRequest request = (HttpServletRequest)event.getServletRequest(); + if (!request.getServletPath().equals("/counter")) { + ServletContext context = event.getServletContext(); + context.setAttribute("counter", (int)context.getAttribute("counter") + 1); + } + } +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/CounterServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/CounterServlet.java new file mode 100644 index 0000000000..a11f084db2 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/CounterServlet.java @@ -0,0 +1,21 @@ +package com.baeldung.servlets; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +@WebServlet(urlPatterns = "/counter", name = "counterServlet") +public class CounterServlet extends HttpServlet { + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + PrintWriter out = response.getWriter(); + + int count = (int)request.getServletContext().getAttribute("counter"); + + out.println("Request counter: " + count); + } + +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/UppercaseServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/UppercaseServlet.java new file mode 100644 index 0000000000..766ec2e6ff --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/UppercaseServlet.java @@ -0,0 +1,20 @@ +package com.baeldung.servlets; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +@WebServlet(urlPatterns = "/uppercase", name = "uppercaseServlet") +public class UppercaseServlet extends HttpServlet { + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + String inputString = request.getParameter("input").toUpperCase(); + + PrintWriter out = response.getWriter(); + + out.println(inputString); + } +} diff --git a/jhipster/pom.xml b/jhipster/pom.xml index 3fcc53b354..c50aac0c7a 100644 --- a/jhipster/pom.xml +++ b/jhipster/pom.xml @@ -15,6 +15,13 @@ ../parent-boot-1 + + + org.hibernate + hibernate-java8 + + + jhipster-monolithic jhipster-microservice diff --git a/jjwt/README.md b/jjwt/README.md index 54a5226056..ed18363dfc 100644 --- a/jjwt/README.md +++ b/jjwt/README.md @@ -42,7 +42,6 @@ Available commands (assumes httpie - https://github.com/jkbrzt/httpie): Parse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim ``` -The Baeldung post that compliments this repo can be found [here](http://www.baeldung.com/) ## Relevant articles: diff --git a/json/README.md b/json/README.md index c0ca4b00ef..3670b4b9ad 100644 --- a/json/README.md +++ b/json/README.md @@ -13,3 +13,4 @@ - [Get a Value by Key in a JSONArray](https://www.baeldung.com/java-jsonarray-get-value-by-key) - [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration) - [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) +- [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping) diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index 507e5820d4..3d2c7337b0 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -19,6 +19,14 @@ exposed https://dl.bintray.com/kotlin/exposed + + + false + + kotlinx + bintray + https://dl.bintray.com/kotlin/kotlinx + @@ -112,9 +120,56 @@ 3.3.0 pom + + + + junit + junit + ${junit.version} + test + + + + com.google.guava + guava + 27.1-jre + + + + org.jetbrains.kotlinx + kotlinx-collections-immutable + 0.1 + + + + + io.mockk + mockk + ${mockk.version} + test + + + net.bytebuddy + byte-buddy + 1.8.13 + compile + + + net.bytebuddy + byte-buddy-agent + 1.8.13 + compile + + + org.objenesis + objenesis + 2.6 + compile + + 4.12 1.5.0 4.1.0 3.0.4 @@ -125,6 +180,7 @@ 3.10.0 1.4.197 0.10.4 + 1.9.3 diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt new file mode 100644 index 0000000000..971f2de4c2 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt @@ -0,0 +1,27 @@ +package com.baeldung.kotlin.immutable + +import junit.framework.Assert.assertEquals +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.immutableListOf +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException + +class KotlinxImmutablesUnitTest{ + + + @Rule + @JvmField + var ee : ExpectedException = ExpectedException.none() + + @Test + fun givenKICLList_whenAddTried_checkExceptionThrown(){ + + val list: ImmutableList = immutableListOf("I", "am", "immutable") + + list.add("My new item") + + assertEquals(listOf("I", "am", "immutable"), list) + + } +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt new file mode 100644 index 0000000000..62c4a4eb88 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt @@ -0,0 +1,73 @@ +package com.baeldung.kotlin.immutable + +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableSet +import junit.framework.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException + +class ReadOnlyUnitTest{ + + @Test + fun givenReadOnlyList_whenCastToMutableList_checkNewElementsAdded(){ + + val list: List = listOf("This", "Is", "Totally", "Immutable") + + (list as MutableList)[2] = "Not" + + assertEquals(listOf("This", "Is", "Not", "Immutable"), list) + + } + + @Rule + @JvmField + var ee : ExpectedException = ExpectedException.none() + + @Test + fun givenImmutableList_whenAddTried_checkExceptionThrown(){ + + val list: List = ImmutableList.of("I", "am", "actually", "immutable") + + ee.expect(UnsupportedOperationException::class.java) + + (list as MutableList).add("Oops") + + } + + @Test + fun givenMutableList_whenCopiedAndAddTried_checkExceptionThrown(){ + + val mutableList : List = listOf("I", "Am", "Definitely", "Immutable") + + (mutableList as MutableList)[2] = "100% Not" + + assertEquals(listOf("I", "Am", "100% Not", "Immutable"), mutableList) + + val list: List = ImmutableList.copyOf(mutableList) + + ee.expect(UnsupportedOperationException::class.java) + + (list as MutableList)[2] = "Really?" + + } + + @Test + fun givenImmutableSetBuilder_whenAddTried_checkExceptionThrown(){ + + val mutableList : List = listOf("Hello", "Baeldung") + val set: ImmutableSet = ImmutableSet.builder() + .add("I","am","immutable") + .addAll(mutableList) + .build() + + assertEquals(setOf("Hello", "Baeldung", "I", "am", "immutable"), set) + + ee.expect(UnsupportedOperationException::class.java) + + (set as MutableSet).add("Oops") + + } + + +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/AnnotationMockKUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/AnnotationMockKUnitTest.kt new file mode 100644 index 0000000000..56cd8b43eb --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/AnnotationMockKUnitTest.kt @@ -0,0 +1,44 @@ +package com.baeldung.mockk + +import io.mockk.MockKAnnotations +import io.mockk.every +import io.mockk.impl.annotations.InjectMockKs +import io.mockk.impl.annotations.MockK +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class InjectTestService { + lateinit var service1: TestableService + lateinit var service2: TestableService + + fun invokeService1(): String { + return service1.getDataFromDb("Test Param") + } +} + +class AnnotationMockKUnitTest { + + @MockK + lateinit var service1: TestableService + + @MockK + lateinit var service2: TestableService + + @InjectMockKs + var objectUnderTest = InjectTestService() + + @BeforeEach + fun setUp() = MockKAnnotations.init(this) + + @Test + fun givenServiceMock_whenCallingMockedMethod_thenCorrectlyVerified() { + // given + every { service1.getDataFromDb("Test Param") } returns "No" + // when + val result = objectUnderTest.invokeService1() + // then + assertEquals("No", result) + } + +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/BasicMockKUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/BasicMockKUnitTest.kt new file mode 100644 index 0000000000..df4c03be09 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/BasicMockKUnitTest.kt @@ -0,0 +1,92 @@ +package com.baeldung.mockk + +import io.mockk.* +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + + +class BasicMockKUnitTest { + + @Test + fun givenServiceMock_whenCallingMockedMethod_thenCorrectlyVerified() { + // given + val service = mockk() + every { service.getDataFromDb("Expected Param") } returns "Expected Output" + // when + val result = service.getDataFromDb("Expected Param") + // then + verify { service.getDataFromDb("Expected Param") } + assertEquals("Expected Output", result) + } + + @Test + fun givenServiceSpy_whenMockingOnlyOneMethod_thenOtherMethodsShouldBehaveAsOriginalObject() { + // given + val service = spyk() + every { service.getDataFromDb(any()) } returns "Mocked Output" + // when checking mocked method + val firstResult = service.getDataFromDb("Any Param") + // then + assertEquals("Mocked Output", firstResult) + // when checking not mocked method + val secondResult = service.doSomethingElse("Any Param") + // then + assertEquals("I don't want to!", secondResult) + } + + @Test + fun givenRelaxedMock_whenCallingNotMockedMethod_thenReturnDefaultValue() { + // given + val service = mockk(relaxed = true) + // when + val result = service.getDataFromDb("Any Param") + // then + assertEquals("", result) + } + + @Test + fun givenObject_whenMockingIt_thenMockedMethodShouldReturnProperValue() { + // given + val service = TestableService() + mockkObject(service) + // when calling not mocked method + val firstResult = service.getDataFromDb("Any Param") + // then return real response + assertEquals("Value from DB", firstResult) + + // when calling mocked method + every { service.getDataFromDb(any()) } returns "Mocked Output" + val secondResult = service.getDataFromDb("Any Param") + // then return mocked response + assertEquals("Mocked Output", secondResult) + } + + @Test + fun givenMock_whenCapturingParamValue_thenProperValueShouldBeCaptured() { + // given + val service = mockk() + val slot = slot() + every { service.getDataFromDb(capture(slot)) } returns "Expected Output" + // when + service.getDataFromDb("Expected Param") + // then + assertEquals("Expected Param", slot.captured) + } + + @Test + fun givenMock_whenCapturingParamsValues_thenProperValuesShouldBeCaptured() { + // given + val service = mockk() + val list = mutableListOf() + every { service.getDataFromDb(capture(list)) } returns "Expected Output" + // when + service.getDataFromDb("Expected Param 1") + service.getDataFromDb("Expected Param 2") + // then + assertEquals(2, list.size) + assertEquals("Expected Param 1", list[0]) + assertEquals("Expected Param 2", list[1]) + } + + +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/HierarchicalMockKUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/HierarchicalMockKUnitTest.kt new file mode 100644 index 0000000000..e9ef133663 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/HierarchicalMockKUnitTest.kt @@ -0,0 +1,33 @@ +package com.baeldung.mockk + +import io.mockk.* +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class Foo { + lateinit var name: String + lateinit var bar: Bar +} + +class Bar { + lateinit var nickname: String +} + +class HierarchicalMockKUnitTest { + + @Test + fun givenHierarchicalClass_whenMockingIt_thenReturnProperValue() { + // given + val foo = mockk { + every { name } returns "Karol" + every { bar } returns mockk { + every { nickname } returns "Tomato" + } + } + // when + val result = foo.bar.nickname + // then + assertEquals("Tomato", result) + } + +} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/TestableService.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/TestableService.kt new file mode 100644 index 0000000000..d6f57e5fb0 --- /dev/null +++ b/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/TestableService.kt @@ -0,0 +1,12 @@ +package com.baeldung.mockk + +class TestableService { + fun getDataFromDb(testParameter: String): String { + // query database and return matching value + return "Value from DB" + } + + fun doSomethingElse(testParameter: String): String { + return "I don't want to!" + } +} \ No newline at end of file diff --git a/logging-modules/log4j/README.md b/logging-modules/log4j/README.md index 9f4184ccba..a7a7ea9643 100644 --- a/logging-modules/log4j/README.md +++ b/logging-modules/log4j/README.md @@ -1,7 +1,5 @@ ### Relevant Articles: - [Introduction to Java Logging](http://www.baeldung.com/java-logging-intro) - [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback) -- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode) -- [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback) - [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders) - [Logging Exceptions Using SLF4J](https://www.baeldung.com/slf4j-log-exceptions) diff --git a/lombok/README.md b/lombok/README.md index e3d08d4e26..4ff7ca7921 100644 --- a/lombok/README.md +++ b/lombok/README.md @@ -6,4 +6,5 @@ - [Lombok Builder with Default Value](https://www.baeldung.com/lombok-builder-default-value) - [Lombok Builder with Custom Setter](https://www.baeldung.com/lombok-builder-custom-setter) - [Setting up Lombok with Eclipse and Intellij](https://www.baeldung.com/lombok-ide) +- [Using the @Singular Annotation with Lombok Builders](https://www.baeldung.com/lombok-builder-singular) diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/singular/Person.java b/lombok/src/main/java/com/baeldung/lombok/builder/singular/Person.java new file mode 100644 index 0000000000..d7d95feb66 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/singular/Person.java @@ -0,0 +1,25 @@ +package com.baeldung.lombok.builder.singular; + +import lombok.Builder; +import lombok.Getter; +import lombok.Singular; + +import java.time.LocalDate; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Getter +@Builder +public class Person { + + private final String givenName; + private final String additionalName; + private final String familyName; + + private final List tags; + @Singular private final List interests; + @Singular private final Set skills; + @Singular private final Map awards; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/singular/Sea.java b/lombok/src/main/java/com/baeldung/lombok/builder/singular/Sea.java new file mode 100644 index 0000000000..8cf38e5f1a --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/singular/Sea.java @@ -0,0 +1,14 @@ +package com.baeldung.lombok.builder.singular; + +import java.util.List; +import lombok.Builder; +import lombok.Getter; +import lombok.Singular; + +@Getter +@Builder +public class Sea { + + @Singular private final List grasses; + @Singular("oneFish") private final List fish; +} diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/singular/BuilderWithSingularSupportForCollectionsUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/singular/BuilderWithSingularSupportForCollectionsUnitTest.java new file mode 100644 index 0000000000..41d5b19df7 --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/builder/singular/BuilderWithSingularSupportForCollectionsUnitTest.java @@ -0,0 +1,192 @@ +package com.baeldung.lombok.builder.singular; + +import org.junit.Test; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +public class BuilderWithSingularSupportForCollectionsUnitTest { + + @Test + public void canAddMultipleElementsAsNewCollection() throws Exception { + Person person = Person.builder() + .givenName("Aaron") + .additionalName("A") + .familyName("Aardvark") + .tags(Arrays.asList("fictional", "incidental")) + .build(); + + assertThat(person.getTags(), containsInAnyOrder("fictional", "incidental")); + } + + @Test + public void canUpdateCollectionAfterBuildIfMutableCollectionPassedToBuilder() throws Exception { + + List tags = new ArrayList(); + tags.add("fictional"); + tags.add("incidental"); + Person person = Person.builder() + .givenName("Aaron") + .additionalName("A") + .familyName("Aardvark") + .tags(tags) + .build(); + person.getTags() + .clear(); + person.getTags() + .add("non-fictional"); + person.getTags() + .add("important"); + + assertThat(person.getTags(), containsInAnyOrder("non-fictional", "important")); + } + + @Test(expected = UnsupportedOperationException.class) + public void cannotUpdateCollectionAfterBuildIfImmutableCollectionPassedToBuilder() throws Exception { + List tags = Arrays.asList("fictional", "incidental"); + Person person = Person.builder() + .givenName("Aaron") + .additionalName("A") + .familyName("Aardvark") + .tags(tags) + .build(); + person.getTags() + .clear(); + } + + @Test + public void canAssignToSingularAnnotatedCollectionOneByOne() throws Exception { + + Person person = Person.builder() + .givenName("Aaron") + .additionalName("A") + .familyName("Aardvark") + .interest("history") + .interest("sport") + .build(); + + assertThat(person.getInterests(), containsInAnyOrder("sport", "history")); + } + + @Test(expected = UnsupportedOperationException.class) + public void singularAnnotatedBuilderCreatesImmutableCollection() throws Exception { + + Person person = Person.builder() + .givenName("Aaron") + .additionalName("A") + .familyName("Aardvark") + .interest("history") + .interest("sport") + .build(); + person.getInterests() + .clear(); + } + + @Test + public void unpopulatedListsCreatedAsNullIfNotSingularButEmptyArrayIfSingular() throws Exception { + + Person person = Person.builder() + .givenName("Aaron") + .additionalName("A") + .familyName("Aardvark") + .build(); + assertThat(person.getInterests(), hasSize(0)); + assertThat(person.getSkills(), hasSize(0)); + assertThat(person.getAwards() + .keySet(), hasSize(0)); + assertThat(person.getTags(), is(nullValue())); + } + + @Test + public void singularSupportsSetsToo() throws Exception { + + Person person = Person.builder() + .givenName("Aaron") + .additionalName("A") + .familyName("Aardvark") + .skill("singing") + .skill("dancing") + .build(); + assertThat(person.getSkills(), contains("singing", "dancing")); + } + + @Test + public void singularSetsAreLenientWithDuplicates() throws Exception { + + Person person = Person.builder() + .givenName("Aaron") + .additionalName("A") + .familyName("Aardvark") + .interest("singing") + .interest("singing") + .skill("singing") + .skill("singing") + .build(); + assertThat(person.getInterests(), contains("singing", "singing")); + assertThat(person.getSkills(), contains("singing")); + } + + @Test + public void singularSupportsMapsToo() throws Exception { + + Person person = Person.builder() + .givenName("Aaron") + .additionalName("A") + .familyName("Aardvark") + .award("Singer of the Year", LocalDate.now() + .minusYears(5)) + .award("Best Dancer", LocalDate.now() + .minusYears(2)) + .build(); + assertThat(person.getAwards() + .keySet(), contains("Singer of the Year", "Best Dancer")); + assertThat(person.getAwards() + .get("Best Dancer"), + is(LocalDate.now() + .minusYears(2))); + } + + @Test + public void singularIsLenientWithMapKeys() throws Exception { + + Person person = Person.builder() + .givenName("Aaron") + .additionalName("A") + .familyName("Aardvark") + .award("Best Dancer", LocalDate.now() + .minusYears(5)) + .award("Best Dancer", LocalDate.now() + .minusYears(4)) + .award("Best Dancer", LocalDate.now() + .minusYears(3)) + .award("Best Dancer", LocalDate.now() + .minusYears(2)) + .award("Best Dancer", LocalDate.now() + .minusYears(1)) + .build(); + assertThat(person.getAwards() + .keySet(), hasSize(1)); + assertThat(person.getAwards() + .get("Best Dancer"), + is(LocalDate.now() + .minusYears(1))); + } + + @Test + public void wordsWithNonStandardPlurals() throws Exception { + Sea sea = Sea.builder() + .grass("Dulse") + .grass("Kelp") + .oneFish("Cod") + .oneFish("Mackerel") + .build(); + assertThat(sea.getGrasses(), contains("Dulse", "Kelp")); + assertThat(sea.getFish(), contains("Cod", "Mackerel")); + } + +} diff --git a/maven/README.md b/maven/README.md index 1352a2a10f..ca648ec203 100644 --- a/maven/README.md +++ b/maven/README.md @@ -15,3 +15,4 @@ - [Use the Latest Version of a Dependency in Maven](https://www.baeldung.com/maven-dependency-latest-version) - [Multi-Module Project with Maven](https://www.baeldung.com/maven-multi-module) - [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin) +- [Eclipse Error: web.xml is missing and failOnMissingWebXml is set to true](https://www.baeldung.com/eclipse-error-web-xml-missing) diff --git a/maven/compiler-plugin-java-9/pom.xml b/maven/compiler-plugin-java-9/pom.xml new file mode 100644 index 0000000000..5303cee82e --- /dev/null +++ b/maven/compiler-plugin-java-9/pom.xml @@ -0,0 +1,22 @@ + + 4.0.0 + com.baeldung + compiler-plugin-java-9 + 0.0.1-SNAPSHOT + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + 9 + 9 + + + + + \ No newline at end of file diff --git a/maven/compiler-plugin-java-9/src/main/java/com/baeldung/maven/java9/MavenCompilerPlugin.java b/maven/compiler-plugin-java-9/src/main/java/com/baeldung/maven/java9/MavenCompilerPlugin.java new file mode 100644 index 0000000000..b460d6e38c --- /dev/null +++ b/maven/compiler-plugin-java-9/src/main/java/com/baeldung/maven/java9/MavenCompilerPlugin.java @@ -0,0 +1,9 @@ +package com.baeldung.maven.java9; + +import static javax.xml.XMLConstants.XML_NS_PREFIX; + +public class MavenCompilerPlugin { + public static void main(String[] args) { + System.out.println("The XML namespace prefix is: " + XML_NS_PREFIX); + } +} diff --git a/maven/compiler-plugin-java-9/src/main/java/module-info.java b/maven/compiler-plugin-java-9/src/main/java/module-info.java new file mode 100644 index 0000000000..afc1d45e71 --- /dev/null +++ b/maven/compiler-plugin-java-9/src/main/java/module-info.java @@ -0,0 +1,3 @@ +module com.baeldung.maven.java9 { + requires java.xml; +} \ No newline at end of file diff --git a/maven/maven-war-plugin/pom.xml b/maven/maven-war-plugin/pom.xml new file mode 100644 index 0000000000..5169a21e78 --- /dev/null +++ b/maven/maven-war-plugin/pom.xml @@ -0,0 +1,29 @@ + + 4.0.0 + com.baeldung + maven-war-plugin-property + 0.0.1-SNAPSHOT + war + maven-war-plugin-property + + + + false + + + + + + maven-war-plugin + + 3.1.0 + + + false + + + + + \ No newline at end of file diff --git a/noexception/README.md b/noexception/README.md deleted file mode 100644 index 9dd4c11190..0000000000 --- a/noexception/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Introduction to NoException](http://www.baeldung.com/introduction-to-noexception) diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 5d7a3b66b3..3178682d34 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -29,10 +29,10 @@ - 5.1.2.RELEASE + 5.1.4.RELEASE 5.0.2 2.9.6 - 5.1.2.RELEASE + 5.1.4.RELEASE \ No newline at end of file diff --git a/patterns/README.md b/patterns/README.md index 9a15cdff02..1c9a59ea21 100644 --- a/patterns/README.md +++ b/patterns/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) - [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) +- [Introduction to the Null Object Pattern](https://www.baeldung.com/java-null-object-pattern) diff --git a/patterns/design-patterns-2/pom.xml b/patterns/design-patterns-2/pom.xml new file mode 100644 index 0000000000..5c3e70b046 --- /dev/null +++ b/patterns/design-patterns-2/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + design-patterns-2 + 1.0 + design-patterns-2 + jar + + + com.baeldung + patterns + 1.0.0-SNAPSHOT + .. + + + + + org.jetbrains + annotations + ${intellij.annotations.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + UTF-8 + 1.8 + 1.8 + 16.0.2 + 3.5 + + diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/JmsRouter.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/JmsRouter.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/JmsRouter.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/JmsRouter.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/Message.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/Message.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/Message.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/Message.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/NullRouter.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/NullRouter.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/NullRouter.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/Router.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/Router.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/Router.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/Router.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/RouterFactory.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/RouterFactory.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/RouterFactory.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/RouterFactory.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/RoutingHandler.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/RoutingHandler.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/RoutingHandler.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/RoutingHandler.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/SmsRouter.java similarity index 100% rename from patterns/design-patterns/src/main/java/com/baeldung/nullobject/SmsRouter.java rename to patterns/design-patterns-2/src/main/java/com/baeldung/nullobject/SmsRouter.java diff --git a/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/APIContracts.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/APIContracts.java new file mode 100644 index 0000000000..7d6abf53b8 --- /dev/null +++ b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/APIContracts.java @@ -0,0 +1,30 @@ +package com.baeldung.nulls; + +public class APIContracts { + + /** + * Prints the value of {@code param} if not null. Prints {@code null} otherwise. + * + * @param param + */ + public void print(Object param) { + System.out.println("Printing " + param); + } + + /** + * @return non null result + * @throws Exception - if result is null + */ + public Object process() throws Exception { + Object result = doSomething(); + if (result == null) { + throw new Exception("Processing fail. Got a null response"); + } else { + return result; + } + } + + private Object doSomething() { + return null; + } +} diff --git a/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/Assertions.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/Assertions.java new file mode 100644 index 0000000000..a0d692623f --- /dev/null +++ b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/Assertions.java @@ -0,0 +1,13 @@ +package com.baeldung.nulls; + +public class Assertions { + + public void accept(Object param){ + assert param != null; + + doSomething(param); + } + + private void doSomething(Object param) { + } +} diff --git a/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/EmptyCollections.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/EmptyCollections.java new file mode 100644 index 0000000000..5958cf8dc6 --- /dev/null +++ b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/EmptyCollections.java @@ -0,0 +1,25 @@ +package com.baeldung.nulls; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class EmptyCollections { + + public List names() { + if (userExist()) { + return Stream.of(readName()).collect(Collectors.toList()); + } else { + return Collections.emptyList(); + } + } + + private boolean userExist() { + return false; + } + + private String readName() { + return "test"; + } +} diff --git a/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/FindBugsAnnotations.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/FindBugsAnnotations.java new file mode 100644 index 0000000000..697d5e4959 --- /dev/null +++ b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/FindBugsAnnotations.java @@ -0,0 +1,30 @@ +package com.baeldung.nulls; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + + +public class FindBugsAnnotations { + + public void accept(@NotNull Object param) { + System.out.println(param.toString()); + } + + public void print(@Nullable Object param) { + System.out.println("Printing " + param); + } + + @NotNull + public Object process() throws Exception { + Object result = doSomething(); + if (result == null) { + throw new Exception("Processing fail. Got a null response"); + } else { + return result; + } + } + + private Object doSomething() { + return null; + } +} diff --git a/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/Preconditions.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/Preconditions.java new file mode 100644 index 0000000000..9d9633a13e --- /dev/null +++ b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/Preconditions.java @@ -0,0 +1,39 @@ +package com.baeldung.nulls; + +public class Preconditions { + + public void goodAccept(String one, String two, String three) { + if (one == null || two == null || three == null) { + throw new IllegalArgumentException(); + } + + process(one); + process(two); + process(three); + } + + public void badAccept(String one, String two, String three) { + if (one == null) { + throw new IllegalArgumentException(); + } else { + process(one); + } + + if (two == null) { + throw new IllegalArgumentException(); + } else { + process(two); + } + + if (three == null) { + throw new IllegalArgumentException(); + } else { + process(three); + } + + } + + private void process(String one) { + } + +} diff --git a/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/PrimitivesAndWrapper.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/PrimitivesAndWrapper.java new file mode 100644 index 0000000000..c75918c486 --- /dev/null +++ b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/PrimitivesAndWrapper.java @@ -0,0 +1,21 @@ +package com.baeldung.nulls; + +public class PrimitivesAndWrapper { + + public static int primitiveSum(int a, int b) { + return a + b; + } + + public static Integer wrapperSum(Integer a, Integer b) { + return a + b; + } + + public static Integer goodSum(Integer a, Integer b) { + if (a != null && b != null) { + return a + b; + } else { + throw new IllegalArgumentException(); + } + } + +} diff --git a/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingLombok.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingLombok.java new file mode 100644 index 0000000000..73db0742c8 --- /dev/null +++ b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingLombok.java @@ -0,0 +1,10 @@ +package com.baeldung.nulls; + +import lombok.NonNull; + +public class UsingLombok { + + public void accept(@NonNull Object param){ + System.out.println(param); + } +} diff --git a/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingObjects.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingObjects.java new file mode 100644 index 0000000000..5384edee5e --- /dev/null +++ b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingObjects.java @@ -0,0 +1,11 @@ +package com.baeldung.nulls; + +import java.util.Objects; + +public class UsingObjects { + + public void accept(Object param) { + Objects.requireNonNull(param); + // doSomething() + } +} diff --git a/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingOptional.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingOptional.java new file mode 100644 index 0000000000..6c17290a72 --- /dev/null +++ b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingOptional.java @@ -0,0 +1,27 @@ +package com.baeldung.nulls; + +import java.util.Optional; + +public class UsingOptional { + + public Optional process(boolean processed) { + + String response = doSomething(processed); + + if (response == null) { + return Optional.empty(); + } + + return Optional.of(response); + } + + private String doSomething(boolean processed) { + + if (processed) { + return "passed"; + } else { + return null; + } + } + +} diff --git a/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingStringUtils.java b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingStringUtils.java new file mode 100644 index 0000000000..c7c73b73eb --- /dev/null +++ b/patterns/design-patterns-2/src/main/java/com/baeldung/nulls/UsingStringUtils.java @@ -0,0 +1,22 @@ +package com.baeldung.nulls; + +import org.apache.commons.lang3.StringUtils; + +public class UsingStringUtils { + + public void accept(String param) { + if (StringUtils.isNotEmpty(param)) { + System.out.println(param); + } else { + throw new IllegalArgumentException(); + } + } + + public void acceptOnlyNonBlank(String param) { + if (StringUtils.isNotBlank(param)) { + System.out.println(param); + } else { + throw new IllegalArgumentException(); + } + } +} diff --git a/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/PrimitivesAndWrapperUnitTest.java b/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/PrimitivesAndWrapperUnitTest.java new file mode 100644 index 0000000000..49655619f6 --- /dev/null +++ b/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/PrimitivesAndWrapperUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.nulls; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class PrimitivesAndWrapperUnitTest { + + @Test + public void givenBothArgsNonNull_whenCallingWrapperSum_thenReturnSum() { + + Integer sum = PrimitivesAndWrapper.wrapperSum(0, 0); + + assertEquals(0, sum.intValue()); + } + + @Test() + public void givenOneArgIsNull_whenCallingWrapperSum_thenThrowNullPointerException() { + assertThrows(NullPointerException.class, () -> PrimitivesAndWrapper.wrapperSum(null, 2)); + } + + @Test() + public void givenBothArgsNull_whenCallingWrapperSum_thenThrowNullPointerException() { + assertThrows(NullPointerException.class, () -> PrimitivesAndWrapper.wrapperSum(null, null)); + } + + @Test() + public void givenOneArgNull_whenCallingGoodSum_thenThrowIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> PrimitivesAndWrapper.goodSum(null, 2)); + } + + + +} \ No newline at end of file diff --git a/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingLombokUnitTest.java b/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingLombokUnitTest.java new file mode 100644 index 0000000000..b322344aba --- /dev/null +++ b/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingLombokUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.nulls; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +class UsingLombokUnitTest { + + private UsingLombok classUnderTest; + + @BeforeEach + public void setup() { + classUnderTest = new UsingLombok(); + } + + @Test + public void whenNullArg_thenThrowNullPointerException() { + + assertThrows(NullPointerException.class, () -> classUnderTest.accept(null)); + + } + +} \ No newline at end of file diff --git a/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingObjectsUnitTest.java b/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingObjectsUnitTest.java new file mode 100644 index 0000000000..e1f5a288e6 --- /dev/null +++ b/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingObjectsUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.nulls; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class UsingObjectsUnitTest { + + private UsingObjects classUnderTest; + + @BeforeEach + public void setup() { + classUnderTest = new UsingObjects(); + } + + @Test + public void whenArgIsNull_thenThrowException() { + + assertThrows(NullPointerException.class, () -> classUnderTest.accept(null)); + } + + @Test + public void whenArgIsNonNull_thenDoesNotThrowException() { + + assertDoesNotThrow(() -> classUnderTest.accept("test ")); + } + +} \ No newline at end of file diff --git a/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingOptionalUnitTest.java b/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingOptionalUnitTest.java new file mode 100644 index 0000000000..8f896cedfa --- /dev/null +++ b/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingOptionalUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.nulls; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class UsingOptionalUnitTest { + + private UsingOptional classUnderTest; + + @BeforeEach + public void setup() { + classUnderTest = new UsingOptional(); + } + + @Test + public void whenArgIsFalse_thenReturnEmptyResponse() { + + Optional result = classUnderTest.process(false); + + assertFalse(result.isPresent()); + } + + @Test + public void whenArgIsTrue_thenReturnValidResponse() { + + Optional result = classUnderTest.process(true); + + assertTrue(result.isPresent()); + } + + @Test + public void whenArgIsFalse_thenChainResponseAndThrowException() { + + assertThrows(Exception.class, () -> classUnderTest.process(false).orElseThrow(() -> new Exception())); + } +} \ No newline at end of file diff --git a/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingStringUtilsUnitTest.java b/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingStringUtilsUnitTest.java new file mode 100644 index 0000000000..f7c51a7dc5 --- /dev/null +++ b/patterns/design-patterns-2/src/test/java/com/baeldung/nulls/UsingStringUtilsUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.nulls; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +class UsingStringUtilsUnitTest { + + private UsingStringUtils classUnderTest; + + @BeforeEach + public void setup() { + classUnderTest = new UsingStringUtils(); + } + + @Test + public void givenArgIsNull_whenCallingAccept_throwIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> classUnderTest.accept(null)); + } + + @Test + public void givenArgIsEmpty_whenCallingAccept_throwIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> classUnderTest.accept("")); + } + + @Test + public void givenArgIsNull_whenCallingAcceptOnlyNonBlank_throwIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> classUnderTest.acceptOnlyNonBlank(null)); + } + + @Test + public void givenArgIsEmpty_whenCallingAcceptOnlyNonBlank_throwIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> classUnderTest.acceptOnlyNonBlank("")); + } + + @Test + public void givenArgIsBlank_whenCallingAcceptOnlyNonBlank_throwIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> classUnderTest.acceptOnlyNonBlank(" ")); + } + +} \ No newline at end of file diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index a4513b7d95..c43ea48505 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -19,3 +19,4 @@ - [The Command Pattern in Java](http://www.baeldung.com/java-command-pattern) - [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) - [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern) +- [Currying in Java](https://baeldung.com/currying-in-java) diff --git a/patterns/design-patterns/src/main/java/com/baeldung/currying/Letter.java b/patterns/design-patterns/src/main/java/com/baeldung/currying/Letter.java new file mode 100644 index 0000000000..0939569d3c --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/currying/Letter.java @@ -0,0 +1,110 @@ +package com.baeldung.currying; + +import java.time.LocalDate; +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.function.Function; + +public class Letter { + private String returningAddress; + private String insideAddress; + private LocalDate dateOfLetter; + private String salutation; + private String body; + private String closing; + + Letter(String returningAddress, String insideAddress, LocalDate dateOfLetter, String salutation, String body, String closing) { + this.returningAddress = returningAddress; + this.insideAddress = insideAddress; + this.dateOfLetter = dateOfLetter; + this.salutation = salutation; + this.body = body; + this.closing = closing; + } + + Letter(String salutation, String body) { + this(null, null, LocalDate.now(), salutation, body, null); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Letter letter = (Letter) o; + return Objects.equals(returningAddress, letter.returningAddress) && + Objects.equals(insideAddress, letter.insideAddress) && + Objects.equals(dateOfLetter, letter.dateOfLetter) && + Objects.equals(salutation, letter.salutation) && + Objects.equals(body, letter.body) && + Objects.equals(closing, letter.closing); + } + + @Override + public int hashCode() { + return Objects.hash(returningAddress, insideAddress, dateOfLetter, salutation, body, closing); + } + + @Override + public String toString() { + return "Letter{" + "returningAddress='" + returningAddress + '\'' + ", insideAddress='" + insideAddress + '\'' + + ", dateOfLetter=" + dateOfLetter + ", salutation='" + salutation + '\'' + ", body='" + body + '\'' + + ", closing='" + closing + '\'' + '}'; + } + + static Letter createLetter(String salutation, String body) { + return new Letter(salutation, body); + } + + static BiFunction SIMPLE_LETTER_CREATOR = // + (salutation, body) -> new Letter(salutation, body); + + static Function> SIMPLE_CURRIED_LETTER_CREATOR = // + saluation -> body -> new Letter(saluation, body); + + static Function>>>>> LETTER_CREATOR = // + returnAddress + -> closing + -> dateOfLetter + -> insideAddress + -> salutation + -> body + -> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing); + + static AddReturnAddress builder() { + return returnAddress + -> closing + -> dateOfLetter + -> insideAddress + -> salutation + -> body + -> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing); + } + + interface AddReturnAddress { + Letter.AddClosing withReturnAddress(String returnAddress); + } + + interface AddClosing { + Letter.AddDateOfLetter withClosing(String closing); + } + + interface AddDateOfLetter { + Letter.AddInsideAddress withDateOfLetter(LocalDate dateOfLetter); + } + + interface AddInsideAddress { + Letter.AddSalutation withInsideAddress(String insideAddress); + } + + interface AddSalutation { + Letter.AddBody withSalutation(String salutation); + } + + interface AddBody { + Letter withBody(String body); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/test/java/com/baeldung/currying/LetterUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/currying/LetterUnitTest.java new file mode 100644 index 0000000000..bf1bafe72c --- /dev/null +++ b/patterns/design-patterns/src/test/java/com/baeldung/currying/LetterUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.currying; + +import org.junit.Test; + +import java.time.LocalDate; + +import static com.baeldung.currying.Letter.LETTER_CREATOR; +import static com.baeldung.currying.Letter.SIMPLE_CURRIED_LETTER_CREATOR; +import static com.baeldung.currying.Letter.SIMPLE_LETTER_CREATOR; +import static org.junit.Assert.assertEquals; + +public class LetterUnitTest { + private static final String BODY = "BODY"; + private static final String SALUTATION = "SALUTATION"; + private static final String RETURNING_ADDRESS = "RETURNING ADDRESS"; + private static final String INSIDE_ADDRESS = "INSIDE ADDRESS"; + private static final LocalDate DATE_OF_LETTER = LocalDate.of(2013, 3, 1); + private static final String CLOSING = "CLOSING"; + private static final Letter SIMPLE_LETTER = new Letter(SALUTATION, BODY); + private static final Letter LETTER = new Letter(RETURNING_ADDRESS, INSIDE_ADDRESS, DATE_OF_LETTER, SALUTATION, BODY, CLOSING); + + @Test + public void whenStaticCreateMethodIsCalled_thenaSimpleLetterIsCreated() { + assertEquals(SIMPLE_LETTER, Letter.createLetter(SALUTATION, BODY)); + } + + @Test + public void whenStaticBiFunctionIsCalled_thenaSimpleLetterIsCreated() { + assertEquals(SIMPLE_LETTER, SIMPLE_LETTER_CREATOR.apply(SALUTATION, BODY)); + } + + @Test + public void whenStaticSimpleCurriedFunctionIsCalled_thenaSimpleLetterIsCreated() { + assertEquals(SIMPLE_LETTER, SIMPLE_CURRIED_LETTER_CREATOR.apply(SALUTATION).apply(BODY)); + } + + @Test + public void whenStaticCurriedFunctionIsCalled_thenaLetterIsCreated() { + assertEquals(LETTER, LETTER_CREATOR + .apply(RETURNING_ADDRESS) + .apply(CLOSING) + .apply(DATE_OF_LETTER) + .apply(INSIDE_ADDRESS) + .apply(SALUTATION) + .apply(BODY)); + } + + @Test + public void whenStaticBuilderIsCalled_thenaLetterIsCreated() { + assertEquals(LETTER, Letter.builder() + .withReturnAddress(RETURNING_ADDRESS) + .withClosing(CLOSING) + .withDateOfLetter(DATE_OF_LETTER) + .withInsideAddress(INSIDE_ADDRESS) + .withSalutation(SALUTATION) + .withBody(BODY)); + } +} \ No newline at end of file diff --git a/patterns/pom.xml b/patterns/pom.xml index 3c3bb6d5ea..111e72b9ca 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -17,6 +17,7 @@ front-controller intercepting-filter design-patterns + design-patterns-2 solid diff --git a/persistence-modules/core-java-persistence/README.md b/persistence-modules/core-java-persistence/README.md index ca0ce81eef..26bd4bf00f 100644 --- a/persistence-modules/core-java-persistence/README.md +++ b/persistence-modules/core-java-persistence/README.md @@ -7,3 +7,4 @@ - [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing) - [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset) - [A Simple Guide to Connection Pooling in Java](https://www.baeldung.com/java-connection-pooling) +- [Guide to the JDBC ResultSet Interface](https://www.baeldung.com/jdbc-resultset) diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java index 749855ca3b..27aef8b82f 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java @@ -1,5 +1,7 @@ package com.baeldung.jdbc; +import java.util.Objects; + public class Employee { private int id; private String name; @@ -48,4 +50,21 @@ public class Employee { this.position = position; } + @Override + public int hashCode() { + return Objects.hash(id, name, position, salary); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Employee other = (Employee) obj; + return id == other.id && Objects.equals(name, other.name) && Objects.equals(position, other.position) && Double.doubleToLongBits(salary) == Double.doubleToLongBits(other.salary); + } + } diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java new file mode 100644 index 0000000000..4e10f8bd43 --- /dev/null +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java @@ -0,0 +1,359 @@ +package com.baeldung.jdbc; + +import static org.junit.Assert.assertEquals; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +import junit.framework.Assert; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class ResultSetLiveTest { + + private static final Logger logger = Logger.getLogger(ResultSetLiveTest.class); + + private final Employee expectedEmployee1 = new Employee(1, "John", 1000.0, "Developer"); + + private final Employee updatedEmployee1 = new Employee(1, "John", 1100.0, "Developer"); + + private final Employee expectedEmployee2 = new Employee(2, "Chris", 925.0, "DBA"); + + private final int rowCount = 2; + + private static Connection dbConnection; + + @BeforeClass + public static void setup() throws ClassNotFoundException, SQLException { + Class.forName("com.mysql.cj.jdbc.Driver"); + dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB?noAccessToProcedureBodies=true", "user1", "pass"); + String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)"; + try (Statement stmt = dbConnection.createStatement()) { + stmt.execute(tableSql); + try (PreparedStatement pstmt = dbConnection.prepareStatement("INSERT INTO employees(name, position, salary) values ('John', 'Developer', 1000.0)")) { + pstmt.executeUpdate(); + } + } + } + + @Test + public void givenDbConnectionA_whenRetreiveByColumnNames_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + } + } + + assertEquals("Employee information retreived by column names.", expectedEmployee1, employee); + } + + @Test + public void givenDbConnectionB_whenRetreiveByColumnIds_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + Integer empId = rs.getInt(1); + String name = rs.getString(2); + String position = rs.getString(3); + Double salary = rs.getDouble(4); + employee = new Employee(empId, name, salary, position); + } + } + + assertEquals("Employee information retreived by column ids.", expectedEmployee1, employee); + } + + @Test + public void givenDbConnectionD_whenInsertRow_thenCorrect() throws SQLException { + int rowCount = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.moveToInsertRow(); + rs.updateString("name", "Chris"); + rs.updateString("position", "DBA"); + rs.updateDouble("salary", 925.0); + rs.insertRow(); + rs.moveToCurrentRow(); + rs.last(); + rowCount = rs.getRow(); + } + + assertEquals("Row Count after inserting a row", 2, rowCount); + } + + private Employee populateResultSet(ResultSet rs) throws SQLException { + Employee employee; + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + return employee; + } + + @Test + public void givenDbConnectionE_whenRowCount_thenCorrect() throws SQLException { + int numOfRows = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.last(); + numOfRows = rs.getRow(); + } + + assertEquals("Num of rows", rowCount, numOfRows); + } + + @Test + public void givenDbConnectionG_whenAbsoluteNavigation_thenCorrect() throws SQLException { + Employee secondEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.absolute(2); + secondEmployee = populateResultSet(rs); + } + + assertEquals("Absolute navigation", expectedEmployee2, secondEmployee); + } + + @Test + public void givenDbConnectionH_whenLastNavigation_thenCorrect() throws SQLException { + Employee secondEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.last(); + secondEmployee = populateResultSet(rs); + } + + assertEquals("Using Last", expectedEmployee2, secondEmployee); + } + + @Test + public void givenDbConnectionI_whenNavigation_thenCorrect() throws SQLException { + Employee firstEmployee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.beforeFirst(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + rs.first(); + while (rs.next()) { + Employee employee = populateResultSet(rs); + } + while (rs.previous()) { + Employee employee = populateResultSet(rs); + } + rs.afterLast(); + while (rs.previous()) { + Employee employee = populateResultSet(rs); + } + rs.last(); + while (rs.previous()) { + firstEmployee = populateResultSet(rs); + } + } + + assertEquals("Several Navigation Options", updatedEmployee1, firstEmployee); + } + + @Test + public void givenDbConnectionJ_whenClosedCursor_thenCorrect() throws SQLException { + Employee employee = null; + dbConnection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); + try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT)) { + dbConnection.setAutoCommit(false); + ResultSet rs = pstmt.executeQuery("select * from employees"); + while (rs.next()) { + if (rs.getString("name") + .equalsIgnoreCase("john")) { + rs.updateString("position", "Senior Engineer"); + rs.updateRow(); + dbConnection.commit(); + employee = populateResultSet(rs); + } + } + rs.last(); + } + + assertEquals("Update using closed cursor", "Senior Engineer", employee.getPosition()); + } + + @Test + public void givenDbConnectionK_whenUpdate_thenCorrect() throws SQLException { + Employee employee = null; + dbConnection.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); + try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.HOLD_CURSORS_OVER_COMMIT)) { + dbConnection.setAutoCommit(false); + ResultSet rs = pstmt.executeQuery("select * from employees"); + while (rs.next()) { + if (rs.getString("name") + .equalsIgnoreCase("john")) { + rs.updateString("name", "John Doe"); + rs.updateRow(); + dbConnection.commit(); + employee = populateResultSet(rs); + } + } + rs.last(); + } + + assertEquals("Update using open cursor", "John Doe", employee.getName()); + } + + @Test + public void givenDbConnectionM_whenDelete_thenCorrect() throws SQLException { + int numOfRows = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.absolute(2); + rs.deleteRow(); + } + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + rs.last(); + numOfRows = rs.getRow(); + } + assertEquals("Deleted row", 1, numOfRows); + } + + @Test + public void givenDbConnectionC_whenUpdate_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + + Assert.assertEquals(1100.0, rs.getDouble("salary")); + + rs.updateDouble("salary", 1200.0); + rs.updateRow(); + + Assert.assertEquals(1200.0, rs.getDouble("salary")); + + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + } + } + } + + @Test + public void givenDbConnectionC_whenUpdateByIndex_thenCorrect() throws SQLException { + Employee employee = null; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + + Assert.assertEquals(1000.0, rs.getDouble(4)); + + rs.updateDouble(4, 1100.0); + rs.updateRow(); + Assert.assertEquals(1100.0, rs.getDouble(4)); + + String name = rs.getString("name"); + Integer empId = rs.getInt("emp_id"); + Double salary = rs.getDouble("salary"); + String position = rs.getString("position"); + employee = new Employee(empId, name, salary, position); + } + } + } + + @Test + public void givenDbConnectionE_whenDBMetaInfo_thenCorrect() throws SQLException { + DatabaseMetaData dbmd = dbConnection.getMetaData(); + boolean supportsTypeForward = dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY); + boolean supportsTypeScrollSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE); + boolean supportsTypeScrollInSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE); + boolean supportsCloseCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); + boolean supportsHoldCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); + boolean concurrency4TypeFwdNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + boolean concurrency4TypeFwdNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollInSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollInSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + boolean concurrency4TypeScrollSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + boolean concurrency4TypeScrollSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + int rsHoldability = dbmd.getResultSetHoldability(); + + assertEquals("checking scroll sensitivity and concur updates : ", true, concurrency4TypeScrollInSensitiveNConcurUpdatable); + } + + @Test + public void givenDbConnectionF_whenRSMetaInfo_thenCorrect() throws SQLException { + int columnCount = 0; + try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) { + ResultSetMetaData metaData = rs.getMetaData(); + columnCount = metaData.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + String catalogName = metaData.getCatalogName(i); + String className = metaData.getColumnClassName(i); + String label = metaData.getColumnLabel(i); + String name = metaData.getColumnName(i); + String typeName = metaData.getColumnTypeName(i); + Integer type = metaData.getColumnType(i); + String tableName = metaData.getTableName(i); + String schemaName = metaData.getSchemaName(i); + boolean isAutoIncrement = metaData.isAutoIncrement(i); + boolean isCaseSensitive = metaData.isCaseSensitive(i); + boolean isCurrency = metaData.isCurrency(i); + boolean isDefiniteWritable = metaData.isDefinitelyWritable(i); + boolean isReadOnly = metaData.isReadOnly(i); + boolean isSearchable = metaData.isSearchable(i); + boolean isReadable = metaData.isReadOnly(i); + boolean isSigned = metaData.isSigned(i); + boolean isWritable = metaData.isWritable(i); + int nullable = metaData.isNullable(i); + } + } + + assertEquals("column count", 4, columnCount); + } + + @Test + public void givenDbConnectionL_whenFetch_thenCorrect() throws SQLException { + PreparedStatement pstmt = null; + ResultSet rs = null; + List listOfEmployees = new ArrayList(); + try { + pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + pstmt.setFetchSize(1); + rs = pstmt.executeQuery(); + rs.setFetchSize(1); + while (rs.next()) { + Employee employee = populateResultSet(rs); + listOfEmployees.add(employee); + } + } catch (Exception e) { + throw e; + } finally { + if (rs != null) + rs.close(); + if (pstmt != null) + pstmt.close(); + } + + assertEquals(2, listOfEmployees.size()); + } + + @AfterClass + public static void closeConnection() throws SQLException { + PreparedStatement deleteStmt = dbConnection.prepareStatement("drop table employees", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); + deleteStmt.execute(); + dbConnection.close(); + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/README.md b/persistence-modules/hibernate-ogm/README.md index f4a5bb6c3b..df99cce129 100644 --- a/persistence-modules/hibernate-ogm/README.md +++ b/persistence-modules/hibernate-ogm/README.md @@ -1,4 +1,4 @@ ## Relevant articles: -- [Guide to Hibernate OGM](http://www.baeldung.com/xxxx) +- [A Guide to Hibernate OGM](https://www.baeldung.com/hibernate-ogm) diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index a09669c8b5..c7f08e50d5 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -83,13 +83,18 @@ jmh-generator-annprocess ${openjdk-jmh.version} + + javax.xml.bind + jaxb-api + 2.3.0 + hibernate5 - src/main/resources + src/test/resources true diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index ea0af97d5a..48c9b9d5c2 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -113,6 +113,7 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); metadataSources.addAnnotatedClass(OfficeEmployee.class); + metadataSources.addAnnotatedClass(Post.class); Metadata metadata = metadataSources.getMetadataBuilder() .applyBasicType(LocalDateStringType.INSTANCE) diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Post.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Post.java new file mode 100644 index 0000000000..25e51e35d0 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Post.java @@ -0,0 +1,59 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "posts") +public class Post { + + @Id + @GeneratedValue + private int id; + + private String title; + + private String body; + + public Post() { } + + public Post(String title, String body) { + this.title = title; + this.body = body; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + @Override + public String toString() { + return "Post{" + + "id=" + id + + ", title='" + title + '\'' + + ", body='" + body + '\'' + + '}'; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java new file mode 100644 index 0000000000..5a4eb20079 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/transaction/PostService.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.transaction; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.query.Query; + +public class PostService { + + + private Session session; + + public PostService(Session session) { + this.session = session; + } + + + public void updatePost(String title, String body, int id) { + Transaction txn = session.beginTransaction(); + Query updateQuery = session.createQuery("UPDATE Post p SET p.title = ?1, p.body = ?2 WHERE p.id = ?3"); + updateQuery.setParameter(1, title); + updateQuery.setParameter(2, body); + updateQuery.setParameter(3, id); + updateQuery.executeUpdate(); + txn.commit(); + } + + + +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java index 29ae55b773..e64e836924 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java @@ -74,4 +74,6 @@ public class CustomClassIntegrationTest { assertEquals("John Smith", result.getEmployeeName()); assertEquals("Sales", result.getDepartmentName()); } + + } diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java new file mode 100644 index 0000000000..246a7d59f9 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.transaction; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.pojo.Post; +import com.baeldung.hibernate.transaction.PostService; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; + +public class TransactionIntegrationTest { + + private static PostService postService; + private static Session session; + private static Logger logger = LoggerFactory.getLogger(TransactionIntegrationTest.class); + + @BeforeClass + public static void init() throws IOException { + Properties properties = new Properties(); + properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); + properties.setProperty("hibernate.connection.url", "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1"); + properties.setProperty("hibernate.connection.username", "sa"); + properties.setProperty("hibernate.show_sql", "true"); + properties.setProperty("jdbc.password", ""); + properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); + properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); + SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties); + session = sessionFactory.openSession(); + postService = new PostService(session); + } + + @Test + public void givenTitleAndBody_whenRepositoryUpdatePost_thenUpdatePost() { + + Post post = new Post("This is a title", "This is a sample post"); + session.persist(post); + + String title = "[UPDATE] Java HowTos"; + String body = "This is an updated posts on Java how-tos"; + postService.updatePost(title, body, post.getId()); + + session.refresh(post); + + assertEquals(post.getTitle(), title); + assertEquals(post.getBody(), body); + } + + +} diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 2c26581bab..2424999fb3 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -6,3 +6,4 @@ - [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) - [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time) - [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date) +- [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates) diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/entity/Item.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/entity/Item.java new file mode 100644 index 0000000000..64ef46f265 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/entity/Item.java @@ -0,0 +1,49 @@ +package com.baeldung.jpa.criteria.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Table(name = "item") +@Entity +public class Item { + + @Id + private Long id; + private String color; + private String grade; + private String name; + + public String getColor() { + return color; + } + + public String getGrade() { + return grade; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public void setColor(String color) { + this.color = color; + } + + public void setGrade(String grade) { + this.grade = grade; + } + + public void setId(Long id) { + this.id = id; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/CustomItemRepository.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/CustomItemRepository.java new file mode 100644 index 0000000000..c55dc4a592 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/CustomItemRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.jpa.criteria.repository; + +import java.util.List; + +import com.baeldung.jpa.criteria.entity.Item; + +public interface CustomItemRepository { + + List findItemsByColorAndGrade(); + + List findItemByColorOrGrade(); +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryImpl.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryImpl.java new file mode 100644 index 0000000000..bf1d3eed0b --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryImpl.java @@ -0,0 +1,77 @@ +package com.baeldung.jpa.criteria.repository.impl; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import com.baeldung.jpa.criteria.entity.Item; +import com.baeldung.jpa.criteria.repository.CustomItemRepository; + +public class CustomItemRepositoryImpl implements CustomItemRepository { + + private EntityManager entityManager; + + public CustomItemRepositoryImpl() { + super(); + EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-criteria"); + entityManager = factory.createEntityManager(); + } + + @Override + public List findItemsByColorAndGrade() { + + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Item.class); + Root itemRoot = criteriaQuery.from(Item.class); + + Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "blue"); + Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "red"); + Predicate predicateForColor = criteriaBuilder.or(predicateForBlueColor, predicateForRedColor); + + Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "A"); + Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B"); + Predicate predicateForGrade = criteriaBuilder.or(predicateForGradeA, predicateForGradeB); + + // final search filter + Predicate finalPredicate = criteriaBuilder.and(predicateForColor, predicateForGrade); + + criteriaQuery.where(finalPredicate); + + List items = entityManager.createQuery(criteriaQuery) + .getResultList(); + return items; + } + + @Override + public List findItemByColorOrGrade() { + + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Item.class); + Root itemRoot = criteriaQuery.from(Item.class); + + Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "red"); + Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "D"); + Predicate predicateForBlueColorAndGradeA = criteriaBuilder.and(predicateForBlueColor, predicateForGradeA); + + Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "blue"); + Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B"); + Predicate predicateForRedColorAndGradeB = criteriaBuilder.and(predicateForRedColor, predicateForGradeB); + + // final search filter + Predicate finalPredicate = criteriaBuilder.or(predicateForBlueColorAndGradeA, predicateForRedColorAndGradeB); + + criteriaQuery.where(finalPredicate); + + List items = entityManager.createQuery(criteriaQuery) + .getResultList(); + return items; + } +} diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index 8592fce533..6382f329c1 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -1,91 +1,112 @@ - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.sqlresultsetmapping.ScheduledDay - com.baeldung.sqlresultsetmapping.Employee - true - - - - - - - - - - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.stringcast.Message - true - - - - - - - - - - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.model.Car - true - - - - - - - - - - - - com.baeldung.jpa.entitygraph.model.Post - com.baeldung.jpa.entitygraph.model.User - com.baeldung.jpa.entitygraph.model.Comment - true - - - - - - - - - - - - - org.eclipse.persistence.jpa.PersistenceProvider - com.baeldung.jpa.datetime.JPA22DateTimeEntity - true - - - - - - - - - - - - - - + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.sqlresultsetmapping.ScheduledDay + com.baeldung.sqlresultsetmapping.Employee + true + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.stringcast.Message + true + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.model.Car + true + + + + + + + + + + + + com.baeldung.jpa.entitygraph.model.Post + com.baeldung.jpa.entitygraph.model.User + com.baeldung.jpa.entitygraph.model.Comment + true + + + + + + + + + + + + + org.eclipse.persistence.jpa.PersistenceProvider + com.baeldung.jpa.datetime.JPA22DateTimeEntity + true + + + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.criteria.entity.Item + true + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryIntegrationTest.java new file mode 100644 index 0000000000..169fb44618 --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/criteria/repository/impl/CustomItemRepositoryIntegrationTest.java @@ -0,0 +1,44 @@ +package com.baeldung.jpa.criteria.repository.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.List; + +import org.junit.Test; + +import com.baeldung.jpa.criteria.entity.Item; +import com.baeldung.jpa.criteria.repository.CustomItemRepository; + +public class CustomItemRepositoryIntegrationTest { + + CustomItemRepository customItemRepository = new CustomItemRepositoryImpl(); + + @Test + public void givenItems_whenFindItemsByColorAndGrade_thenReturnItems() { + + List items = customItemRepository.findItemsByColorAndGrade(); + + assertFalse("No items found", items.isEmpty()); + assertEquals("There should be only one item", 1, items.size()); + + Item item = items.get(0); + + assertEquals("this item do not have blue color", "blue", item.getColor()); + assertEquals("this item does not belong to A grade", "A", item.getGrade()); + } + + @Test + public void givenItems_whenFindItemByColorOrGrade_thenReturnItems() { + + List items = customItemRepository.findItemByColorOrGrade(); + + assertFalse("No items found", items.isEmpty()); + assertEquals("There should be only one item", 1, items.size()); + + Item item = items.get(0); + + assertEquals("this item do not have red color", "red", item.getColor()); + assertEquals("this item does not belong to D grade", "D", item.getGrade()); + } +} diff --git a/persistence-modules/java-jpa/src/test/resources/item.sql b/persistence-modules/java-jpa/src/test/resources/item.sql new file mode 100644 index 0000000000..faf50f6829 --- /dev/null +++ b/persistence-modules/java-jpa/src/test/resources/item.sql @@ -0,0 +1,4 @@ +insert into item(id,grade,color) values (10,'C','blue'); +insert into item(id,grade,color) values (11,'C','red'); +insert into item(id,grade,color) values (12,'A','blue'); +insert into item(id,grade,color) values (13,'D','red'); \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md index f093d4baf0..40f9f40749 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/README.md +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -1,3 +1,4 @@ # Relevant Articles - [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field) +- [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb) diff --git a/persistence-modules/spring-boot-persistence-mongodb/pom.xml b/persistence-modules/spring-boot-persistence-mongodb/pom.xml index 86b93c7826..585e54bf57 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb/pom.xml @@ -25,6 +25,11 @@ org.springframework.boot spring-boot-starter-data-mongodb + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + test + org.junit.jupiter @@ -102,4 +107,4 @@ - \ No newline at end of file + diff --git a/spring-boot/src/test/java/com/baeldung/mongodb/ManualEmbeddedMongoDbIntegrationTest.java b/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/ManualEmbeddedMongoDbIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/mongodb/ManualEmbeddedMongoDbIntegrationTest.java rename to persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/ManualEmbeddedMongoDbIntegrationTest.java diff --git a/spring-boot/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java b/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java similarity index 90% rename from spring-boot/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java rename to persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java index 39127f62e9..954bae3684 100644 --- a/spring-boot/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java @@ -2,7 +2,6 @@ package com.baeldung.mongodb; import static org.assertj.core.api.Assertions.assertThat; -import org.baeldung.boot.Application; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -12,10 +11,11 @@ import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; +import com.baeldung.SpringBootPersistenceApplication; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DBObject; -@ContextConfiguration(classes = Application.class) +@ContextConfiguration(classes = SpringBootPersistenceApplication.class) @DataMongoTest @ExtendWith(SpringExtension.class) public class MongoDbSpringIntegrationTest { diff --git a/persistence-modules/spring-boot-persistence/README.MD b/persistence-modules/spring-boot-persistence/README.MD index f62ca57a19..ee7c2e298e 100644 --- a/persistence-modules/spring-boot-persistence/README.MD +++ b/persistence-modules/spring-boot-persistence/README.MD @@ -7,3 +7,4 @@ - [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot) - [Integrating Spring Boot with HSQLDB](https://www.baeldung.com/spring-boot-hsqldb) - [Configuring a DataSource Programmatically in Spring Boot](https://www.baeldung.com/spring-boot-configure-data-source-programmatic) +- [Resolving “Failed to Configure a DataSource” Error](https://www.baeldung.com/spring-boot-failed-to-configure-data-source) diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/disabledatasource/application/Application.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/disabledatasource/application/Application.java new file mode 100644 index 0000000000..79273ba141 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/disabledatasource/application/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.disabledatasource.application; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; + +@SpringBootApplication(exclude=DataSourceAutoConfiguration.class) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/exists/Car.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/exists/Car.java new file mode 100644 index 0000000000..bf09caf6ff --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/exists/Car.java @@ -0,0 +1,48 @@ +package com.baeldung.exists; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +/** + * @author paullatzelsperger + * @since 2019-03-20 + */ +@Entity +public class Car { + + @Id + @GeneratedValue + private int id; + private Integer power; + private String model; + + Car() { + + } + + public Car(int power, String model) { + this.power = power; + this.model = model; + } + + public Integer getPower() { + return power; + } + + public void setPower(Integer power) { + this.power = power; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + public int getId() { + return id; + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/exists/CarRepository.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/exists/CarRepository.java new file mode 100644 index 0000000000..a54f19f4cd --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/exists/CarRepository.java @@ -0,0 +1,24 @@ +package com.baeldung.exists; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +/** + * @author paullatzelsperger + * @since 2019-03-20 + */ +@Repository +public interface CarRepository extends JpaRepository { + + boolean existsCarByPower(int power); + + boolean existsCarByModel(String model); + + @Query("select case when count(c)> 0 then true else false end from Car c where c.model = :model") + boolean existsCarExactCustomQuery(@Param("model") String model); + + @Query("select case when count(c)> 0 then true else false end from Car c where lower(c.model) like lower(:model)") + boolean existsCarLikeCustomQuery(@Param("model") String model); +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/ExampleApplication.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/ExampleApplication.java new file mode 100644 index 0000000000..4b6a93ab8b --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/ExampleApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.springboothibernate.application; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(ExampleApplication.class, args); + } + +} + diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/datasources/DataSourceBean.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/datasources/DataSourceBean.java new file mode 100644 index 0000000000..54a0c4f077 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/datasources/DataSourceBean.java @@ -0,0 +1,21 @@ +package com.baeldung.springboothibernate.application.datasources; + +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.sql.DataSource; + +@Configuration +public class DataSourceBean { + + @Bean + public DataSource getDataSource() { + DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create(); + dataSourceBuilder.driverClassName("org.h2.Driver"); + dataSourceBuilder.url("jdbc:h2:mem:test"); + dataSourceBuilder.username("SA"); + dataSourceBuilder.password(""); + return dataSourceBuilder.build(); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/models/Book.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/models/Book.java new file mode 100644 index 0000000000..7562c072c7 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/models/Book.java @@ -0,0 +1,40 @@ +package com.baeldung.springboothibernate.application.models; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Book { + + @Id + @GeneratedValue + private Long id; + private String name; + + public Book() { + super(); + } + + public Book(Long id, String name) { + super(); + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/repositories/BookRepository.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/repositories/BookRepository.java new file mode 100644 index 0000000000..3d5789fb4d --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/repositories/BookRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.springboothibernate.application.repositories; + +import com.baeldung.springboothibernate.application.models.Book; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface BookRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/services/BookService.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/services/BookService.java new file mode 100644 index 0000000000..e495045bab --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothibernate/application/services/BookService.java @@ -0,0 +1,19 @@ +package com.baeldung.springboothibernate.application.services; + +import com.baeldung.springboothibernate.application.models.Book; +import com.baeldung.springboothibernate.application.repositories.BookRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class BookService { + + @Autowired + private BookRepository bookRepository; + + public List list() { + return bookRepository.findAll(); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties index b0caf4a809..7b5a467a2b 100644 --- a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties @@ -3,3 +3,9 @@ spring.datasource.url = jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1 spring.datasource.username = sa spring.datasource.password = spring.jpa.hibernate.ddl-auto = create + +# Enabling H2 Console +spring.h2.console.enabled=true + +# Uppercase Table Names +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java new file mode 100644 index 0000000000..1633df35d6 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java @@ -0,0 +1,86 @@ +package com.baeldung.exists; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.ignoreCase; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.ExampleMatcher; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Arrays; +import java.util.List; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class CarRepositoryIntegrationTest { + + @Autowired + private CarRepository repository; + private int searchId; + + @Before + public void setup() { + List cars = repository.saveAll(Arrays.asList(new Car(200, "BMW"), new Car(300, "Audi"))); + searchId = cars.get(0).getId(); + } + + @After + public void teardown() { + repository.deleteAll(); + } + + @Test + public void whenIdIsCorrect_thenExistsShouldReturnTrue() { + assertThat(repository.existsById(searchId)).isTrue(); + } + + @Test + public void givenExample_whenExists_thenIsTrue() { + ExampleMatcher modelMatcher = ExampleMatcher.matching() + .withIgnorePaths("id") // must explicitly ignore -> PK + .withMatcher("model", ignoreCase()); + Car probe = new Car(); + probe.setModel("bmw"); + + Example example = Example.of(probe, modelMatcher); + + assertThat(repository.exists(example)).isTrue(); + } + + @Test + public void givenPower_whenExists_thenIsFalse() { + assertThat(repository.existsCarByPower(200)).isTrue(); + assertThat(repository.existsCarByPower(800)).isFalse(); + } + + @Test + public void existsByDerivedQuery_byModel() { + assertThat(repository.existsCarByModel("Audi")).isTrue(); + assertThat(repository.existsCarByModel("audi")).isFalse(); + assertThat(repository.existsCarByModel("AUDI")).isFalse(); + assertThat(repository.existsCarByModel("")).isFalse(); + } + + @Test + public void givenModelName_whenExistsExact_thenIsTrue() { + assertThat(repository.existsCarExactCustomQuery("BMW")).isTrue(); + assertThat(repository.existsCarExactCustomQuery("Bmw")).isFalse(); + assertThat(repository.existsCarExactCustomQuery("bmw")).isFalse(); + assertThat(repository.existsCarExactCustomQuery("")).isFalse(); + } + + @Test + public void givenModelName_whenExistsLike_thenIsTrue() { + assertThat(repository.existsCarLikeCustomQuery("BMW")).isTrue(); + assertThat(repository.existsCarLikeCustomQuery("Bmw")).isTrue(); + assertThat(repository.existsCarLikeCustomQuery("bmw")).isTrue(); + assertThat(repository.existsCarLikeCustomQuery("")).isFalse(); + } + +} diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothibernate/application/tests/BookServiceUnitTest.java b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothibernate/application/tests/BookServiceUnitTest.java new file mode 100644 index 0000000000..655a852001 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothibernate/application/tests/BookServiceUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.springboothibernate.application.tests; + +import com.baeldung.springboothibernate.application.models.Book; +import com.baeldung.springboothibernate.application.services.BookService; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class BookServiceUnitTest { + + @Autowired + private BookService bookService; + + @Test + public void whenApplicationStarts_thenHibernateCreatesInitialRecords() { + List books = bookService.list(); + + Assert.assertEquals(books.size(), 3); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/test/resources/application.properties b/persistence-modules/spring-boot-persistence/src/test/resources/application.properties index a5c1d983cf..3a6470c8dc 100644 --- a/persistence-modules/spring-boot-persistence/src/test/resources/application.properties +++ b/persistence-modules/spring-boot-persistence/src/test/resources/application.properties @@ -12,5 +12,5 @@ hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory -spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql +spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql, import_books.sql spring.datasource.data=import_*_users.sql \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/src/test/resources/import_books.sql b/persistence-modules/spring-boot-persistence/src/test/resources/import_books.sql new file mode 100644 index 0000000000..8eaf972a00 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/test/resources/import_books.sql @@ -0,0 +1,3 @@ +insert into book values(1, 'The Tartar Steppe'); +insert into book values(2, 'Poem Strip'); +insert into book values(3, 'Restless Nights: Selected Stories of Dino Buzzati'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md new file mode 100644 index 0000000000..295a434d17 --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -0,0 +1,5 @@ +========= + +## Spring Data JPA Example Project + +### Relevant Articles: diff --git a/persistence-modules/spring-data-jpa-2/pom.xml b/persistence-modules/spring-data-jpa-2/pom.xml new file mode 100644 index 0000000000..8e46112659 --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + com.baeldung + spring-data-jpa-2 + spring-data-jpa + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..3ea3d113da --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java new file mode 100644 index 0000000000..f82022e67e --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java @@ -0,0 +1,38 @@ +package com.baeldung.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Fruit { + + @Id + private long id; + private String name; + private String color; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java new file mode 100644 index 0000000000..9f92909b66 --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java @@ -0,0 +1,27 @@ +package com.baeldung.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.baeldung.entity.Fruit; + +@Repository +public interface FruitRepository extends JpaRepository { + + Long deleteByName(String name); + + List deleteByColor(String color); + + Long removeByName(String name); + + List removeByColor(String color); + + @Modifying + @Query("delete from Fruit f where f.name=:name or f.color=:color") + List deleteFruits(@Param("name") String name, @Param("color") String color); +} diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties new file mode 100644 index 0000000000..72fc330767 --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.jpa.show-sql=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java new file mode 100644 index 0000000000..866cf1157b --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java @@ -0,0 +1,77 @@ +package com.baeldung.repository; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.entity.Fruit; + +@RunWith(SpringRunner.class) +@SpringBootTest +class FruitRepositoryIntegrationTest { + + @Autowired + private FruitRepository fruitRepository; + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenDeletedByColor_ThenDeletedFruitsShouldReturn() { + + List fruits = fruitRepository.deleteByColor("green"); + + assertEquals("number of fruits are not matching", 2, fruits.size()); + fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor())); + } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenDeletedByName_ThenDeletedFruitCountShouldReturn() { + + Long deletedFruitCount = fruitRepository.deleteByName("apple"); + + assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue()); + } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenRemovedByColor_ThenDeletedFruitsShouldReturn() { + + List fruits = fruitRepository.removeByColor("green"); + + assertEquals("number of fruits are not matching", 2, fruits.size()); + fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor())); + } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenRemovedByName_ThenDeletedFruitCountShouldReturn() { + + Long deletedFruitCount = fruitRepository.removeByName("apple"); + + assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue()); + } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenDeletedByColorOrName_ThenDeletedFruitsShouldReturn() { + + List fruits = fruitRepository.deleteFruits("apple", "green"); + + assertEquals("number of fruits are not matching", 3, fruits.size()); + fruits.forEach(fruit -> assertTrue("Its not a green fruit or apple", ("green".equals(fruit.getColor())) || "apple".equals(fruit.getColor()))); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql new file mode 100644 index 0000000000..ce2189121f --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql @@ -0,0 +1,4 @@ +insert into fruit(id,name,color) values (1,'apple','red'); +insert into fruit(id,name,color) values (2,'custard apple','green'); +insert into fruit(id,name,color) values (3,'mango','yellow'); +insert into fruit(id,name,color) values (4,'guava','green'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md index 9512ad336d..48c3180262 100644 --- a/persistence-modules/spring-data-jpa/README.md +++ b/persistence-modules/spring-data-jpa/README.md @@ -22,6 +22,7 @@ - [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) - [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test) - [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation) +- [Spring Data JPA Batch Inserts](https://www.baeldung.com/spring-data-jpa-batch-inserts) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml index 401f4877ac..c512994931 100644 --- a/persistence-modules/spring-data-jpa/pom.xml +++ b/persistence-modules/spring-data-jpa/pom.xml @@ -53,6 +53,15 @@ spring-security-test test + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + com.google.guava diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/batchinserts/CustomerController.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/batchinserts/CustomerController.java new file mode 100644 index 0000000000..7623d4d166 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/batchinserts/CustomerController.java @@ -0,0 +1,43 @@ +package com.baeldung.batchinserts; + +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.batchinserts.model.Customer; +import com.baeldung.batchinserts.repository.CustomerRepository; + +/** + * A simple controller to test the JPA CrudRepository operations + * controllers + * + * @author ysharma2512 + * + */ +@RestController +public class CustomerController { + + @Autowired + CustomerRepository customerRepository; + + public CustomerController(CustomerRepository customerRepository2) { + this.customerRepository = customerRepository2; + } + + @PostMapping("/customers") + public ResponseEntity> insertCustomers() throws URISyntaxException { + Customer c1 = new Customer("James", "Gosling"); + Customer c2 = new Customer("Doug", "Lea"); + Customer c3 = new Customer("Martin", "Fowler"); + Customer c4 = new Customer("Brian", "Goetz"); + List customers = Arrays.asList(c1, c2, c3, c4); + customerRepository.saveAll(customers); + return ResponseEntity.ok(customers); + } + +} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/batchinserts/model/Customer.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/batchinserts/model/Customer.java new file mode 100644 index 0000000000..4d82cf12a2 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/batchinserts/model/Customer.java @@ -0,0 +1,56 @@ +package com.baeldung.batchinserts.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +/** + * Customer Entity class + * @author ysharma2512 + * + */ +@Entity +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String firstName; + private String lastName; + + public Customer(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @Override + public String toString() { + return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); + } + +} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/batchinserts/repository/CustomerRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/batchinserts/repository/CustomerRepository.java new file mode 100644 index 0000000000..ab0214bade --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/batchinserts/repository/CustomerRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.batchinserts.repository; + +import org.springframework.data.repository.CrudRepository; + +import com.baeldung.batchinserts.model.Customer; + +/** + * JPA CrudRepository interface + * + * @author ysharma2512 + * + */ +public interface CustomerRepository extends CrudRepository{ + +} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java index 4299f9e3bb..f5b94e507c 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java @@ -1,7 +1,5 @@ package com.baeldung.dao.repositories; -import java.util.List; - import org.springframework.stereotype.Repository; import com.baeldung.domain.Item; @@ -15,7 +13,4 @@ public interface CustomItemRepository { void findThenDelete(Long id); - List findItemsByColorAndGrade(); - - List findItemByColorOrGrade(); } diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java index 9791cb0aa7..5538448c49 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java @@ -1,12 +1,6 @@ package com.baeldung.dao.repositories.impl; -import java.util.List; - import javax.persistence.EntityManager; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @@ -36,53 +30,4 @@ public class CustomItemRepositoryImpl implements CustomItemRepository { entityManager.remove(item); } - @Override - public List findItemsByColorAndGrade() { - - CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Item.class); - Root itemRoot = criteriaQuery.from(Item.class); - - Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "blue"); - Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "red"); - Predicate predicateForColor = criteriaBuilder.or(predicateForBlueColor, predicateForRedColor); - - Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "A"); - Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B"); - Predicate predicateForGrade = criteriaBuilder.or(predicateForGradeA, predicateForGradeB); - - // final search filter - Predicate finalPredicate = criteriaBuilder.and(predicateForColor, predicateForGrade); - - criteriaQuery.where(finalPredicate); - - List items = entityManager.createQuery(criteriaQuery) - .getResultList(); - return items; - } - - @Override - public List findItemByColorOrGrade() { - - CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Item.class); - Root itemRoot = criteriaQuery.from(Item.class); - - Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "red"); - Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "D"); - Predicate predicateForBlueColorAndGradeA = criteriaBuilder.and(predicateForBlueColor, predicateForGradeA); - - Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "blue"); - Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B"); - Predicate predicateForRedColorAndGradeB = criteriaBuilder.and(predicateForRedColor, predicateForGradeB); - - // final search filter - Predicate finalPredicate = criteriaBuilder.or(predicateForBlueColorAndGradeA, predicateForRedColorAndGradeB); - - criteriaQuery.where(finalPredicate); - - List items = entityManager.createQuery(criteriaQuery) - .getResultList(); - return items; - } } diff --git a/persistence-modules/spring-data-jpa/src/main/resources/application.properties b/persistence-modules/spring-data-jpa/src/main/resources/application.properties index 37fb9ca9c4..239f81db7b 100644 --- a/persistence-modules/spring-data-jpa/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa/src/main/resources/application.properties @@ -14,4 +14,9 @@ hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFa spring.datasource.data=import_entities.sql -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true + +spring.jpa.properties.hibernate.jdbc.batch_size=4 +spring.jpa.properties.hibernate.order_inserts=true +spring.jpa.properties.hibernate.order_updates=true +spring.jpa.properties.hibernate.generate_statistics=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java new file mode 100644 index 0000000000..f60e0d21bf --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java @@ -0,0 +1,44 @@ +package com.baeldung.batchinserts; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import com.baeldung.batchinserts.CustomerController; +import com.baeldung.batchinserts.repository.CustomerRepository; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +@ContextConfiguration(classes = { PersistenceConfiguration.class, PersistenceProductConfiguration.class, PersistenceUserConfiguration.class }) +public class BatchInsertIntegrationTest { + + @Autowired + private CustomerRepository customerRepository; + private MockMvc mockMvc; + @Before + public void setUp() throws Exception { + mockMvc = MockMvcBuilders.standaloneSetup( new CustomerController(customerRepository)) + .build(); + } + + @Test + public void whenInsertingCustomers_thenCustomersAreCreated() throws Exception { + this.mockMvc.perform(post("/customers")) + .andExpect(status().isOk()); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryIntegrationTest.java deleted file mode 100644 index c5fb7fa25f..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryIntegrationTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.baeldung.dao.repositories.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.util.CollectionUtils; - -import com.baeldung.config.PersistenceConfiguration; -import com.baeldung.config.PersistenceProductConfiguration; -import com.baeldung.config.PersistenceUserConfiguration; -import com.baeldung.dao.repositories.CustomItemRepository; -import com.baeldung.domain.Item; - -@RunWith(SpringRunner.class) -@DataJpaTest(excludeAutoConfiguration = { PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class }) -public class CustomItemRepositoryIntegrationTest { - - @Autowired - CustomItemRepository customItemRepositoryImpl; - - @Autowired - EntityManager entityManager; - - @Before - public void setUp() { - - Item firstItem = new Item(); - firstItem.setColor("blue"); - firstItem.setGrade("C"); - firstItem.setId(10l); - - entityManager.persist(firstItem); - - Item secondItem = new Item(); - secondItem.setColor("red"); - secondItem.setGrade("C"); - secondItem.setId(11l); - - entityManager.persist(secondItem); - - Item thirdItem = new Item(); - thirdItem.setColor("blue"); - thirdItem.setGrade("A"); - thirdItem.setId(12l); - - entityManager.persist(thirdItem); - - Item fourthItem = new Item(); - fourthItem.setColor("red"); - fourthItem.setGrade("D"); - fourthItem.setId(13l); - - entityManager.persist(fourthItem); - } - - @Test - public void givenItems_whenFindItemsByColorAndGrade_thenReturnItems() { - - List items = customItemRepositoryImpl.findItemsByColorAndGrade(); - - assertFalse("No items found", CollectionUtils.isEmpty(items)); - assertEquals("There should be only one item", 1, items.size()); - - Item item = items.get(0); - - assertEquals("this item do not have blue color", "blue", item.getColor()); - assertEquals("this item does not belong to A grade", "A", item.getGrade()); - } - - @Test - public void givenItems_whenFindItemByColorOrGrade_thenReturnItems() { - - List items = customItemRepositoryImpl.findItemByColorOrGrade(); - - assertFalse("No items found", CollectionUtils.isEmpty(items)); - assertEquals("There should be only one item", 1, items.size()); - - Item item = items.get(0); - - assertEquals("this item do not have red color", "red", item.getColor()); - assertEquals("this item does not belong to D grade", "D", item.getGrade()); - } - -} diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 29a6996791..3daba6cd55 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -156,13 +156,13 @@ - 4.3.8.RELEASE + 5.1.5.RELEASE 3.21.0-GA - 5.2.10.Final + 5.2.17.Final 6.0.6 - 1.11.3.RELEASE + 2.1.5.RELEASE 1.4.195 @@ -170,7 +170,7 @@ 2.5 - 5.4.1.Final + 6.0.15.Final 1.4.01 2.2.5 diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java index aa85128628..822cbb8ed5 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -3,6 +3,7 @@ package com.baeldung; import org.baeldung.config.PersistenceJPAConfigL2Cache; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @@ -11,6 +12,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) @WebAppConfiguration +@DirtiesContext public class SpringContextIntegrationTest { @Test diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java index 9ddc48460a..4d1bcbe1b2 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java @@ -35,7 +35,7 @@ public class InMemoryDBIntegrationTest { Student student = new Student(ID, NAME); studentRepository.save(student); - Student student2 = studentRepository.findOne(ID); + Student student2 = studentRepository.findById(ID).get(); assertEquals("name incorrect", NAME, student2.getName()); } diff --git a/pom.xml b/pom.xml index d26b96ea8e..615fc7b46e 100644 --- a/pom.xml +++ b/pom.xml @@ -377,8 +377,10 @@ core-groovy + core-java-8 + core-java-arrays core-java-collections core-java-collections-list @@ -392,7 +394,8 @@ core-java-networking core-java-perf core-java-sun - core-java + core-java + core-java-jvm core-scala couchbase custom-pmd @@ -434,9 +437,11 @@ immutables jackson + jackson-2 java-collections-conversions java-collections-maps + java-lite java-numbers @@ -456,6 +461,7 @@ jersey JGit jgroups + jhipster jib jjwt jmeter @@ -524,6 +530,9 @@ rxjava rxjava-2 software-security/sql-injection-samples + + tensorflow-java + @@ -568,6 +577,7 @@ spring-4 spring-5 + spring-5-webflux spring-5-mvc spring-5-reactive spring-5-reactive-client @@ -587,6 +597,7 @@ spring-boot spring-boot-admin + spring-boot-angular spring-boot-angular-ecommerce spring-boot-autoconfiguration spring-boot-bootstrap @@ -739,6 +750,8 @@ xml xmlunit-2 xstream + + tensorflow-java @@ -924,7 +937,6 @@ core-kotlin-2 jenkins/hello-world - jhipster jws libraries @@ -1015,6 +1027,7 @@ core-java-8 + core-java-arrays core-java-collections core-java-collections-list @@ -1069,6 +1082,7 @@ immutables jackson + jackson-2 java-collections-conversions java-collections-maps @@ -1091,6 +1105,7 @@ jersey JGit jgroups + jhipster jib jjwt jmeter @@ -1218,6 +1233,7 @@ spring-boot spring-boot-admin + spring-boot-angular spring-boot-angular-ecommerce spring-boot-autoconfiguration spring-boot-bootstrap @@ -1409,7 +1425,6 @@ core-kotlin-2 jenkins/hello-world - jhipster jws libraries @@ -1478,7 +1493,7 @@ 2.3.1 1.9.13 1.2 - 2.9.7 + 2.9.8 1.3 1.2.0 5.2.0 diff --git a/reactor-core/README.md b/reactor-core/README.md index 6f90e59894..5f9d2d1bc2 100644 --- a/reactor-core/README.md +++ b/reactor-core/README.md @@ -2,3 +2,4 @@ - [Intro To Reactor Core](http://www.baeldung.com/reactor-core) - [Combining Publishers in Project Reactor](http://www.baeldung.com/reactor-combine-streams) +- [Programmatically Creating Sequences with Project Reactor](https://www.baeldung.com/flux-sequences-reactor) diff --git a/reactor-core/pom.xml b/reactor-core/pom.xml index db9550df7b..66c634e113 100644 --- a/reactor-core/pom.xml +++ b/reactor-core/pom.xml @@ -16,7 +16,13 @@ io.projectreactor reactor-core - ${reactor-core.version} + ${reactor.version} + + + io.projectreactor + reactor-test + ${reactor.version} + test org.assertj @@ -24,16 +30,10 @@ ${assertj.version} test - - io.projectreactor - reactor-test - ${reactor-core.version} - test - - 3.1.3.RELEASE + 3.2.6.RELEASE 3.6.1 diff --git a/reactor-core/src/main/java/com/baeldung/reactor/creation/FibonacciState.java b/reactor-core/src/main/java/com/baeldung/reactor/creation/FibonacciState.java new file mode 100644 index 0000000000..291002e1f9 --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/creation/FibonacciState.java @@ -0,0 +1,27 @@ +package com.baeldung.reactor.creation; + +public class FibonacciState { + private int former; + private int latter; + + public FibonacciState(int former, int latter) { + this.former = former; + this.latter = latter; + } + + public int getFormer() { + return former; + } + + public void setFormer(int former) { + this.former = former; + } + + public int getLatter() { + return latter; + } + + public void setLatter(int latter) { + this.latter = latter; + } +} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceCreator.java b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceCreator.java new file mode 100644 index 0000000000..fb53b1cab1 --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceCreator.java @@ -0,0 +1,14 @@ +package com.baeldung.reactor.creation; + +import reactor.core.publisher.Flux; + +import java.util.List; +import java.util.function.Consumer; + +public class SequenceCreator { + public Consumer> consumer; + + public Flux createNumberSequence() { + return Flux.create(sink -> SequenceCreator.this.consumer = items -> items.forEach(sink::next)); + } +} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceGenerator.java b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceGenerator.java new file mode 100644 index 0000000000..44d83d06bf --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceGenerator.java @@ -0,0 +1,31 @@ +package com.baeldung.reactor.creation; + +import reactor.core.publisher.Flux; +import reactor.util.function.Tuples; + +public class SequenceGenerator { + public Flux generateFibonacciWithTuples() { + return Flux.generate( + () -> Tuples.of(0, 1), + (state, sink) -> { + sink.next(state.getT1()); + return Tuples.of(state.getT2(), state.getT1() + state.getT2()); + } + ); + } + + public Flux generateFibonacciWithCustomClass(int limit) { + return Flux.generate( + () -> new FibonacciState(0, 1), + (state, sink) -> { + sink.next(state.getFormer()); + if (state.getLatter() > limit) { + sink.complete(); + } + int temp = state.getFormer(); + state.setFormer(state.getLatter()); + state.setLatter(temp + state.getLatter()); + return state; + }); + } +} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceHandler.java b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceHandler.java new file mode 100644 index 0000000000..a9611c63e2 --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/creation/SequenceHandler.java @@ -0,0 +1,13 @@ +package com.baeldung.reactor.creation; + +import reactor.core.publisher.Flux; + +public class SequenceHandler { + public Flux handleIntegerSequence(Flux sequence) { + return sequence.handle((number, sink) -> { + if (number % 2 == 0) { + sink.next(number / 2); + } + }); + } +} diff --git a/reactor-core/src/test/java/com/baeldung/reactor/creation/SequenceUnitTest.java b/reactor-core/src/test/java/com/baeldung/reactor/creation/SequenceUnitTest.java new file mode 100644 index 0000000000..78af1d2478 --- /dev/null +++ b/reactor-core/src/test/java/com/baeldung/reactor/creation/SequenceUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.reactor.creation; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SequenceUnitTest { + @Test + public void whenGeneratingNumbersWithTuplesState_thenFibonacciSequenceIsProduced() { + SequenceGenerator sequenceGenerator = new SequenceGenerator(); + Flux fibonacciFlux = sequenceGenerator.generateFibonacciWithTuples().take(5); + + StepVerifier.create(fibonacciFlux) + .expectNext(0, 1, 1, 2, 3) + .expectComplete() + .verify(); + } + + @Test + public void whenGeneratingNumbersWithCustomClass_thenFibonacciSequenceIsProduced() { + SequenceGenerator sequenceGenerator = new SequenceGenerator(); + + StepVerifier.create(sequenceGenerator.generateFibonacciWithCustomClass(10)) + .expectNext(0, 1, 1, 2, 3, 5, 8) + .expectComplete() + .verify(); + } + + @Test + public void whenCreatingNumbers_thenSequenceIsProducedAsynchronously() throws InterruptedException { + SequenceGenerator sequenceGenerator = new SequenceGenerator(); + List sequence1 = sequenceGenerator.generateFibonacciWithTuples().take(3).collectList().block(); + List sequence2 = sequenceGenerator.generateFibonacciWithTuples().take(4).collectList().block(); + + SequenceCreator sequenceCreator = new SequenceCreator(); + Thread producingThread1 = new Thread( + () -> sequenceCreator.consumer.accept(sequence1) + ); + Thread producingThread2 = new Thread( + () -> sequenceCreator.consumer.accept(sequence2) + ); + + List consolidated = new ArrayList<>(); + sequenceCreator.createNumberSequence().subscribe(consolidated::add); + + producingThread1.start(); + producingThread2.start(); + producingThread1.join(); + producingThread2.join(); + + assertThat(consolidated).containsExactlyInAnyOrder(0, 1, 1, 0, 1, 1, 2); + } + + @Test + public void whenHandlingNumbers_thenSequenceIsMappedAndFiltered() { + SequenceHandler sequenceHandler = new SequenceHandler(); + SequenceGenerator sequenceGenerator = new SequenceGenerator(); + Flux sequence = sequenceGenerator.generateFibonacciWithTuples().take(10); + + StepVerifier.create(sequenceHandler.handleIntegerSequence(sequence)) + .expectNext(0, 1, 4, 17) + .expectComplete() + .verify(); + } +} diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java new file mode 100644 index 0000000000..b79fa9af22 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java @@ -0,0 +1,84 @@ +package com.baeldung.rxjava; + +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Test; + +import io.reactivex.Observable; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; + +public class RxJavaHooksManualTest { + + private boolean initHookCalled = false; + private boolean hookCalled = false; + + @Test + public void givenIOScheduler_whenCalled_shouldExecuteTheHooks() { + + RxJavaPlugins.setInitIoSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setIoSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.io()) + .test(); + assertTrue(hookCalled && initHookCalled); + } + + @Test + public void givenNewThreadScheduler_whenCalled_shouldExecuteTheHook() { + + RxJavaPlugins.setInitNewThreadSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setNewThreadSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 15) + .map(v -> v * 2) + .subscribeOn(Schedulers.newThread()) + .test(); + assertTrue(hookCalled && initHookCalled); + } + + @Test + public void givenSingleScheduler_whenCalled_shouldExecuteTheHooks() { + + RxJavaPlugins.setInitSingleSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setSingleSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.single()) + .test(); + assertTrue(hookCalled && initHookCalled); + + } + + @After + public void reset() { + hookCalled = false; + initHookCalled = false; + RxJavaPlugins.reset(); + } +} diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java new file mode 100644 index 0000000000..dd4287a4a9 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java @@ -0,0 +1,244 @@ +package com.baeldung.rxjava; + +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Test; + +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Maybe; +import io.reactivex.Observable; +import io.reactivex.Single; +import io.reactivex.flowables.ConnectableFlowable; +import io.reactivex.observables.ConnectableObservable; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; + +public class RxJavaHooksUnitTest { + + private boolean initHookCalled = false; + private boolean hookCalled = false; + + @Test + public void givenObservable_whenError_shouldExecuteTheHook() { + RxJavaPlugins.setErrorHandler(throwable -> { + hookCalled = true; + }); + + Observable.error(new IllegalStateException()) + .subscribe(); + assertTrue(hookCalled); + } + + @Test + public void givenCompletable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnCompletableAssembly(completable -> { + hookCalled = true; + return completable; + }); + Completable.fromSingle(Single.just(1)); + assertTrue(hookCalled); + } + + @Test + public void givenCompletable_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnCompletableSubscribe((completable, observer) -> { + hookCalled = true; + return observer; + }); + + Completable.fromSingle(Single.just(1)) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenObservable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnObservableAssembly(observable -> { + hookCalled = true; + return observable; + }); + + Observable.range(1, 10); + assertTrue(hookCalled); + } + + @Test + public void givenObservable_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnObservableSubscribe((observable, observer) -> { + hookCalled = true; + return observer; + }); + + Observable.range(1, 10) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenConnectableObservable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnConnectableObservableAssembly(connectableObservable -> { + hookCalled = true; + return connectableObservable; + }); + + ConnectableObservable.range(1, 10) + .publish() + .connect(); + assertTrue(hookCalled); + } + + @Test + public void givenFlowable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnFlowableAssembly(flowable -> { + hookCalled = true; + return flowable; + }); + + Flowable.range(1, 10); + assertTrue(hookCalled); + } + + @Test + public void givenFlowable_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnFlowableSubscribe((flowable, observer) -> { + hookCalled = true; + return observer; + }); + + Flowable.range(1, 10) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenConnectableFlowable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnConnectableFlowableAssembly(connectableFlowable -> { + hookCalled = true; + return connectableFlowable; + }); + + ConnectableFlowable.range(1, 10) + .publish() + .connect(); + assertTrue(hookCalled); + } + + @Test + public void givenParallel_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnParallelAssembly(parallelFlowable -> { + hookCalled = true; + return parallelFlowable; + }); + + Flowable.range(1, 10) + .parallel(); + assertTrue(hookCalled); + } + + @Test + public void givenMaybe_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnMaybeAssembly(maybe -> { + hookCalled = true; + return maybe; + }); + + Maybe.just(1); + assertTrue(hookCalled); + } + + @Test + public void givenMaybe_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnMaybeSubscribe((maybe, observer) -> { + hookCalled = true; + return observer; + }); + + Maybe.just(1) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenSingle_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnSingleAssembly(single -> { + hookCalled = true; + return single; + }); + + Single.just(1); + assertTrue(hookCalled); + } + + @Test + public void givenSingle_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnSingleSubscribe((single, observer) -> { + hookCalled = true; + return observer; + }); + + Single.just(1) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenAnyScheduler_whenCalled_shouldExecuteTheHook() { + + RxJavaPlugins.setScheduleHandler((runnable) -> { + hookCalled = true; + return runnable; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.single()) + .test(); + hookCalled = false; + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.computation()) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenComputationScheduler_whenCalled_shouldExecuteTheHooks() { + + RxJavaPlugins.setInitComputationSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + RxJavaPlugins.setComputationSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.computation()) + .test(); + assertTrue(hookCalled && initHookCalled); + } + + @After + public void reset() { + initHookCalled = false; + hookCalled = false; + RxJavaPlugins.reset(); + } +} diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index fa9d48ab72..7e83077f54 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -2,4 +2,3 @@ - [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin) - [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) - [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) -- [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index ef2f7d07eb..538a15c879 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -19,3 +19,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Logging a Reactive Sequence](https://www.baeldung.com/spring-reactive-sequence-logging) - [Testing Reactive Streams Using StepVerifier and TestPublisher](https://www.baeldung.com/reactive-streams-step-verifier-test-publisher) - [Debugging Reactive Streams in Spring 5](https://www.baeldung.com/spring-debugging-reactive-streams) +- [Static Content in Spring WebFlux](https://www.baeldung.com/spring-webflux-static-content) diff --git a/spring-5-webflux/.gitignore b/spring-5-webflux/.gitignore new file mode 100644 index 0000000000..aa4871eeea --- /dev/null +++ b/spring-5-webflux/.gitignore @@ -0,0 +1,2 @@ +# Files # +*.log \ No newline at end of file diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml new file mode 100644 index 0000000000..3306fd1729 --- /dev/null +++ b/spring-5-webflux/pom.xml @@ -0,0 +1,63 @@ + + + + 4.0.0 + com.baeldung + spring-5-webflux + 1.0-SNAPSHOT + spring-5-webflux + http://www.baeldung.com + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.projectlombok + lombok + + + + org.springframework.boot + spring-boot-starter-test + test + + + + junit + junit + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/ResponseStatusController.java b/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/ResponseStatusController.java new file mode 100644 index 0000000000..bc4f628ab1 --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/ResponseStatusController.java @@ -0,0 +1,64 @@ +package com.baeldung.spring.responsestatus; + +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; + +@RequestMapping("/statuses") +@RestController +public class ResponseStatusController { + + @GetMapping(value = "/ok", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + public Flux ok() { + return Flux.just("ok"); + } + + @GetMapping(value = "/no-content", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + @ResponseStatus(HttpStatus.NO_CONTENT) + public Flux noContent() { + return Flux.empty(); + } + + @GetMapping(value = "/accepted", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + public Flux accepted(ServerHttpResponse response) { + response.setStatusCode(HttpStatus.ACCEPTED); + return Flux.just("accepted"); + } + + @GetMapping(value = "/bad-request") + public Mono badRequest() { + return Mono.error(new IllegalArgumentException()); + } + + @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Illegal arguments") + @ExceptionHandler(IllegalArgumentException.class) + public void illegalArgument() { + + } + + @GetMapping(value = "/unauthorized") + public ResponseEntity> unathorized() { + return ResponseEntity + .status(HttpStatus.UNAUTHORIZED) + .header("X-Reason", "user-invalid") + .body(Mono.just("unauthorized")); + } + + @Bean + public RouterFunction notFound() { + return RouterFunctions.route(GET("/statuses/not-found"), request -> ServerResponse + .notFound() + .build()); + } + +} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/SpringResponseStatusApp.java b/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/SpringResponseStatusApp.java new file mode 100644 index 0000000000..1d90511d9d --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/responsestatus/SpringResponseStatusApp.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.responsestatus; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringResponseStatusApp { + + public static void main(String[] args) { + SpringApplication.run(SpringResponseStatusApp.class, args); + } +} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/CustomNettyWebServerFactory.java b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/CustomNettyWebServerFactory.java new file mode 100644 index 0000000000..f9de3b4006 --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/CustomNettyWebServerFactory.java @@ -0,0 +1,36 @@ +package com.baeldung.spring.serverconfig; + +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; +import org.springframework.boot.web.embedded.netty.NettyServerCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import reactor.netty.http.server.HttpServer; + +@Configuration +@Profile("skipAutoConfig") +public class CustomNettyWebServerFactory { + + @Bean + public NettyReactiveWebServerFactory nettyReactiveWebServerFactory() { + NettyReactiveWebServerFactory webServerFactory = new NettyReactiveWebServerFactory(); + webServerFactory.addServerCustomizers(new EventLoopNettyCustomizer()); + return webServerFactory; + } + + private static class EventLoopNettyCustomizer implements NettyServerCustomizer { + + @Override + public HttpServer apply(HttpServer httpServer) { + EventLoopGroup parentGroup = new NioEventLoopGroup(); + EventLoopGroup childGroup = new NioEventLoopGroup(); + return httpServer + .tcpConfiguration(tcpServer -> tcpServer.bootstrap( + serverBootstrap -> serverBootstrap.group(parentGroup, childGroup).channel(NioServerSocketChannel.class) + )); + } + } +} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/GreetingController.java b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/GreetingController.java new file mode 100644 index 0000000000..990ea5cf83 --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/GreetingController.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.serverconfig; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +@RestController +@RequestMapping("/greet") +public class GreetingController { + + private final GreetingService greetingService; + + public GreetingController(GreetingService greetingService) { + this.greetingService = greetingService; + } + + @GetMapping("/{name}") + private Mono greet(@PathVariable String name) { + return greetingService.greet(name); + } +} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/GreetingService.java b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/GreetingService.java new file mode 100644 index 0000000000..a6243b2bd0 --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/GreetingService.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.serverconfig; + +import org.springframework.stereotype.Service; +import reactor.core.publisher.Mono; + +@Service +public class GreetingService { + + public Mono greet(String name) { + return Mono.just("Greeting " + name); + } +} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/NettyWebServerFactoryPortCustomizer.java b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/NettyWebServerFactoryPortCustomizer.java new file mode 100644 index 0000000000..fdde130286 --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/NettyWebServerFactoryPortCustomizer.java @@ -0,0 +1,30 @@ +package com.baeldung.spring.serverconfig; + +import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; +import org.springframework.boot.web.embedded.netty.NettyServerCustomizer; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.stereotype.Component; +import reactor.netty.http.server.HttpServer; + +@Component +public class NettyWebServerFactoryPortCustomizer implements WebServerFactoryCustomizer { + + @Override + public void customize(NettyReactiveWebServerFactory serverFactory) { + serverFactory.addServerCustomizers(new PortCustomizer(8443)); + } + + private static class PortCustomizer implements NettyServerCustomizer { + + private final int port; + + private PortCustomizer(int port) { + this.port = port; + } + + @Override + public HttpServer apply(HttpServer httpServer) { + return httpServer.port(port); + } + } +} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/NettyWebServerFactorySslCustomizer.java b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/NettyWebServerFactorySslCustomizer.java new file mode 100644 index 0000000000..cf4e5ac8ea --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/NettyWebServerFactorySslCustomizer.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.serverconfig; + +import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; +import org.springframework.boot.web.embedded.netty.SslServerCustomizer; +import org.springframework.boot.web.server.Http2; +import org.springframework.boot.web.server.Ssl; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.stereotype.Component; + +@Component +public class NettyWebServerFactorySslCustomizer implements WebServerFactoryCustomizer { + + @Override + public void customize(NettyReactiveWebServerFactory serverFactory) { + Ssl ssl = new Ssl(); + ssl.setEnabled(true); + ssl.setKeyStore("classpath:sample.jks"); + ssl.setKeyAlias("alias"); + ssl.setKeyPassword("password"); + ssl.setKeyStorePassword("secret"); + Http2 http2 = new Http2(); + http2.setEnabled(false); + serverFactory.addServerCustomizers(new SslServerCustomizer(ssl, http2, null)); + serverFactory.setPort(8443); + } +} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/ServerConfigApplication.java b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/ServerConfigApplication.java new file mode 100644 index 0000000000..b4f6006be3 --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/serverconfig/ServerConfigApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.serverconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ServerConfigApplication { + + public static void main(String[] args) { + SpringApplication.run(ServerConfigApplication.class, args); + } +} diff --git a/spring-5-webflux/src/main/resources/logback.xml b/spring-5-webflux/src/main/resources/logback.xml new file mode 100644 index 0000000000..48b68c6bf1 --- /dev/null +++ b/spring-5-webflux/src/main/resources/logback.xml @@ -0,0 +1,31 @@ + + + + + + %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable + + + + + + netty-access.log + + %msg%n + + + + + + + + + + + + + + + + diff --git a/spring-5-webflux/src/main/resources/sample.jks b/spring-5-webflux/src/main/resources/sample.jks new file mode 100644 index 0000000000..6aa9a28053 Binary files /dev/null and b/spring-5-webflux/src/main/resources/sample.jks differ diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/responsestatus/ResponseStatusControllerLiveTest.java b/spring-5-webflux/src/test/java/com/baeldung/spring/responsestatus/ResponseStatusControllerLiveTest.java new file mode 100644 index 0000000000..4c6708e423 --- /dev/null +++ b/spring-5-webflux/src/test/java/com/baeldung/spring/responsestatus/ResponseStatusControllerLiveTest.java @@ -0,0 +1,70 @@ +package com.baeldung.spring.responsestatus; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ResponseStatusControllerLiveTest { + + @Autowired + private WebTestClient testClient; + + @Test + public void whenCallRest_thenStatusIsOk() { + testClient.get() + .uri("/statuses/ok") + .exchange() + .expectStatus() + .isOk(); + } + + @Test + public void whenCallRest_thenStatusIsNoContent() { + testClient.get() + .uri("/statuses/no-content") + .exchange() + .expectStatus() + .isNoContent(); + } + + @Test + public void whenCallRest_thenStatusIsAccepted() { + testClient.get() + .uri("/statuses/accepted") + .exchange() + .expectStatus() + .isAccepted(); + } + + @Test + public void whenCallRest_thenStatusIsBadRequest() { + testClient.get() + .uri("/statuses/bad-request") + .exchange() + .expectStatus() + .isBadRequest(); + } + + @Test + public void whenCallRest_thenStatusIsUnauthorized() { + testClient.get() + .uri("/statuses/unauthorized") + .exchange() + .expectStatus() + .isUnauthorized(); + } + + @Test + public void whenCallRest_thenStatusIsNotFound() { + testClient.get() + .uri("/statuses/not-found") + .exchange() + .expectStatus() + .isNotFound(); + } +} diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/GreetingControllerIntegrationTest.java b/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/GreetingControllerIntegrationTest.java new file mode 100644 index 0000000000..ce156beb3f --- /dev/null +++ b/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/GreetingControllerIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.spring.serverconfig; + +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@WebFluxTest +public class GreetingControllerIntegrationTest { + + @Autowired + private WebTestClient webClient; + + @MockBean + private GreetingService greetingService; + + private final String name = "Baeldung"; + + @Before + public void setUp() { + when(greetingService.greet(name)).thenReturn(Mono.just("Greeting Baeldung")); + } + + @Test + public void shouldGreet() { + webClient.get().uri("/greet/{name}", name) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Greeting Baeldung"); + } +} diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/GreetingLiveTest.java b/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/GreetingLiveTest.java new file mode 100644 index 0000000000..2400272c6e --- /dev/null +++ b/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/GreetingLiveTest.java @@ -0,0 +1,57 @@ +package com.baeldung.spring.serverconfig; + +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import javax.net.ssl.SSLException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; +import reactor.netty.http.client.HttpClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) +@DirtiesContext +public class GreetingLiveTest { + + private static final String BASE_URL = "https://localhost:8443"; + + private WebTestClient webTestClient; + + @Before + public void setup() throws SSLException { + webTestClient = WebTestClient.bindToServer(getConnector()) + .baseUrl(BASE_URL) + .build(); + } + + @Test + public void shouldGreet() { + final String name = "Baeldung"; + + ResponseSpec response = webTestClient.get() + .uri("/greet/{name}", name) + .exchange(); + + response.expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Greeting Baeldung"); + } + + private ReactorClientHttpConnector getConnector() throws SSLException { + SslContext sslContext = SslContextBuilder + .forClient() + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .build(); + HttpClient httpClient = HttpClient.create().secure(t -> t.sslContext(sslContext)); + return new ReactorClientHttpConnector(httpClient); + } +} diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/GreetingSkipAutoConfigLiveTest.java b/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/GreetingSkipAutoConfigLiveTest.java new file mode 100644 index 0000000000..45918dfd70 --- /dev/null +++ b/spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/GreetingSkipAutoConfigLiveTest.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.serverconfig; + +import org.springframework.test.context.ActiveProfiles; + +@ActiveProfiles("skipAutoConfig") +public class GreetingSkipAutoConfigLiveTest extends GreetingLiveTest { + +} diff --git a/spring-5-webflux/src/test/resources/logback-test.xml b/spring-5-webflux/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..12cedf5952 --- /dev/null +++ b/spring-5-webflux/src/test/resources/logback-test.xml @@ -0,0 +1,13 @@ + + + + + + %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable + + + + + + + diff --git a/spring-all/README.md b/spring-all/README.md index 81dd435007..82d876768e 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -22,7 +22,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Guide to the Spring Task Scheduler](http://www.baeldung.com/spring-task-scheduler) - [Guide to Spring Retry](http://www.baeldung.com/spring-retry) - [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope) -- [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent) - [A CLI with Spring Shell](http://www.baeldung.com/spring-shell-cli) - [JasperReports with Spring](http://www.baeldung.com/spring-jasper) - [Model, ModelMap, and ModelView in Spring MVC](http://www.baeldung.com/spring-mvc-model-model-map-model-view) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 5872fbdac5..8c88efb970 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-all 0.1-SNAPSHOT @@ -47,12 +47,16 @@ org.springframework spring-websocket - - + + org.springframework spring-messaging - - + + + javax.annotation + javax.annotation-api + ${annotation-api.version} + org.springframework @@ -227,13 +231,13 @@ - + org.baeldung.sample.App 5.0.6.RELEASE 1.2.0.RELEASE - + 1.3.2 5.2.5.Final diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java index 08626bb4d2..6589143a94 100644 --- a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java +++ b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithJavaConfig.java @@ -7,6 +7,7 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration @PropertySource("classpath:foo.properties") +@PropertySource("classpath:bar.properties") public class PropertiesWithJavaConfig { public PropertiesWithJavaConfig() { diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/BallService.java b/spring-all/src/main/java/org/baeldung/sampleabstract/BallService.java new file mode 100644 index 0000000000..9a75de7fa1 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/BallService.java @@ -0,0 +1,28 @@ +package org.baeldung.sampleabstract; + +import org.springframework.beans.factory.annotation.Autowired; + +import javax.annotation.PostConstruct; + +public abstract class BallService { + + private RuleRepository ruleRepository; + + private LogRepository logRepository; + + public BallService(RuleRepository ruleRepository) { + this.ruleRepository = ruleRepository; + } + + @Autowired + public final void setLogRepository(LogRepository logRepository) { + this.logRepository = logRepository; + } + + @PostConstruct + public void afterInitialize() { + + System.out.println(ruleRepository.toString()); + System.out.println(logRepository.toString()); + } +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/BasketballService.java b/spring-all/src/main/java/org/baeldung/sampleabstract/BasketballService.java new file mode 100644 index 0000000000..c117231d3c --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/BasketballService.java @@ -0,0 +1,13 @@ +package org.baeldung.sampleabstract; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class BasketballService extends BallService { + + @Autowired + public BasketballService(RuleRepository ruleRepository) { + super(ruleRepository); + } +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java b/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java new file mode 100644 index 0000000000..615d354ecf --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/DemoApp.java @@ -0,0 +1,18 @@ +package org.baeldung.sampleabstract; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = "org.baeldung.sampleabstract") +public class DemoApp { + + + public static void main(String[] args) { + + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoApp.class); + } + +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/LogRepository.java b/spring-all/src/main/java/org/baeldung/sampleabstract/LogRepository.java new file mode 100644 index 0000000000..3a65671493 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/LogRepository.java @@ -0,0 +1,12 @@ +package org.baeldung.sampleabstract; + +import org.springframework.stereotype.Component; + +@Component +public class LogRepository { + + @Override + public String toString() { + return "logRepository"; + } +} diff --git a/spring-all/src/main/java/org/baeldung/sampleabstract/RuleRepository.java b/spring-all/src/main/java/org/baeldung/sampleabstract/RuleRepository.java new file mode 100644 index 0000000000..fd42178ab6 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/sampleabstract/RuleRepository.java @@ -0,0 +1,12 @@ +package org.baeldung.sampleabstract; + +import org.springframework.stereotype.Component; + +@Component +public class RuleRepository { + + @Override + public String toString() { + return "ruleRepository"; + } +} diff --git a/spring-all/src/main/resources/configForProperties.xml b/spring-all/src/main/resources/configForProperties.xml index 0f766665eb..459aea3ec6 100644 --- a/spring-all/src/main/resources/configForProperties.xml +++ b/spring-all/src/main/resources/configForProperties.xml @@ -7,7 +7,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd" > - + diff --git a/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesJavaConfigIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesJavaConfigIntegrationTest.java new file mode 100644 index 0000000000..9cb41c20f7 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesJavaConfigIntegrationTest.java @@ -0,0 +1,25 @@ +package org.baeldung.properties.multiple; + +import org.baeldung.properties.spring.PropertiesWithJavaConfig; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringJUnitConfig(PropertiesWithJavaConfig.class) +public class MultiplePropertiesJavaConfigIntegrationTest { + + @Value("${key.something}") + private String something; + + @Value("${key.something2}") + private String something2; + + + @Test + public void whenReadInjectedValues_thenGetCorrectValues() { + assertThat(something).isEqualTo("val"); + assertThat(something2).isEqualTo("val2"); + } +} diff --git a/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java new file mode 100644 index 0000000000..b4f81f3541 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java @@ -0,0 +1,21 @@ +package org.baeldung.properties.multiple; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringJUnitConfig(locations = "classpath:configForProperties.xml") +public class MultiplePropertiesXmlConfigIntegrationTest { + + @Value("${key.something}") private String something; + + @Value("${key.something2}") private String something2; + + @Test + public void whenReadInjectedValues_thenGetCorrectValues() { + assertThat(something).isEqualTo("val"); + assertThat(something2).isEqualTo("val2"); + } +} diff --git a/spring-boot-angular-ecommerce/src/main/frontend/package.json b/spring-boot-angular-ecommerce/src/main/frontend/package.json index 958e9f1023..17363ef961 100644 --- a/spring-boot-angular-ecommerce/src/main/frontend/package.json +++ b/spring-boot-angular-ecommerce/src/main/frontend/package.json @@ -7,7 +7,7 @@ "build": "ng build", "postbuild": "npm run deploy", "predeploy": "rimraf ../resources/static/ && mkdirp ../resources/static", - "deploy": "copyfiles -f dist/** ../resources/static", + "deploy": "copyfiles -f dist/frontend/** ../resources/static", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" diff --git a/spring-boot-angular/README.md b/spring-boot-angular/README.md new file mode 100644 index 0000000000..cfc1ea69f4 --- /dev/null +++ b/spring-boot-angular/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Building a Web Application with Spring Boot and Angular](https://www.baeldung.com/spring-boot-angular-web) + diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/.angular-cli.json b/spring-boot-angular/angularclient/.angular-cli.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/.angular-cli.json rename to spring-boot-angular/angularclient/.angular-cli.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/.editorconfig b/spring-boot-angular/angularclient/.editorconfig similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/.editorconfig rename to spring-boot-angular/angularclient/.editorconfig diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/.gitignore b/spring-boot-angular/angularclient/.gitignore similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/.gitignore rename to spring-boot-angular/angularclient/.gitignore diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/README.md b/spring-boot-angular/angularclient/README.md similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/README.md rename to spring-boot-angular/angularclient/README.md diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/app.e2e-spec.ts b/spring-boot-angular/angularclient/e2e/app.e2e-spec.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/app.e2e-spec.ts rename to spring-boot-angular/angularclient/e2e/app.e2e-spec.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/app.po.ts b/spring-boot-angular/angularclient/e2e/app.po.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/app.po.ts rename to spring-boot-angular/angularclient/e2e/app.po.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/tsconfig.e2e.json b/spring-boot-angular/angularclient/e2e/tsconfig.e2e.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/e2e/tsconfig.e2e.json rename to spring-boot-angular/angularclient/e2e/tsconfig.e2e.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/karma.conf.js b/spring-boot-angular/angularclient/karma.conf.js similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/karma.conf.js rename to spring-boot-angular/angularclient/karma.conf.js diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/package-lock.json b/spring-boot-angular/angularclient/package-lock.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/package-lock.json rename to spring-boot-angular/angularclient/package-lock.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/package.json b/spring-boot-angular/angularclient/package.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/package.json rename to spring-boot-angular/angularclient/package.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/protractor.conf.js b/spring-boot-angular/angularclient/protractor.conf.js similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/protractor.conf.js rename to spring-boot-angular/angularclient/protractor.conf.js diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app-routing.module.ts b/spring-boot-angular/angularclient/src/app/app-routing.module.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app-routing.module.ts rename to spring-boot-angular/angularclient/src/app/app-routing.module.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.css b/spring-boot-angular/angularclient/src/app/app.component.css similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.css rename to spring-boot-angular/angularclient/src/app/app.component.css diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.html b/spring-boot-angular/angularclient/src/app/app.component.html similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.html rename to spring-boot-angular/angularclient/src/app/app.component.html diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.spec.ts b/spring-boot-angular/angularclient/src/app/app.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.spec.ts rename to spring-boot-angular/angularclient/src/app/app.component.spec.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.ts b/spring-boot-angular/angularclient/src/app/app.component.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.component.ts rename to spring-boot-angular/angularclient/src/app/app.component.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.module.ts b/spring-boot-angular/angularclient/src/app/app.module.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/app.module.ts rename to spring-boot-angular/angularclient/src/app/app.module.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/model/user.ts b/spring-boot-angular/angularclient/src/app/model/user.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/model/user.ts rename to spring-boot-angular/angularclient/src/app/model/user.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/service/user.service.spec.ts b/spring-boot-angular/angularclient/src/app/service/user.service.spec.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/service/user.service.spec.ts rename to spring-boot-angular/angularclient/src/app/service/user.service.spec.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/service/user.service.ts b/spring-boot-angular/angularclient/src/app/service/user.service.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/service/user.service.ts rename to spring-boot-angular/angularclient/src/app/service/user.service.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.css b/spring-boot-angular/angularclient/src/app/user-form/user-form.component.css similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.css rename to spring-boot-angular/angularclient/src/app/user-form/user-form.component.css diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.html b/spring-boot-angular/angularclient/src/app/user-form/user-form.component.html similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.html rename to spring-boot-angular/angularclient/src/app/user-form/user-form.component.html diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.spec.ts b/spring-boot-angular/angularclient/src/app/user-form/user-form.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.spec.ts rename to spring-boot-angular/angularclient/src/app/user-form/user-form.component.spec.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.ts b/spring-boot-angular/angularclient/src/app/user-form/user-form.component.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-form/user-form.component.ts rename to spring-boot-angular/angularclient/src/app/user-form/user-form.component.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.css b/spring-boot-angular/angularclient/src/app/user-list/user-list.component.css similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.css rename to spring-boot-angular/angularclient/src/app/user-list/user-list.component.css diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.html b/spring-boot-angular/angularclient/src/app/user-list/user-list.component.html similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.html rename to spring-boot-angular/angularclient/src/app/user-list/user-list.component.html diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.spec.ts b/spring-boot-angular/angularclient/src/app/user-list/user-list.component.spec.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.spec.ts rename to spring-boot-angular/angularclient/src/app/user-list/user-list.component.spec.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.ts b/spring-boot-angular/angularclient/src/app/user-list/user-list.component.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/app/user-list/user-list.component.ts rename to spring-boot-angular/angularclient/src/app/user-list/user-list.component.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/assets/.gitkeep b/spring-boot-angular/angularclient/src/assets/.gitkeep similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/assets/.gitkeep rename to spring-boot-angular/angularclient/src/assets/.gitkeep diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/environments/environment.prod.ts b/spring-boot-angular/angularclient/src/environments/environment.prod.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/environments/environment.prod.ts rename to spring-boot-angular/angularclient/src/environments/environment.prod.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/environments/environment.ts b/spring-boot-angular/angularclient/src/environments/environment.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/environments/environment.ts rename to spring-boot-angular/angularclient/src/environments/environment.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/favicon.ico b/spring-boot-angular/angularclient/src/favicon.ico similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/favicon.ico rename to spring-boot-angular/angularclient/src/favicon.ico diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/index.html b/spring-boot-angular/angularclient/src/index.html similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/index.html rename to spring-boot-angular/angularclient/src/index.html diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/main.ts b/spring-boot-angular/angularclient/src/main.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/main.ts rename to spring-boot-angular/angularclient/src/main.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/polyfills.ts b/spring-boot-angular/angularclient/src/polyfills.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/polyfills.ts rename to spring-boot-angular/angularclient/src/polyfills.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/styles.css b/spring-boot-angular/angularclient/src/styles.css similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/styles.css rename to spring-boot-angular/angularclient/src/styles.css diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/tsconfig.app.json b/spring-boot-angular/angularclient/src/tsconfig.app.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/tsconfig.app.json rename to spring-boot-angular/angularclient/src/tsconfig.app.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/tsconfig.spec.json b/spring-boot-angular/angularclient/src/tsconfig.spec.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/tsconfig.spec.json rename to spring-boot-angular/angularclient/src/tsconfig.spec.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/src/typings.d.ts b/spring-boot-angular/angularclient/src/typings.d.ts similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/src/typings.d.ts rename to spring-boot-angular/angularclient/src/typings.d.ts diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/tsconfig.json b/spring-boot-angular/angularclient/tsconfig.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/tsconfig.json rename to spring-boot-angular/angularclient/tsconfig.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/angularclient/tslint.json b/spring-boot-angular/angularclient/tslint.json similarity index 100% rename from spring-boot-angular/src/main/java/com/baeldung/angularclient/tslint.json rename to spring-boot-angular/angularclient/tslint.json diff --git a/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java b/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java index c101ed771f..14c90d5b10 100644 --- a/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java +++ b/spring-boot-angular/src/main/java/com/baeldung/application/controllers/UserController.java @@ -1,6 +1,6 @@ package com.baeldung.application.controllers; -import com.application.entities.User; +import com.baeldung.application.entities.User; import com.baeldung.application.repositories.UserRepository; import java.util.List; import org.springframework.web.bind.annotation.CrossOrigin; diff --git a/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java b/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java index f8ef5a4c0c..5a81cadcbe 100644 --- a/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java +++ b/spring-boot-angular/src/main/java/com/baeldung/application/repositories/UserRepository.java @@ -6,5 +6,4 @@ import org.springframework.stereotype.Repository; import org.springframework.web.bind.annotation.CrossOrigin; @Repository -@CrossOrigin(origins = "http://localhost:4200") public interface UserRepository extends CrudRepository{} diff --git a/spring-boot-angular/src/main/java/com/baeldung/pom.xml b/spring-boot-angular/src/main/java/com/baeldung/pom.xml new file mode 100644 index 0000000000..d4ebc870b4 --- /dev/null +++ b/spring-boot-angular/src/main/java/com/baeldung/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + com.baeldung.springbootangular + spring-boot-angular + 1.0 + jar + Spring Boot Angular Application + + org.springframework.boot + spring-boot-starter-parent + 2.1.3.RELEASE + + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md index 70fcd90118..6a88f25bd7 100644 --- a/spring-boot-bootstrap/README.md +++ b/spring-boot-bootstrap/README.md @@ -1,6 +1,5 @@ ### Relevant Articles: - [Spring Boot Tutorial – Bootstrap a Simple Application](http://www.baeldung.com/spring-boot-start) -- [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) - [Thin JARs with Spring Boot](http://www.baeldung.com/spring-boot-thin-jar) - [Deploying a Spring Boot Application to Cloud Foundry](https://www.baeldung.com/spring-boot-app-deploy-to-cloud-foundry) - [Deploy a Spring Boot Application to Google App Engine](https://www.baeldung.com/spring-boot-google-app-engine) diff --git a/spring-boot-data/pom.xml b/spring-boot-data/pom.xml index 9ef4cc69c8..8735a54e7b 100644 --- a/spring-boot-data/pom.xml +++ b/spring-boot-data/pom.xml @@ -119,4 +119,4 @@ 2.2.4 - \ No newline at end of file + diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md index 553b02ebf0..d5063f14e5 100644 --- a/spring-boot-ops/README.md +++ b/spring-boot-ops/README.md @@ -10,3 +10,5 @@ - [Spring Boot Console Application](http://www.baeldung.com/spring-boot-console-app) - [Comparing Embedded Servlet Containers in Spring Boot](http://www.baeldung.com/spring-boot-servlet-containers) - [Programmatically Restarting a Spring Boot Application](https://www.baeldung.com/java-restart-spring-boot-app) + - [Spring Properties File Outside jar](https://www.baeldung.com/spring-properties-file-outside-jar) + diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index 625b2ad188..f36434b682 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -95,6 +95,15 @@ ${project.artifactId} + + + src/main/resources + true + + **/conf.properties + + + org.springframework.boot @@ -110,6 +119,29 @@ + + org.apache.maven.plugins + maven-failsafe-plugin + 2.18 + + + + integration-tests + + integration-test + verify + + + + + **/ExternalPropertyFileLoaderIntegrationTest.java + + + + + diff --git a/spring-boot-ops/src/main/java/com/baeldung/properties/ConfProperties.java b/spring-boot-ops/src/main/java/com/baeldung/properties/ConfProperties.java new file mode 100644 index 0000000000..0b6041bb06 --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/properties/ConfProperties.java @@ -0,0 +1,43 @@ +package com.baeldung.properties; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class ConfProperties { + + @Value("${url}") + private String url; + + @Value("${username}") + private String username; + + @Value("${password}") + private String password; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + +} diff --git a/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java new file mode 100644 index 0000000000..0cdbb452d5 --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyConfigurer.java @@ -0,0 +1,18 @@ +package com.baeldung.properties; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.core.io.FileSystemResource; + +@Configuration +public class ExternalPropertyConfigurer { + + @Bean + public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer(); + properties.setLocation(new FileSystemResource("src/main/resources/external/conf.properties")); + properties.setIgnoreResourceNotFound(false); + return properties; + } +} \ No newline at end of file diff --git a/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java new file mode 100644 index 0000000000..dc5e14549b --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/properties/ExternalPropertyFileLoader.java @@ -0,0 +1,18 @@ +package com.baeldung.properties; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; + +@SpringBootApplication +public class ExternalPropertyFileLoader { + + @Autowired + ConfProperties prop; + + public static void main(String[] args) { + new SpringApplicationBuilder(ExternalPropertyFileLoader.class).build() + .run(args); + } + +} diff --git a/spring-boot-ops/src/main/resources/external/conf.properties b/spring-boot-ops/src/main/resources/external/conf.properties new file mode 100644 index 0000000000..cfcd23dc76 --- /dev/null +++ b/spring-boot-ops/src/main/resources/external/conf.properties @@ -0,0 +1,4 @@ +url=jdbc:postgresql://localhost:5432/ +username=admin +password=root +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderIntegrationTest.java new file mode 100644 index 0000000000..2001db57d0 --- /dev/null +++ b/spring-boot-ops/src/test/java/com/baeldung/properties/ExternalPropertyFileLoaderIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.properties; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = ExternalPropertyFileLoader.class) +public class ExternalPropertyFileLoaderIntegrationTest { + + @Autowired + ConfProperties props; + + @Test + public void whenExternalisedPropertiesLoaded_thenReadValues() throws IOException { + assertEquals("jdbc:postgresql://localhost:5432/", props.getUrl()); + assertEquals("admin", props.getUsername()); + assertEquals("root", props.getPassword()); + } + +} diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md index 8fbc9527b8..af372077f0 100644 --- a/spring-boot-rest/README.md +++ b/spring-boot-rest/README.md @@ -10,3 +10,4 @@ Module for the articles that are part of the Spring REST E-book: 8. [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest) 9. [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring) 10. [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types) +11. [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java index 1cc732ab08..fbbba23013 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java @@ -9,7 +9,7 @@ public interface IOperations { // read - one - T findOne(final long id); + T findById(final long id); // read - all diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java index 5900c443b8..f589eaecf5 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java @@ -18,9 +18,8 @@ public abstract class AbstractService implements IOperat @Override @Transactional(readOnly = true) - public T findOne(final long id) { - return getDao().findById(id) - .get(); + public T findById(final long id) { + return getDao().findById(id).orElse(null); } // read - all diff --git a/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java b/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java index 4b876a8338..ab16b61e1d 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java +++ b/spring-boot-rest/src/main/java/com/baeldung/spring/WebConfig.java @@ -55,7 +55,7 @@ public class WebConfig implements WebMvcConfigurer { @Bean public FilterRegistrationBean shallowEtagHeaderFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>( new ShallowEtagHeaderFilter()); - filterRegistrationBean.addUrlPatterns("/auth/foos/*"); + filterRegistrationBean.addUrlPatterns("/foos/*"); filterRegistrationBean.setName("etagFilter"); return filterRegistrationBean; } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java index 255fcaabb7..8174480078 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java @@ -20,6 +20,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; import org.springframework.web.util.UriComponentsBuilder; import com.baeldung.persistence.model.Foo; @@ -32,7 +33,7 @@ import com.baeldung.web.util.RestPreconditions; import com.google.common.base.Preconditions; @RestController -@RequestMapping(value = "/auth/foos") +@RequestMapping(value = "/foos") public class FooController { @Autowired @@ -51,22 +52,29 @@ public class FooController { @GetMapping(value = "/{id}/custom-etag") public ResponseEntity findByIdWithCustomEtag(@PathVariable("id") final Long id, final HttpServletResponse response) { - final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); + final Foo foo = RestPreconditions.checkFound(service.findById(id)); eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); return ResponseEntity.ok() - .eTag(Long.toString(resourceById.getVersion())) - .body(resourceById); + .eTag(Long.toString(foo.getVersion())) + .body(foo); } // read - one @GetMapping(value = "/{id}") public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { - final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); + try { + final Foo resourceById = RestPreconditions.checkFound(service.findById(id)); + + eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); + return resourceById; + } + catch (MyResourceNotFoundException exc) { + throw new ResponseStatusException( + HttpStatus.NOT_FOUND, "Foo Not Found", exc); + } - eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); - return resourceById; } // read - all @@ -120,7 +128,7 @@ public class FooController { @ResponseStatus(HttpStatus.OK) public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { Preconditions.checkNotNull(resource); - RestPreconditions.checkFound(service.findOne(resource.getId())); + RestPreconditions.checkFound(service.findById(resource.getId())); service.update(resource); } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/RootController.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/RootController.java index 436e41e8eb..d618e9f0bf 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/controller/RootController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/RootController.java @@ -7,34 +7,28 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.util.UriTemplate; import com.baeldung.web.util.LinkUtil; @Controller -@RequestMapping(value = "/auth/") public class RootController { - public RootController() { - super(); - } - // API // discover - @RequestMapping(value = "admin", method = RequestMethod.GET) + @GetMapping("/") @ResponseStatus(value = HttpStatus.NO_CONTENT) public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) { final String rootUri = request.getRequestURL() .toString(); - final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo"); - final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); - response.addHeader("Link", linkToFoo); + final URI fooUri = new UriTemplate("{rootUri}{resource}").expand(rootUri, "foos"); + final String linkToFoos = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); + response.addHeader("Link", linkToFoos); } } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/Student.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/Student.java new file mode 100644 index 0000000000..3b6a5c0298 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/Student.java @@ -0,0 +1,53 @@ +package com.baeldung.web.controller.students; + +public class Student { + + private long id; + private String firstName; + private String lastName; + + public Student() {} + + public Student(String firstName, String lastName) { + super(); + this.firstName = firstName; + this.lastName = lastName; + } + + public Student(long id, String firstName, String lastName) { + super(); + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @Override + public String toString() { + return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; + } + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentController.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentController.java new file mode 100644 index 0000000000..f937e0c757 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentController.java @@ -0,0 +1,73 @@ +package com.baeldung.web.controller.students; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import com.baeldung.web.controller.students.StudentService; + +@RestController +@RequestMapping("/students") +public class StudentController { + + @Autowired + private StudentService service; + + @GetMapping("/") + public List read() { + return service.readAll(); + } + + @GetMapping("/{id}") + public ResponseEntity read(@PathVariable("id") Long id) { + Student foundStudent = service.read(id); + if (foundStudent == null) { + return ResponseEntity.notFound().build(); + } else { + return ResponseEntity.ok(foundStudent); + } + } + + @PostMapping("/") + public ResponseEntity create(@RequestBody Student student) throws URISyntaxException { + Student createdStudent = service.create(student); + + URI uri = ServletUriComponentsBuilder.fromCurrentRequest() + .path("/{id}") + .buildAndExpand(createdStudent.getId()) + .toUri(); + + return ResponseEntity.created(uri) + .body(createdStudent); + + } + + @PutMapping("/{id}") + public ResponseEntity update(@RequestBody Student student, @PathVariable Long id) { + Student updatedStudent = service.update(id, student); + if (updatedStudent == null) { + return ResponseEntity.notFound().build(); + } else { + return ResponseEntity.ok(updatedStudent); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteStudent(@PathVariable Long id) { + service.delete(id); + + return ResponseEntity.noContent().build(); + } + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentService.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentService.java new file mode 100644 index 0000000000..d923f4f14f --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/students/StudentService.java @@ -0,0 +1,51 @@ +package com.baeldung.web.controller.students; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Service; + +@Service +public class StudentService { + + // DB repository mock + private Map repository = Arrays.asList( + new Student[]{ + new Student(1, "Alan","Turing"), + new Student(2, "Sebastian","Bach"), + new Student(3, "Pablo","Picasso"), + }).stream() + .collect(Collectors.toConcurrentMap(s -> s.getId(), Function.identity())); + + // DB id sequence mock + private AtomicLong sequence = new AtomicLong(3); + + public List readAll() { + return repository.values().stream().collect(Collectors.toList()); + } + + public Student read(Long id) { + return repository.get(id); + } + + public Student create(Student student) { + long key = sequence.incrementAndGet(); + student.setId(key); + repository.put(key, student); + return student; + } + + public Student update(Long id, Student student) { + student.setId(id); + Student oldStudent = repository.replace(id, student); + return oldStudent == null ? null : student; + } + + public void delete(Long id) { + repository.remove(id); + } +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java index 31555ef353..afcd364cce 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java @@ -115,7 +115,7 @@ class PaginatedResultsRetrievedDiscoverabilityListener implements ApplicationLis protected void plural(final UriComponentsBuilder uriBuilder, final Class clazz) { final String resourceName = clazz.getSimpleName() .toLowerCase() + "s"; - uriBuilder.path("/auth/" + resourceName); + uriBuilder.path("/" + resourceName); } } diff --git a/spring-boot-rest/src/main/resources/application.properties b/spring-boot-rest/src/main/resources/application.properties index a0179f1e4b..176deb4f49 100644 --- a/spring-boot-rest/src/main/resources/application.properties +++ b/spring-boot-rest/src/main/resources/application.properties @@ -1,6 +1,5 @@ -server.port=8082 server.servlet.context-path=/spring-boot-rest ### Spring Boot default error handling configurations #server.error.whitelabel.enabled=false -#server.error.include-stacktrace=always \ No newline at end of file +#server.error.include-stacktrace=always diff --git a/spring-boot-rest/src/test/java/com/baeldung/Consts.java b/spring-boot-rest/src/test/java/com/baeldung/Consts.java index e33efd589e..4850a1b36a 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/Consts.java +++ b/spring-boot-rest/src/test/java/com/baeldung/Consts.java @@ -1,5 +1,5 @@ package com.baeldung; public interface Consts { - int APPLICATION_PORT = 8082; + int APPLICATION_PORT = 8080; } diff --git a/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractLiveTest.java b/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractLiveTest.java index d26632bc38..18f612d398 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractLiveTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/common/web/AbstractLiveTest.java @@ -59,7 +59,7 @@ public abstract class AbstractLiveTest { // protected String getURL() { - return "http://localhost:" + APPLICATION_PORT + "/spring-boot-rest/auth/foos"; + return "http://localhost:" + APPLICATION_PORT + "/spring-boot-rest/foos"; } } diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java index bd5b5eb58e..3300b91fde 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java @@ -27,7 +27,7 @@ public class FooControllerAppIntegrationTest { @Test public void whenFindPaginatedRequest_thenEmptyResponse() throws Exception { - this.mockMvc.perform(get("/auth/foos").param("page", "0") + this.mockMvc.perform(get("/foos").param("page", "0") .param("size", "2")) .andExpect(status().isOk()) .andExpect(content().json("[]")); diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerCustomEtagIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerCustomEtagIntegrationTest.java index dc48c21b30..9e7b60ed8c 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerCustomEtagIntegrationTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerCustomEtagIntegrationTest.java @@ -29,7 +29,7 @@ public class FooControllerCustomEtagIntegrationTest { @Autowired private MockMvc mvc; - private String FOOS_ENDPOINT = "/auth/foos/"; + private String FOOS_ENDPOINT = "/foos/"; private String CUSTOM_ETAG_ENDPOINT_SUFFIX = "/custom-etag"; private static String serializeFoo(Foo foo) throws Exception { diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java index 7e41cf6393..bd98523b0a 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java @@ -51,7 +51,7 @@ public class FooControllerWebLayerIntegrationTest { doNothing().when(publisher) .publishEvent(any(PaginatedResultsRetrievedEvent.class)); - this.mockMvc.perform(get("/auth/foos").param("page", "0") + this.mockMvc.perform(get("/foos").param("page", "0") .param("size", "2")) .andExpect(status().isOk()) .andExpect(jsonPath("$",Matchers.hasSize(1))); diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooPageableLiveTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooPageableLiveTest.java index 359a62a4d8..6a365f3bd5 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/web/FooPageableLiveTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooPageableLiveTest.java @@ -74,7 +74,7 @@ public class FooPageableLiveTest extends AbstractBasicLiveTest { } protected String getPageableURL() { - return "http://localhost:" + APPLICATION_PORT + "/spring-boot-rest/auth/foos/pageable"; + return "http://localhost:" + APPLICATION_PORT + "/spring-boot-rest/foos/pageable"; } } diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/StudentControllerIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/StudentControllerIntegrationTest.java new file mode 100644 index 0000000000..54ac69ebeb --- /dev/null +++ b/spring-boot-rest/src/test/java/com/baeldung/web/StudentControllerIntegrationTest.java @@ -0,0 +1,76 @@ +package com.baeldung.web; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.server.MediaTypeNotSupportedStatusException; + +import com.baeldung.web.controller.students.Student; +import com.fasterxml.jackson.databind.ObjectMapper; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class StudentControllerIntegrationTest { + + private static final String STUDENTS_PATH = "/students/"; + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenReadAll_thenStatusIsOk() throws Exception { + this.mockMvc.perform(get(STUDENTS_PATH)) + .andExpect(status().isOk()); + } + + @Test + public void whenReadOne_thenStatusIsOk() throws Exception { + this.mockMvc.perform(get(STUDENTS_PATH + 1)) + .andExpect(status().isOk()); + } + + @Test + public void whenCreate_thenStatusIsCreated() throws Exception { + Student student = new Student(10, "Albert", "Einstein"); + this.mockMvc.perform(post(STUDENTS_PATH).content(asJsonString(student)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isCreated()); + } + + @Test + public void whenUpdate_thenStatusIsOk() throws Exception { + Student student = new Student(1, "Nikola", "Tesla"); + this.mockMvc.perform(put(STUDENTS_PATH + 1) + .content(asJsonString(student)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()); + } + + @Test + public void whenDelete_thenStatusIsNoContent() throws Exception { + this.mockMvc.perform(delete(STUDENTS_PATH + 3)) + .andExpect(status().isNoContent()); + } + + private String asJsonString(final Object obj) { + try { + return new ObjectMapper().writeValueAsString(obj); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/spring-boot-rest/src/test/resources/foo_API_test.postman_collection.json b/spring-boot-rest/src/test/resources/foo_API_test.postman_collection.json index 5a6230bd22..dc4acafab3 100644 --- a/spring-boot-rest/src/test/resources/foo_API_test.postman_collection.json +++ b/spring-boot-rest/src/test/resources/foo_API_test.postman_collection.json @@ -42,15 +42,14 @@ "raw": "{\n \"name\": \"Transformers\"\n}" }, "url": { - "raw": "http://localhost:8082/spring-boot-rest/auth/foos", + "raw": "http://localhost:8080/spring-boot-rest/foos", "protocol": "http", "host": [ "localhost" ], - "port": "8082", + "port": "8080", "path": [ "spring-boot-rest", - "auth", "foos" ] } @@ -85,15 +84,14 @@ "raw": "" }, "url": { - "raw": "http://localhost:8082/spring-boot-rest/auth/foos/{{id}}", + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", "protocol": "http", "host": [ "localhost" ], - "port": "8082", + "port": "8080", "path": [ "spring-boot-rest", - "auth", "foos", "{{id}}" ] @@ -123,15 +121,14 @@ "raw": "" }, "url": { - "raw": "http://localhost:8082/spring-boot-rest/auth/foos/{{id}}", + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", "protocol": "http", "host": [ "localhost" ], - "port": "8082", + "port": "8080", "path": [ "spring-boot-rest", - "auth", "foos", "{{id}}" ] @@ -164,15 +161,14 @@ "raw": "" }, "url": { - "raw": "http://localhost:8082/spring-boot-rest/auth/foos/{{id}}", + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", "protocol": "http", "host": [ "localhost" ], - "port": "8082", + "port": "8080", "path": [ "spring-boot-rest", - "auth", "foos", "{{id}}" ] diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index aaa0fbf4c7..79a77775de 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -22,6 +22,12 @@ org.springframework.security.oauth spring-security-oauth2 + 2.3.3.RELEASE + + + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure + 2.1.2.RELEASE org.springframework.boot @@ -55,6 +61,12 @@ spring-security-test test + + org.springframework.boot + spring-boot-autoconfigure + 2.1.1.RELEASE + + diff --git a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java index 32a48ce612..16ce8e6fc6 100644 --- a/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java +++ b/spring-boot-security/src/main/java/com/baeldung/integrationtesting/WebSecurityConfigurer.java @@ -12,7 +12,7 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("spring") - .password("secret") + .password("{noop}secret") .roles("USER"); } diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java index 2ecad4ae35..7007c15596 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java @@ -2,14 +2,13 @@ package com.baeldung.springbootsecurity.basic_auth; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; @SpringBootApplication(exclude = { SecurityAutoConfiguration.class // ,ManagementWebSecurityAutoConfiguration.class }, scanBasePackages = "com.baeldung.springbootsecurity.basic_auth") public class SpringBootSecurityApplication { - public static void main(String[] args) { SpringApplication.run(SpringBootSecurityApplication.class, args); } diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java index 993c573fb0..592ef5354d 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java @@ -5,6 +5,8 @@ import org.springframework.security.config.annotation.authentication.builders.Au import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity @@ -12,14 +14,15 @@ public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth + PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); + auth .inMemoryAuthentication() .withUser("user") - .password("password") + .password(encoder.encode("password")) .roles("USER") .and() .withUser("admin") - .password("admin") + .password(encoder.encode("admin")) .roles("USER", "ADMIN"); } diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java index b403feb5c1..4686100638 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/AuthorizationServerConfig.java @@ -25,13 +25,13 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap clients .inMemory() .withClient("baeldung") - .secret("baeldung") + .secret("{noop}baeldung") .authorizedGrantTypes("client_credentials", "password", "authorization_code") .scopes("openid", "read") .autoApprove(true) .and() .withClient("baeldung-admin") - .secret("baeldung") + .secret("{noop}baeldung") .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token") .scopes("read", "write") .autoApprove(true); diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/WebSecurityConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/WebSecurityConfiguration.java new file mode 100644 index 0000000000..f2540c01b8 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2server/config/WebSecurityConfiguration.java @@ -0,0 +1,15 @@ +package com.baeldung.springbootsecurity.oauth2server.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Bean + public AuthenticationManager customAuthenticationManager() throws Exception { + return authenticationManager(); + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2sso/SpringBootOAuth2SsoApplication.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2sso/SpringBootOAuth2SsoApplication.java index b1cd580f08..342c246e66 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2sso/SpringBootOAuth2SsoApplication.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/oauth2sso/SpringBootOAuth2SsoApplication.java @@ -1,6 +1,7 @@ package com.baeldung.springbootsecurity.oauth2sso; import org.springframework.boot.autoconfigure.SpringBootApplication; + import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.boot.builder.SpringApplicationBuilder; diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java index 665dd0bce9..59ae2885ad 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java @@ -14,7 +14,7 @@ public class SpringBootSecurityTagLibsConfig extends WebSecurityConfigurerAdapte protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("testUser") - .password("password") + .password("{noop}password") .roles("ADMIN"); } diff --git a/spring-boot-security/src/main/resources/application-authz.properties b/spring-boot-security/src/main/resources/application-authz.properties index d29b0cdd3c..0c53999bb3 100644 --- a/spring-boot-security/src/main/resources/application-authz.properties +++ b/spring-boot-security/src/main/resources/application-authz.properties @@ -1,3 +1,3 @@ -security.user.password=password +spring.security.user.password=password security.oauth2.client.client-id=client security.oauth2.client.client-secret=secret diff --git a/spring-boot-security/src/main/resources/application-taglibs.properties b/spring-boot-security/src/main/resources/application-taglibs.properties index 218868405f..3e482ed92a 100644 --- a/spring-boot-security/src/main/resources/application-taglibs.properties +++ b/spring-boot-security/src/main/resources/application-taglibs.properties @@ -1,3 +1,3 @@ #jsp config -spring.mvc.view.prefix: /WEB-INF/views/ -spring.mvc.view.suffix: .jsp +spring.mvc.view.prefix= /WEB-INF/views/ +spring.mvc.view.suffix= .jsp diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java index 32c3fbdef4..dd9c511361 100644 --- a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java +++ b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java @@ -1,10 +1,10 @@ package com.baeldung.springbootsecurity.basic_auth; -import com.baeldung.springbootsecurity.basic_auth.SpringBootSecurityApplication; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; @@ -18,7 +18,6 @@ import java.net.URL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootSecurityApplication.class) public class BasicAuthConfigurationIntegrationTest { @@ -50,8 +49,6 @@ public class BasicAuthConfigurationIntegrationTest { ResponseEntity response = restTemplate.getForEntity(base.toString(), String.class); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); - assertTrue(response - .getBody() - .contains("Unauthorized")); + Assert.assertNull(response.getBody()); } } diff --git a/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java similarity index 98% rename from spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerIntegrationTest.java rename to spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java index 654e7925b9..0585c06a59 100644 --- a/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerIntegrationTest.java +++ b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class) -public class HomeControllerIntegrationTest { +public class HomeControllerUnitTest { @Autowired private TestRestTemplate restTemplate; diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 28123687fd..7d270c9c25 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -28,7 +28,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Boot Exit Codes](http://www.baeldung.com/spring-boot-exit-codes) - [Guide to the Favicon in Spring Boot](http://www.baeldung.com/spring-boot-favicon) - [Spring Shutdown Callbacks](http://www.baeldung.com/spring-shutdown-callbacks) -- [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb) - [Container Configuration in Spring Boot 2](http://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) - [Introduction to Chaos Monkey](https://www.baeldung.com/spring-boot-chaos-monkey) - [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) @@ -36,3 +35,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report) - [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information) - [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) +- [Entity To DTO Conversion for a Spring REST API](https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application) +- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 2e463e0189..ed2d8259df 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -15,16 +15,7 @@ - - - org.springframework.boot - spring-boot-starter-data-mongodb - - - de.flapdoodle.embed - de.flapdoodle.embed.mongo - test - + org.junit.jupiter diff --git a/spring-cloud-data-flow/apache-spark-job/pom.xml b/spring-cloud-data-flow/apache-spark-job/pom.xml new file mode 100644 index 0000000000..390b7ebdc6 --- /dev/null +++ b/spring-cloud-data-flow/apache-spark-job/pom.xml @@ -0,0 +1,36 @@ + + + + spring-cloud-data-flow + com.baeldung + 0.0.1-SNAPSHOT + + 4.0.0 + + apache-spark-job + + + org.springframework.cloud + spring-cloud-task-core + 2.0.0.RELEASE + + + org.apache.spark + spark-core_2.10 + 1.6.2 + + + log4j + log4j + + + org.slf4j + slf4j-log4j12 + + + + + + \ No newline at end of file diff --git a/spring-cloud-data-flow/apache-spark-job/src/main/java/com/baeldung/spring/cloud/PiApproximation.java b/spring-cloud-data-flow/apache-spark-job/src/main/java/com/baeldung/spring/cloud/PiApproximation.java new file mode 100644 index 0000000000..dfead21728 --- /dev/null +++ b/spring-cloud-data-flow/apache-spark-job/src/main/java/com/baeldung/spring/cloud/PiApproximation.java @@ -0,0 +1,39 @@ +package com.baeldung.spring.cloud; + +import org.apache.spark.SparkConf; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.api.java.function.Function; +import org.apache.spark.api.java.function.Function2; +import org.apache.spark.rdd.RDD; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class PiApproximation { + public static void main(String[] args) { + SparkConf conf = new SparkConf().setAppName("BaeldungPIApproximation"); + JavaSparkContext context = new JavaSparkContext(conf); + int slices = args.length >= 1 ? Integer.valueOf(args[0]) : 2; + int n = (100000L * slices) > Integer.MAX_VALUE ? Integer.MAX_VALUE : 100000 * slices; + + List xs = IntStream.rangeClosed(0, n) + .mapToObj(element -> Integer.valueOf(element)) + .collect(Collectors.toList()); + + JavaRDD dataSet = context.parallelize(xs, slices); + + JavaRDD pointsInsideTheCircle = dataSet.map(integer -> { + double x = Math.random() * 2 - 1; + double y = Math.random() * 2 - 1; + return (x*x + y*y ) < 1 ? 1: 0; + }); + + int count = pointsInsideTheCircle.reduce((integer, integer2) -> integer + integer2); + + System.out.println("The pi was estimated as:" + count / n); + + context.stop(); + } +} diff --git a/spring-cloud-data-flow/pom.xml b/spring-cloud-data-flow/pom.xml index daf8ebd2c8..36a780c28d 100644 --- a/spring-cloud-data-flow/pom.xml +++ b/spring-cloud-data-flow/pom.xml @@ -20,6 +20,7 @@ log-sink batch-job etl + apache-spark-job diff --git a/spring-cloud/README.md b/spring-cloud/README.md index fede3cc12d..5139cdca20 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -17,4 +17,5 @@ - [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) - [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles) - [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube) +- [Introduction to Spring Cloud OpenFeign](https://www.baeldung.com/spring-cloud-openfeign) diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index baf86a4386..bf70e0284c 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -32,6 +32,7 @@ spring-cloud-zuul-eureka-integration spring-cloud-contract spring-cloud-kubernetes + spring-cloud-kubernetes-2 spring-cloud-archaius spring-cloud-functions spring-cloud-vault diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/.gitignore b/spring-cloud/spring-cloud-kubernetes-2/client-service/.gitignore new file mode 100644 index 0000000000..2af7cefb0a --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/Dockerfile b/spring-cloud/spring-cloud-kubernetes-2/client-service/Dockerfile new file mode 100644 index 0000000000..bd8cf2918f --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/Dockerfile @@ -0,0 +1,5 @@ +FROM openjdk:8-jdk-alpine +VOLUME /tmp +COPY target/client-service-1.0-SNAPSHOT.jar app.jar +ENV JAVA_OPTS="" +ENTRYPOINT exec java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=9999 -jar /app.jar \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/client-config.yaml b/spring-cloud/spring-cloud-kubernetes-2/client-service/client-config.yaml new file mode 100644 index 0000000000..329c01582e --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/client-config.yaml @@ -0,0 +1,8 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: client-service +data: + application.properties: |- + bean.message=Testing reload ! Message from backend is: %s
Services : %s + diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/client-service-deployment.yaml b/spring-cloud/spring-cloud-kubernetes-2/client-service/client-service-deployment.yaml new file mode 100644 index 0000000000..8867aecc33 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/client-service-deployment.yaml @@ -0,0 +1,33 @@ +kind: Service +apiVersion: v1 +metadata: + name: client-service +spec: + selector: + app: client-service + ports: + - protocol: TCP + port: 8080 + nodePort: 30083 + type: NodePort +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: client-service +spec: + selector: + matchLabels: + app: client-service + replicas: 1 + template: + metadata: + labels: + app: client-service + spec: + containers: + - name: client-service + image: client-service:latest + imagePullPolicy: Never + ports: + - containerPort: 8080 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/pom.xml b/spring-cloud/spring-cloud-kubernetes-2/client-service/pom.xml new file mode 100644 index 0000000000..908a545242 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/pom.xml @@ -0,0 +1,96 @@ + + + 4.0.0 + client-service + client-service + 1.0-SNAPSHOT + + + com.baeldung.spring.cloud + spring-cloud-kubernetes-2 + 1.0-SNAPSHOT + + + + 1.8 + Finchley.SR2 + 1.0.0.RELEASE + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud-dependencies.version} + pom + import + + + org.springframework.cloud + spring-cloud-kubernetes-dependencies + ${spring.cloud.k8s.version} + pom + import + + + + + + + org.springframework.cloud + spring-cloud-kubernetes-discovery + + + org.springframework.cloud + spring-cloud-starter-kubernetes-config + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.cloud + spring-cloud-starter-netflix-hystrix + + + org.springframework.cloud + spring-cloud-starter-kubernetes-ribbon + + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.spring.cloud.kubernetes.client.Application + JAR + + + + + repackage + + + + + + + + diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/Application.java b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/Application.java new file mode 100644 index 0000000000..24e562c79b --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/Application.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.cloud.kubernetes.client; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.cloud.netflix.ribbon.RibbonClient; +import org.springframework.context.annotation.Bean; +import org.springframework.web.client.RestTemplate; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; + +@SpringBootApplication +@EnableDiscoveryClient +@EnableCircuitBreaker +@RibbonClient(name = "travel-agency-service", configuration = RibbonConfiguration.class) +public class Application { + + @LoadBalanced + @Bean + RestTemplate restTemplate() { + return new RestTemplate(); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/ClientConfig.java b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/ClientConfig.java new file mode 100644 index 0000000000..4bc8fbe327 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/ClientConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.cloud.kubernetes.client; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "bean") +public class ClientConfig { + + private String message = "Message from backend is: %s
Services : %s"; + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/ClientController.java b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/ClientController.java new file mode 100755 index 0000000000..952bccc3a8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/ClientController.java @@ -0,0 +1,54 @@ +package com.baeldung.spring.cloud.kubernetes.client; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.http.ResponseEntity; +import org.springframework.util.CollectionUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +import java.net.UnknownHostException; +import java.util.List; + +@RestController +public class ClientController { + + @Autowired + private DiscoveryClient discoveryClient; + + @Autowired + private ClientConfig config; + + @Autowired + private TravelAgencyService travelAgencyService; + + @RequestMapping("/deals") + public String getDeals() { + return travelAgencyService.getDeals(); + } + + @GetMapping + public String load() { + + RestTemplate restTemplate = new RestTemplate(); + String resourceUrl = "http://travel-agency-service:8080"; + ResponseEntity response = restTemplate.getForEntity(resourceUrl, String.class); + + String serviceList = ""; + if (discoveryClient != null) { + List services = this.discoveryClient.getServices(); + + for (String service : services) { + + List instances = this.discoveryClient.getInstances(service); + + serviceList += ("[" + service + " : " + ((!CollectionUtils.isEmpty(instances)) ? instances.size() : 0) + " instances ]"); + } + } + + return String.format(config.getMessage(), response.getBody(), serviceList); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/RibbonConfiguration.java b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/RibbonConfiguration.java new file mode 100755 index 0000000000..2b81c78be4 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/RibbonConfiguration.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2016 to the original authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.baeldung.spring.cloud.kubernetes.client; + +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.AvailabilityFilteringRule; +import com.netflix.loadbalancer.IPing; +import com.netflix.loadbalancer.IRule; +import com.netflix.loadbalancer.PingUrl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; + +public class RibbonConfiguration { + + @Autowired + IClientConfig ribbonClientConfig; + + /** + * PingUrl will ping a URL to check the status of each server. + * Say Hello has, as you’ll recall, a method mapped to the /path; that means that Ribbon will get an HTTP 200 response when it pings a running Backend Server + * + * @param config Client configuration + * @return The URL to be used for the Ping + */ + @Bean + public IPing ribbonPing(IClientConfig config) { + return new PingUrl(); + } + + /** + * AvailabilityFilteringRule will use Ribbon’s built-in circuit breaker functionality to filter out any servers in an “open-circuit” state: + * if a ping fails to connect to a given server, or if it gets a read failure for the server, Ribbon will consider that server “dead” until it begins to respond normally. + * + * @param config Client configuration + * @return The Load Balancer rule + */ + @Bean + public IRule ribbonRule(IClientConfig config) { + return new AvailabilityFilteringRule(); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/TravelAgencyService.java b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/TravelAgencyService.java new file mode 100644 index 0000000000..5ce6d7b8a1 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/java/com/baeldung/spring/cloud/kubernetes/client/TravelAgencyService.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.cloud.kubernetes.client; + +import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; +import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +@Service +public class TravelAgencyService { + + private final RestTemplate restTemplate; + + public TravelAgencyService(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + } + + @HystrixCommand(fallbackMethod = "getFallbackName", commandProperties = { + @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") }) + public String getDeals() { + return this.restTemplate.getForObject("http://travel-agency-service:8080/deals", String.class); + } + + private String getFallbackName() { + return "Fallback"; + } +} diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/resources/application.yaml b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/resources/application.yaml new file mode 100644 index 0000000000..f966fdd7a5 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/resources/application.yaml @@ -0,0 +1,16 @@ +spring: + application.name: client-service + cloud.kubernetes.reload.enabled: true +server.port: 8080 +management: + endpoint: + restart: + enabled: true + health: + enabled: true + info: + enabled: true +ribbon: + http: + client: + enabled: true \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes-2/client-service/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a6a978a354 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/client-service/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.kubernetes.client.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-cloud/spring-cloud-kubernetes-2/deployment-all.sh b/spring-cloud/spring-cloud-kubernetes-2/deployment-all.sh new file mode 100755 index 0000000000..9c088b7422 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/deployment-all.sh @@ -0,0 +1,34 @@ +### build the repository +mvn clean install + +### set docker env +eval $(minikube docker-env) + +### build the docker images on minikube +cd travel-agency-service +docker build -t travel-agency-service . +cd ../client-service +docker build -t client-service . +cd .. + +### secret and mongodb +kubectl delete -f secret.yaml +kubectl delete -f mongo-deployment.yaml + +kubectl create -f secret.yaml +kubectl create -f mongo-deployment.yaml + +### travel-agency-service +kubectl delete -f travel-agency-service/travel-agency-deployment.yaml +kubectl create -f travel-agency-service/travel-agency-deployment.yaml + + +### client-service +kubectl delete configmap client-service +kubectl delete -f client-service/client-service-deployment.yaml + +kubectl create -f client-service/client-config.yaml +kubectl create -f client-service/client-service-deployment.yaml + +# Check that the pods are running +kubectl get pods \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes-2/mongo-deployment.yaml b/spring-cloud/spring-cloud-kubernetes-2/mongo-deployment.yaml new file mode 100644 index 0000000000..3d40581578 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/mongo-deployment.yaml @@ -0,0 +1,45 @@ +apiVersion: v1 +kind: Service +metadata: + labels: + app: mongo + name: mongodb-service +spec: + type: NodePort + ports: + - name: "http" + port: 27017 + protocol: TCP + targetPort: 27017 + selector: + service: mongo +--- +apiVersion: extensions/v1beta1 +kind: Deployment +metadata: + name: mongo +spec: + replicas: 1 + template: + metadata: + labels: + service: mongo + name: mongodb-service + spec: + containers: + - args: + - mongod + - --smallfiles + image: mongo:latest + name: mongo + env: + - name: MONGO_INITDB_ROOT_USERNAME + valueFrom: + secretKeyRef: + name: db-secret + key: username + - name: MONGO_INITDB_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: db-secret + key: password diff --git a/spring-cloud/spring-cloud-kubernetes-2/pom.xml b/spring-cloud/spring-cloud-kubernetes-2/pom.xml new file mode 100644 index 0000000000..d501e8102f --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + com.baeldung.spring.cloud + spring-cloud-kubernetes-2 + 1.0-SNAPSHOT + spring-cloud-kubernetes-2 + pom + + + 2.0.6.RELEASE + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + client-service + travel-agency-service + + + diff --git a/spring-cloud/spring-cloud-kubernetes-2/secret.yaml b/spring-cloud/spring-cloud-kubernetes-2/secret.yaml new file mode 100644 index 0000000000..a813c35be7 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/secret.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Secret +metadata: + name: db-secret +data: + username: dXNlcg== + password: cDQ1NXcwcmQ= diff --git a/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/Dockerfile b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/Dockerfile new file mode 100755 index 0000000000..30b66d5eff --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/Dockerfile @@ -0,0 +1,5 @@ +FROM openjdk:8-jdk-alpine +VOLUME /tmp +COPY target/travel-agency-service-1.0-SNAPSHOT.jar app.jar +ENV JAVA_OPTS="" +ENTRYPOINT exec java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=9999 -jar /app.jar \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/pom.xml b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/pom.xml new file mode 100755 index 0000000000..a375264533 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + travel-agency-service + 1.0-SNAPSHOT + + + com.baeldung.spring.cloud + spring-cloud-kubernetes-2 + 1.0-SNAPSHOT + + + + 1.8 + Finchley.SR2 + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud-dependencies.version} + pom + import + + + ch.qos.logback + logback-classic + 1.2.3 + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-actuator + + + org.springframework.boot + spring-boot-actuator-autoconfigure + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.spring.cloud.kubernetes.travelagency.Application + JAR + + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/Application.java b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/Application.java new file mode 100755 index 0000000000..bfc7356176 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/Application.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.cloud.kubernetes.travelagency; + +import com.baeldung.spring.cloud.kubernetes.travelagency.controller.TravelAgencyController; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application implements CommandLineRunner { + + private static final Log log = LogFactory.getLog(TravelAgencyController.class); + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + public void run(String... args) throws Exception { + log.info("Travel Agency Started! "); + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/controller/TravelAgencyController.java b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/controller/TravelAgencyController.java new file mode 100644 index 0000000000..42f001616a --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/controller/TravelAgencyController.java @@ -0,0 +1,55 @@ +package com.baeldung.spring.cloud.kubernetes.travelagency.controller; + +import com.baeldung.spring.cloud.kubernetes.travelagency.model.TravelDeal; +import com.baeldung.spring.cloud.kubernetes.travelagency.repository.TravelDealRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.List; +import java.util.Random; +import static org.springframework.web.bind.annotation.RequestMethod.GET; + +@RestController +public class TravelAgencyController { + + @Autowired + private TravelDealRepository travelDealRepository; + + private static final Log log = LogFactory.getLog(TravelAgencyController.class); + + @RequestMapping(method = GET, path = "/deals") + public String deals() { + log.info("Client is requesting new deals!"); + + List travelDealList = travelDealRepository.findAll(); + if (!travelDealList.isEmpty()) { + int randomDeal = new Random().nextInt(travelDealList.size()); + return travelDealList.get(randomDeal) + .toString(); + } else { + return "NO DEALS"; + } + } + + @RequestMapping(method = GET, path = "/") + @ResponseBody + public String get() throws UnknownHostException { + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("Host: ") + .append(InetAddress.getLocalHost() + .getHostName()) + .append("
"); + stringBuilder.append("IP: ") + .append(InetAddress.getLocalHost() + .getHostAddress()) + .append("
"); + stringBuilder.append("Type: ") + .append("Travel Agency") + .append("
"); + return stringBuilder.toString(); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/model/TravelDeal.java b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/model/TravelDeal.java new file mode 100644 index 0000000000..2cd2bf2d45 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/model/TravelDeal.java @@ -0,0 +1,92 @@ +package com.baeldung.spring.cloud.kubernetes.travelagency.model; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; + +import java.math.BigInteger; +import java.util.Date; + +@Document(collection = "travel_deal") +public class TravelDeal { + + @Id + private BigInteger id; + + private String destination; + + private String description; + + @Field("deal_price") + private double dealPrice; + + @Field("old_price") + private double oldPrice; + + @Field("departure_date") + private Date departureDate; + + @Field("arrival_date") + private Date arrivalDate; + + public BigInteger getId() { + return id; + } + + public void setId(BigInteger id) { + this.id = id; + } + + public String getDestination() { + return destination; + } + + public void setDestination(String destination) { + this.destination = destination; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public double getDealPrice() { + return dealPrice; + } + + public void setDealPrice(double dealPrice) { + this.dealPrice = dealPrice; + } + + public double getOldPrice() { + return oldPrice; + } + + public void setOldPrice(double oldPrice) { + this.oldPrice = oldPrice; + } + + public Date getDepartureDate() { + return departureDate; + } + + public void setDepartureDate(Date departureDate) { + this.departureDate = departureDate; + } + + public Date getArrivalDate() { + return arrivalDate; + } + + public void setArrivalDate(Date arrivalDate) { + this.arrivalDate = arrivalDate; + } + + @Override + public String toString() { + return "TravelDeal{" + "id=" + id + ", destination='" + destination + '\'' + ", description='" + description + '\'' + ", dealPrice=" + dealPrice + ", oldPrice=" + oldPrice + ", departureDate=" + departureDate + ", arrivalDate=" + arrivalDate + '}'; + } +} diff --git a/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/repository/TravelDealRepository.java b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/repository/TravelDealRepository.java new file mode 100644 index 0000000000..20c1e3b67a --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/java/com/baeldung/spring/cloud/kubernetes/travelagency/repository/TravelDealRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.cloud.kubernetes.travelagency.repository; + +import java.util.List; + +import com.baeldung.spring.cloud.kubernetes.travelagency.model.TravelDeal; +import org.springframework.data.mongodb.repository.MongoRepository; + +public interface TravelDealRepository extends MongoRepository { + + public List findByDestination(String destination); + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/resources/application.properties b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/resources/application.properties new file mode 100644 index 0000000000..ffe78f0917 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/resources/application.properties @@ -0,0 +1,14 @@ +spring.application.name=travel-agency-service +server.port=8080 +spring.cloud.kubernetes.reload.enabled=true +spring.cloud.kubernetes.secrets.name=db-secret +spring.data.mongodb.host=mongodb-service +spring.data.mongodb.port=27017 +spring.data.mongodb.database=admin +spring.data.mongodb.username=${MONGO_USERNAME} +spring.data.mongodb.password=${MONGO_PASSWORD} +management.endpoint.health.enabled=true +management.endpoint.info.enabled=true +management.endpoint.restart.enabled=true +com.baeldung.spring.cloud.kubernetes.services=debug + diff --git a/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/resources/logback-spring.xml b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/resources/logback-spring.xml new file mode 100644 index 0000000000..49aeda8f9f --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/resources/logback-spring.xml @@ -0,0 +1,17 @@ + + + + + + logstash:5000 + + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/resources/logback.xml new file mode 100644 index 0000000000..37492be5bf --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + diff --git a/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/travel-agency-config.yaml b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/travel-agency-config.yaml new file mode 100644 index 0000000000..93a67e3777 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/travel-agency-config.yaml @@ -0,0 +1,8 @@ +apiVersion: v1 +kind: Secret +metadata: + name: travel-agency-service +data: + application.properties: |- + bean.message=Testing reload ! Message from backend is: %s
Services : %s + diff --git a/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/travel-agency-deployment.yaml b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/travel-agency-deployment.yaml new file mode 100644 index 0000000000..a41f13bf61 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes-2/travel-agency-service/travel-agency-deployment.yaml @@ -0,0 +1,44 @@ +kind: Service +apiVersion: v1 +metadata: + name: travel-agency-service +spec: + selector: + app: travel-agency-service + ports: + - protocol: TCP + port: 8080 + nodePort: 30081 + type: NodePort +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: travel-agency-service +spec: + selector: + matchLabels: + app: travel-agency-service + replicas: 2 + template: + metadata: + labels: + app: travel-agency-service + spec: + containers: + - name: travel-agency-service + image: travel-agency-service:latest + imagePullPolicy: Never + ports: + - containerPort: 8080 + env: + - name: MONGO_USERNAME + valueFrom: + secretKeyRef: + name: db-secret + key: username + - name: MONGO_PASSWORD + valueFrom: + secretKeyRef: + name: db-secret + key: password \ No newline at end of file diff --git a/spring-core/README.md b/spring-core/README.md index dcc15a4cb9..d542fa8ed1 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -23,3 +23,4 @@ - [Unsatisfied Dependency in Spring](https://www.baeldung.com/spring-unsatisfied-dependency) - [What is a Spring Bean?](https://www.baeldung.com/spring-bean) - [Spring PostConstruct and PreDestroy Annotations](https://www.baeldung.com/spring-postconstruct-predestroy) +- [Guice vs Spring – Dependency Injection](https://www.baeldung.com/guice-spring-dependency-injection) diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml index 772d6f2553..e563a6a3b5 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - com.baeldung spring-data-rest + 1.0 spring-data-rest jar @@ -40,11 +40,7 @@ org.xerial sqlite-jdbc - ${sqlite.version} -
@@ -53,8 +49,6 @@ com.baeldung.SpringDataRestApplication - 3.25.2 - 2.1.0.RELEASE diff --git a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java b/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java index ad219ccd53..274ae3bc1d 100644 --- a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java @@ -37,7 +37,7 @@ public class SpringDataProjectionLiveTest { @Before public void setup() { - if (bookRepo.findById(1L) == null) { + if (!bookRepo.findById(1L).isPresent()) { Book book = new Book("Animal Farm"); book.setIsbn("978-1943138425"); book = bookRepo.save(book); diff --git a/spring-ehcache/README.md b/spring-ehcache/README.md index 749441375e..ecf96cd7c7 100644 --- a/spring-ehcache/README.md +++ b/spring-ehcache/README.md @@ -3,5 +3,5 @@ A simple example of using ehcache with spring-boot. ### Relevant Articles: -- [Spring Boot Ehcache Example](http://www.baeldung.com/spring-ehcache) +- [Spring Boot Ehcache Example](https://www.baeldung.com/spring-boot-ehcache) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 851a3689ab..497b0f4c1f 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -29,6 +29,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) -- [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 8c2661cc27..b9ed3a3e81 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -17,7 +17,7 @@ org.springframework spring-oxm - ${spring-oxm.version} + ${spring.version} com.sun.mail @@ -181,7 +181,6 @@ 1.4.9 5.1.0 20180130 - 5.0.2.RELEASE 3.0.8 diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index ed6df1675f..e0d3a70626 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -12,7 +12,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Project Configuration with Spring](http://www.baeldung.com/project-configuration-with-spring) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) -- [Bootstrap a Web Application with Spring 5](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) - [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) diff --git a/spring-rest-simple/README.md b/spring-rest-simple/README.md index 179e556202..882d0ac301 100644 --- a/spring-rest-simple/README.md +++ b/spring-rest-simple/README.md @@ -3,6 +3,5 @@ - [Guide to UriComponentsBuilder in Spring](http://www.baeldung.com/spring-uricomponentsbuilder) - [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code) - [Spring RequestMapping](http://www.baeldung.com/spring-requestmapping) -- [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring) - [Spring and Apache FileUpload](http://www.baeldung.com/spring-apache-file-upload) - [Test a REST API with curl](http://www.baeldung.com/curl-rest) diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java index e8cb218258..c68d586667 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java @@ -2,12 +2,21 @@ package org.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import java.util.List; + import org.baeldung.web.dto.Foo; import org.baeldung.web.dto.FooProtos; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +import com.google.common.collect.Lists; @Controller public class FooController { @@ -16,6 +25,12 @@ public class FooController { super(); } + @RequestMapping(method = RequestMethod.GET, value = "/foos") + @ResponseBody + public List findListOfFoo() { + return Lists.newArrayList(new Foo(1, randomAlphabetic(4))); + } + // API - read @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @@ -32,6 +47,27 @@ public class FooController { public Foo updateFoo(@PathVariable("id") final String id, @RequestBody final Foo foo) { return foo; } + + @RequestMapping(method = RequestMethod.PATCH, value = "/foos/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo patchFoo(@PathVariable("id") final String id, @RequestBody final Foo foo) { + return foo; + } + + @RequestMapping(method = RequestMethod.POST, value = "/foos") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo postFoo(@RequestBody final Foo foo) { + return foo; + } + + @RequestMapping(method = RequestMethod.HEAD, value = "/foos") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo headFoo() { + return new Foo(1, randomAlphabetic(4)); + } @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}", produces = { "application/x-protobuf" }) @ResponseBody diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java new file mode 100644 index 0000000000..e213d0255f --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java @@ -0,0 +1,269 @@ +package org.baeldung.web.test; + +import static org.apache.commons.codec.binary.Base64.encodeBase64; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URI; +import java.util.Arrays; +import java.util.Set; + +import org.baeldung.web.dto.Foo; +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RequestCallback; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import com.google.common.base.Charsets; + +public class RestTemplateBasicLiveTest { + + private RestTemplate restTemplate; + private static final String fooResourceUrl = "http://localhost:8082/spring-rest/foos"; + + @Before + public void beforeTest() { + restTemplate = new RestTemplate(); + // restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); + } + + // GET + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { + final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class); + + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException { + final RestTemplate template = new RestTemplate(); + final ResponseEntity response = template.getForEntity(fooResourceUrl + "/1", String.class); + + final ObjectMapper mapper = new XmlMapper(); + final JsonNode root = mapper.readTree(response.getBody()); + final JsonNode name = root.path("name"); + assertThat(name.asText(), notNullValue()); + } + + @Test + public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException { + final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); + + assertThat(foo.getName(), notNullValue()); + assertThat(foo.getId(), is(1L)); + } + + // HEAD, OPTIONS + + @Test + public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { + final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); + assertTrue(httpHeaders.getContentType() + .includes(MediaType.APPLICATION_JSON)); + } + + // POST + + @Test + public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() { + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class); + assertThat(foo, notNullValue()); + assertThat(foo.getName(), is("bar")); + } + + @Test + public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() { + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final URI location = restTemplate.postForLocation(fooResourceUrl, request); + assertThat(location, notNullValue()); + } + + @Test + public void givenFooService_whenPostResource_thenResourceIsCreated() { + final Foo foo = new Foo("bar"); + final ResponseEntity response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); + + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + final Foo fooResponse = response.getBody(); + assertThat(fooResponse, notNullValue()); + assertThat(fooResponse.getName(), is("bar")); + } + + @Test + public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { + final Set optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl); + final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD }; + + assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); + } + + // PUT + + @Test + public void givenFooService_whenPutExistingEntity_thenItIsUpdated() { + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create Resource + final ResponseEntity createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + + // Update Resource + final Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(createResponse.getBody() + .getId()); + final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody() + .getId(); + final HttpEntity requestUpdate = new HttpEntity<>(updatedInstance, headers); + restTemplate.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class); + + // Check that Resource was updated + final ResponseEntity updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = updateResponse.getBody(); + assertThat(foo.getName(), is(updatedInstance.getName())); + } + + @Test + public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() { + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create entity + ResponseEntity response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + + // Update entity + final Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(response.getBody() + .getId()); + final String resourceUrl = fooResourceUrl + '/' + response.getBody() + .getId(); + restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); + + // Check that entity was updated + response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = response.getBody(); + assertThat(foo.getName(), is(updatedInstance.getName())); + } + + // PATCH + + @Test + public void givenFooService_whenPatchExistingEntity_thenItIsUpdated() { + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create Resource + final ResponseEntity createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + + // Update Resource + final Foo updatedResource = new Foo("newName"); + updatedResource.setId(createResponse.getBody() + .getId()); + final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody() + .getId(); + final HttpEntity requestUpdate = new HttpEntity<>(updatedResource, headers); + final ClientHttpRequestFactory requestFactory = getSimpleClientHttpRequestFactory(); + final RestTemplate template = new RestTemplate(requestFactory); + template.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); + template.patchForObject(resourceUrl, requestUpdate, Void.class); + + // Check that Resource was updated + final ResponseEntity updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = updateResponse.getBody(); + assertThat(foo.getName(), is(updatedResource.getName())); + } + + // DELETE + + @Test + public void givenFooService_whenCallDelete_thenEntityIsRemoved() { + final Foo foo = new Foo("remove me"); + final ResponseEntity response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + + final String entityUrl = fooResourceUrl + "/" + response.getBody() + .getId(); + restTemplate.delete(entityUrl); + try { + restTemplate.getForEntity(entityUrl, Foo.class); + fail(); + } catch (final HttpClientErrorException ex) { + assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND)); + } + } + + @Test + public void givenFooService_whenFormSubmit_thenResourceIsCreated() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + MultiValueMap map= new LinkedMultiValueMap<>(); + map.add("id", "1"); + + HttpEntity> request = new HttpEntity<>(map, headers); + + ResponseEntity response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class); + + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + final String fooResponse = response.getBody(); + assertThat(fooResponse, notNullValue()); + assertThat(fooResponse, is("1")); + } + + private HttpHeaders prepareBasicAuthHeaders() { + final HttpHeaders headers = new HttpHeaders(); + final String encodedLogPass = getBase64EncodedLogPass(); + headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass); + return headers; + } + + private String getBase64EncodedLogPass() { + final String logPass = "user1:user1Pass"; + final byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII)); + return new String(authHeaderBytes, Charsets.US_ASCII); + } + + private RequestCallback requestCallback(final Foo updatedInstance) { + return clientHttpRequest -> { + final ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(clientHttpRequest.getBody(), updatedInstance); + clientHttpRequest.getHeaders() + .add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + clientHttpRequest.getHeaders() + .add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass()); + }; + } + + // Simply setting restTemplate timeout using ClientHttpRequestFactory + + ClientHttpRequestFactory getSimpleClientHttpRequestFactory() { + final int timeout = 5; + final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); + clientHttpRequestFactory.setConnectTimeout(timeout * 1000); + return clientHttpRequestFactory; + } + +} diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java new file mode 100644 index 0000000000..b920ed38da --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java @@ -0,0 +1,122 @@ +package org.baeldung.web.test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import okhttp3.Request; +import okhttp3.RequestBody; + +public class TestRestTemplateBasicLiveTest { + + private RestTemplate restTemplate; + + private static final String FOO_RESOURCE_URL = "http://localhost:" + 8082 + "/spring-rest/foos"; + private static final String URL_SECURED_BY_AUTHENTICATION = "http://httpbin.org/basic-auth/user/passwd"; + private static final String BASE_URL = "http://localhost:" + 8082 + "/spring-rest"; + + @Before + public void beforeTest() { + restTemplate = new RestTemplate(); + } + + // GET + @Test + public void givenTestRestTemplate_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() { + RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); + restTemplateBuilder.configure(restTemplate); + TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenRestTemplateBuilderWrapper_whenSendGetForEntity_thenStatusOk() { + RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); + restTemplateBuilder.build(); + TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() { + RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); + restTemplateBuilder.configure(restTemplate); + TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder, "user", "passwd"); + ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, + String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenTestRestTemplateWithCredentials_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); + ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, + String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenTestRestTemplateWithBasicAuth_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + ResponseEntity response = testRestTemplate.withBasicAuth("user", "passwd"). + getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenTestRestTemplateWithCredentialsAndEnabledCookies_whenSendGetForEntity_thenStatusOk() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd", TestRestTemplate. + HttpClientOption.ENABLE_COOKIES); + ResponseEntity response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION, + String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + // HEAD + @Test + public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeaders() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + final HttpHeaders httpHeaders = testRestTemplate.headForHeaders(FOO_RESOURCE_URL); + assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); + } + + // POST + @Test + public void givenService_whenPostForObject_thenCreatedObjectIsReturned() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); + final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), + "{\"id\":1,\"name\":\"Jim\"}"); + final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); + testRestTemplate.postForObject(URL_SECURED_BY_AUTHENTICATION, request, String.class); + } + + // PUT + @Test + public void givenService_whenPutForObject_thenCreatedObjectIsReturned() { + TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); + final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"), + "{\"id\":1,\"name\":\"Jim\"}"); + final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); + testRestTemplate.put(URL_SECURED_BY_AUTHENTICATION, request, String.class); + } + +} diff --git a/spring-resttemplate/pom.xml b/spring-resttemplate/pom.xml index 9a0978f120..06d4eed9fc 100644 --- a/spring-resttemplate/pom.xml +++ b/spring-resttemplate/pom.xml @@ -25,6 +25,10 @@ org.springframework.boot spring-boot-devtools + + org.springframework.boot + spring-boot-starter-web + org.springframework.boot spring-boot-starter-test diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java similarity index 89% rename from spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java index 76fc346aca..9a361e92c9 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/RestTemplateConfigurationApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.configuration; +package org.baeldung.resttemplate; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java new file mode 100644 index 0000000000..a9d400b199 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/FooController.java @@ -0,0 +1,124 @@ +package org.baeldung.resttemplate.configuration; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +import java.net.URI; +import java.util.Collection; +import java.util.Map; + +import org.baeldung.resttemplate.web.dto.Foo; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; + +@Controller +public class FooController { + + private Map fooRepository = Maps.newHashMap(ImmutableMap.of(1L, new Foo(1L, randomAlphabetic(4)))); + + public FooController() { + super(); + } + + @RequestMapping(method = RequestMethod.GET, value = "/foos") + @ResponseBody + public Collection findListOfFoo() { + return fooRepository.values(); + } + + // API - read + + @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") + @ResponseBody + public Foo findById(@PathVariable final long id) throws HttpClientErrorException { + Foo foo = fooRepository.get(id); + + if (foo == null) { + throw new HttpClientErrorException(HttpStatus.NOT_FOUND); + } else { + return foo; + } + } + + // API - write + + @RequestMapping(method = RequestMethod.PUT, value = "/foos/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { + fooRepository.put(id, foo); + return foo; + } + + @RequestMapping(method = RequestMethod.PATCH, value = "/foos/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo patchFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { + fooRepository.put(id, foo); + return foo; + } + + @RequestMapping(method = RequestMethod.POST, value = "/foos") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public ResponseEntity postFoo(@RequestBody final Foo foo) { + + fooRepository.put(foo.getId(), foo); + final URI location = ServletUriComponentsBuilder + .fromCurrentServletMapping() + .path("/foos/{id}") + .build() + .expand(foo.getId()) + .toUri(); + + final HttpHeaders headers = new HttpHeaders(); + headers.setLocation(location); + + final ResponseEntity entity = new ResponseEntity(foo, headers, HttpStatus.CREATED); + return entity; + } + + @RequestMapping(method = RequestMethod.HEAD, value = "/foos") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo headFoo() { + return new Foo(1, randomAlphabetic(4)); + } + + @RequestMapping(method = RequestMethod.POST, value = "/foos/new") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo createFoo(@RequestBody final Foo foo) { + fooRepository.put(foo.getId(), foo); + return foo; + } + + @RequestMapping(method = RequestMethod.DELETE, value = "/foos/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public long deleteFoo(@PathVariable final long id) { + fooRepository.remove(id); + return id; + } + + @RequestMapping(method = RequestMethod.POST, value = "/foos/form") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public String submitFoo(@RequestParam("id") String id) { + return id; + } + +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java index 4e121185b1..966d5bcaa1 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java @@ -7,6 +7,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; +import org.springframework.web.client.RestTemplate; @Configuration @EnableAutoConfiguration @@ -25,4 +26,8 @@ public class SpringConfig { return new RestTemplateBuilder(customRestTemplateCustomizer()); } + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } } diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/dto/Foo.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java similarity index 93% rename from spring-resttemplate/src/main/java/org/baeldung/web/dto/Foo.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java index 240b368b50..ed0a42c429 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/web/dto/Foo.java +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/dto/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package org.baeldung.resttemplate.web.dto; import com.thoughtworks.xstream.annotations.XStreamAlias; diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/exception/NotFoundException.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java similarity index 55% rename from spring-resttemplate/src/main/java/org/baeldung/web/exception/NotFoundException.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java index 5b4d80a659..3e606e9314 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/web/exception/NotFoundException.java +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/exception/NotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.exception; +package org.baeldung.resttemplate.web.exception; public class NotFoundException extends RuntimeException { } diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java similarity index 82% rename from spring-resttemplate/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java index b1b87e89a5..214de38746 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/handler/RestTemplateResponseErrorHandler.java @@ -1,13 +1,14 @@ -package org.baeldung.web.handler; +package org.baeldung.resttemplate.web.handler; -import org.baeldung.web.exception.NotFoundException; +import java.io.IOException; + +import org.baeldung.resttemplate.web.exception.NotFoundException; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.ResponseErrorHandler; -import java.io.IOException; - @Component public class RestTemplateResponseErrorHandler implements ResponseErrorHandler { @@ -31,6 +32,7 @@ public class RestTemplateResponseErrorHandler .getStatusCode() .series() == HttpStatus.Series.SERVER_ERROR) { //Handle SERVER_ERROR + throw new HttpClientErrorException(httpResponse.getStatusCode()); } else if (httpResponse .getStatusCode() .series() == HttpStatus.Series.CLIENT_ERROR) { diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/model/Bar.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java similarity index 87% rename from spring-resttemplate/src/main/java/org/baeldung/web/model/Bar.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java index 474e2070a5..cf5279697f 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/web/model/Bar.java +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Bar.java @@ -1,4 +1,4 @@ -package org.baeldung.web.model; +package org.baeldung.resttemplate.web.model; public class Bar { private String id; diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/model/Employee.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Employee.java similarity index 95% rename from spring-resttemplate/src/main/java/org/baeldung/web/model/Employee.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Employee.java index 7cab4a0430..a9b84a77b4 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/web/model/Employee.java +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/model/Employee.java @@ -1,4 +1,4 @@ -package org.baeldung.web.model; +package org.baeldung.resttemplate.web.model; import java.util.Date; import java.util.Objects; diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java similarity index 78% rename from spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java index 0bf24bd480..54a66ea591 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/BarConsumerService.java @@ -1,7 +1,7 @@ -package org.baeldung.web.service; +package org.baeldung.resttemplate.web.service; -import org.baeldung.web.handler.RestTemplateResponseErrorHandler; -import org.baeldung.web.model.Bar; +import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import org.baeldung.resttemplate.web.model.Bar; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Service; diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/service/EmployeeService.java b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java similarity index 89% rename from spring-resttemplate/src/main/java/org/baeldung/web/service/EmployeeService.java rename to spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java index 91614e90ad..c6562fbc94 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/web/service/EmployeeService.java +++ b/spring-resttemplate/src/main/java/org/baeldung/resttemplate/web/service/EmployeeService.java @@ -1,6 +1,6 @@ -package org.baeldung.web.service; +package org.baeldung.resttemplate.web.service; -import org.baeldung.web.model.Employee; +import org.baeldung.resttemplate.web.model.Employee; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-resttemplate/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 3a5a20cfeb..3c762b894b 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,6 +1,6 @@ package org.baeldung; -import org.baeldung.resttemplate.configuration.RestTemplateConfigurationApplication; +import org.baeldung.resttemplate.RestTemplateConfigurationApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java index 143aa079d5..a54c124d5f 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -14,7 +14,8 @@ import java.net.URI; import java.util.Arrays; import java.util.Set; -import org.baeldung.web.dto.Foo; +import org.baeldung.resttemplate.web.dto.Foo; +import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpEntity; @@ -34,6 +35,7 @@ import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.google.common.base.Charsets; public class RestTemplateBasicLiveTest { @@ -44,6 +46,7 @@ public class RestTemplateBasicLiveTest { @Before public void beforeTest() { restTemplate = new RestTemplate(); + restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler()); // restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); } @@ -61,7 +64,7 @@ public class RestTemplateBasicLiveTest { final RestTemplate template = new RestTemplate(); final ResponseEntity response = template.getForEntity(fooResourceUrl + "/1", String.class); - final ObjectMapper mapper = new ObjectMapper(); + final ObjectMapper mapper = new XmlMapper(); final JsonNode root = mapper.readTree(response.getBody()); final JsonNode name = root.path("name"); assertThat(name.asText(), notNullValue()); @@ -97,7 +100,7 @@ public class RestTemplateBasicLiveTest { @Test public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() { final HttpEntity request = new HttpEntity<>(new Foo("bar")); - final URI location = restTemplate.postForLocation(fooResourceUrl, request); + final URI location = restTemplate.postForLocation(fooResourceUrl, request, Foo.class); assertThat(location, notNullValue()); } @@ -211,7 +214,7 @@ public class RestTemplateBasicLiveTest { restTemplate.getForEntity(entityUrl, Foo.class); fail(); } catch (final HttpClientErrorException ex) { - assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND)); + assertThat(ex.getStatusCode(), is(HttpStatus.INTERNAL_SERVER_ERROR)); } } @@ -221,7 +224,7 @@ public class RestTemplateBasicLiveTest { headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap map= new LinkedMultiValueMap<>(); - map.add("id", "1"); + map.add("id", "10"); HttpEntity> request = new HttpEntity<>(map, headers); @@ -230,7 +233,7 @@ public class RestTemplateBasicLiveTest { assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); final String fooResponse = response.getBody(); assertThat(fooResponse, notNullValue()); - assertThat(fooResponse, is("1")); + assertThat(fooResponse, is("10")); } private HttpHeaders prepareBasicAuthHeaders() { diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java index e303c75a28..967c4a6188 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/client/TestRestTemplateBasicLiveTest.java @@ -4,6 +4,7 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; +import org.baeldung.resttemplate.web.dto.Foo; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.web.client.TestRestTemplate; @@ -34,7 +35,7 @@ public class TestRestTemplateBasicLiveTest { @Test public void givenTestRestTemplate_whenSendGetForEntity_thenStatusOk() { TestRestTemplate testRestTemplate = new TestRestTemplate(); - ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @@ -43,7 +44,7 @@ public class TestRestTemplateBasicLiveTest { RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); restTemplateBuilder.configure(restTemplate); TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder); - ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @@ -52,7 +53,7 @@ public class TestRestTemplateBasicLiveTest { RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); restTemplateBuilder.build(); TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder); - ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class); + ResponseEntity response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java index 2dfa81f441..60069cea71 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java @@ -1,7 +1,8 @@ package org.baeldung.web.handler; -import org.baeldung.web.exception.NotFoundException; -import org.baeldung.web.model.Bar; +import org.baeldung.resttemplate.web.exception.NotFoundException; +import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler; +import org.baeldung.resttemplate.web.model.Bar; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java index a45af318f1..f93ba71666 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java @@ -7,7 +7,8 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat import java.net.URI; import org.baeldung.SpringTestConfig; -import org.baeldung.web.model.Employee; +import org.baeldung.resttemplate.web.model.Employee; +import org.baeldung.resttemplate.web.service.EmployeeService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java index 23cd9a8fd2..f4b391573a 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java @@ -1,6 +1,7 @@ package org.baeldung.web.service; -import org.baeldung.web.model.Employee; +import org.baeldung.resttemplate.web.model.Employee; +import org.baeldung.resttemplate.web.service.EmployeeService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index b4239fb2b8..7c60a8e18a 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -21,17 +21,17 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-taglibs - ${org.springframework.security.version} + ${spring-security.version} @@ -144,7 +144,7 @@ org.springframework.security spring-security-test - ${org.springframework.security.version} + ${spring-security.version} test @@ -192,9 +192,6 @@ - - 5.0.6.RELEASE - 3.1.0 1.2 diff --git a/spring-security-mvc-jsonview/pom.xml b/spring-security-mvc-jsonview/pom.xml index 7f1129128f..b6d3e7e399 100644 --- a/spring-security-mvc-jsonview/pom.xml +++ b/spring-security-mvc-jsonview/pom.xml @@ -38,17 +38,17 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-taglibs - ${org.springframework.security.version} + ${spring-security.version} @@ -133,7 +133,7 @@ org.springframework.security spring-security-test - ${org.springframework.security.version} + ${spring-security.version} test @@ -206,9 +206,6 @@
- - 5.0.5.RELEASE - 3.1.0 1.2 diff --git a/spring-security-mvc-ldap/README.md b/spring-security-mvc-ldap/README.md index fe6a667c40..ac080c138d 100644 --- a/spring-security-mvc-ldap/README.md +++ b/spring-security-mvc-ldap/README.md @@ -6,7 +6,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Article: - [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll) -- [Spring Security Basic Authentication](http://www.baeldung.com/spring-security-basic-authentication) - [Intro to Spring Security LDAP](http://www.baeldung.com/spring-security-ldap) ### Notes diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index bbdff6fc2f..048297bbd4 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -21,17 +21,17 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-taglibs - ${org.springframework.security.version} + ${spring-security.version} @@ -116,7 +116,7 @@ org.springframework.security spring-security-test - ${org.springframework.security.version} + ${spring-security.version} test @@ -175,7 +175,6 @@ - 5.0.5.RELEASE 3.1.0 diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 37c743e896..24f1c5807a 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -21,12 +21,12 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring-security.version} @@ -144,7 +144,7 @@ org.springframework.security spring-security-test - ${org.springframework.security.version} + ${spring-security.version} test @@ -274,7 +274,6 @@ - 5.1.0.RELEASE 0.25.0.RELEASE diff --git a/spring-session/spring-session-jdbc/README.MD b/spring-session/spring-session-jdbc/README.md similarity index 55% rename from spring-session/spring-session-jdbc/README.MD rename to spring-session/spring-session-jdbc/README.md index 9293dfc953..94fd1cd3e7 100644 --- a/spring-session/spring-session-jdbc/README.MD +++ b/spring-session/spring-session-jdbc/README.md @@ -2,5 +2,3 @@ This module is for Spring Session with JDBC tutorial. Jira BAEL-1911 ### Relevant Articles: - -- [Spring Session with JDBC](http://www.baeldung.com/spring-session-jdbc) diff --git a/spring-session/spring-session-redis/README.md b/spring-session/spring-session-redis/README.md index 5e9304d778..5865913711 100644 --- a/spring-session/spring-session-redis/README.md +++ b/spring-session/spring-session-redis/README.md @@ -3,4 +3,3 @@ ## Spring Session Examples ### Relevant Articles: -- [Guide to Spring Session](http://www.baeldung.com/spring-session) diff --git a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/ForkJoinStateMachineConfiguration.java b/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/ForkJoinStateMachineConfiguration.java index 3a3e632c51..55e1397823 100644 --- a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/ForkJoinStateMachineConfiguration.java +++ b/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/ForkJoinStateMachineConfiguration.java @@ -64,11 +64,11 @@ public class ForkJoinStateMachineConfiguration extends StateMachineConfigurerAda @Bean public Guard mediumGuard() { - return (ctx) -> false; + return ctx -> false; } @Bean public Guard highGuard() { - return (ctx) -> false; + return ctx -> false; } } \ No newline at end of file diff --git a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/JunctionStateMachineConfiguration.java b/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/JunctionStateMachineConfiguration.java index 2f48a9dbb5..21b37381df 100644 --- a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/JunctionStateMachineConfiguration.java +++ b/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/JunctionStateMachineConfiguration.java @@ -50,11 +50,11 @@ public class JunctionStateMachineConfiguration extends StateMachineConfigurerAda @Bean public Guard mediumGuard() { - return (ctx) -> false; + return ctx -> false; } @Bean public Guard highGuard() { - return (ctx) -> false; + return ctx -> false; } } \ No newline at end of file diff --git a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/SimpleStateMachineConfiguration.java b/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/SimpleStateMachineConfiguration.java index d1b1ce001c..0c392c2c35 100644 --- a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/SimpleStateMachineConfiguration.java +++ b/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/SimpleStateMachineConfiguration.java @@ -18,7 +18,7 @@ import java.util.logging.Logger; @EnableStateMachine public class SimpleStateMachineConfiguration extends StateMachineConfigurerAdapter { - public static final Logger LOGGER = Logger.getLogger(SimpleStateMachineConfiguration.class.getName()); + private static final Logger LOGGER = Logger.getLogger(SimpleStateMachineConfiguration.class.getName()); @Override public void configure(StateMachineConfigurationConfigurer config) throws Exception { @@ -80,7 +80,7 @@ public class SimpleStateMachineConfiguration extends StateMachineConfigurerAdapt @Bean public Guard simpleGuard() { - return (ctx) -> { + return ctx -> { int approvalCount = (int) ctx .getExtendedState() .getVariables() diff --git a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/StateMachineListener.java b/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/StateMachineListener.java index 47a274404e..09e8946810 100644 --- a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/StateMachineListener.java +++ b/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/StateMachineListener.java @@ -7,10 +7,10 @@ import java.util.logging.Logger; public class StateMachineListener extends StateMachineListenerAdapter { - public static final Logger LOGGER = Logger.getLogger(StateMachineListener.class.getName()); + private static final Logger LOGGER = Logger.getLogger(StateMachineListener.class.getName()); @Override public void stateChanged(State from, State to) { - LOGGER.info(String.format("Transitioned from %s to %s%n", from == null ? "none" : from.getId(), to.getId())); + LOGGER.info(() -> String.format("Transitioned from %s to %s%n", from == null ? "none" : from.getId(), to.getId())); } } diff --git a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/ForkJoinStateMachineIntegrationTest.java b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/ForkJoinStateMachineIntegrationTest.java index b34d5c47c6..66acad901c 100644 --- a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/ForkJoinStateMachineIntegrationTest.java +++ b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/ForkJoinStateMachineIntegrationTest.java @@ -1,18 +1,15 @@ package com.baeldung.spring.statemachine; import com.baeldung.spring.statemachine.config.ForkJoinStateMachineConfiguration; -import com.baeldung.spring.statemachine.config.JunctionStateMachineConfiguration; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.statemachine.StateMachine; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; import java.util.Arrays; import static org.junit.Assert.assertEquals; diff --git a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/HierarchicalStateMachineIntegrationTest.java b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/HierarchicalStateMachineIntegrationTest.java index 3d7c0be828..00a9c9a08c 100644 --- a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/HierarchicalStateMachineIntegrationTest.java +++ b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/HierarchicalStateMachineIntegrationTest.java @@ -1,18 +1,15 @@ package com.baeldung.spring.statemachine; import com.baeldung.spring.statemachine.config.HierarchicalStateMachineConfiguration; -import com.baeldung.spring.statemachine.config.JunctionStateMachineConfiguration; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.statemachine.StateMachine; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; import java.util.Arrays; import static org.junit.Assert.assertEquals; diff --git a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/JunctionStateMachineIntegrationTest.java b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/JunctionStateMachineIntegrationTest.java index 93de23fad3..f0ee757522 100644 --- a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/JunctionStateMachineIntegrationTest.java +++ b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/JunctionStateMachineIntegrationTest.java @@ -1,20 +1,16 @@ package com.baeldung.spring.statemachine; import com.baeldung.spring.statemachine.config.JunctionStateMachineConfiguration; -import com.baeldung.spring.statemachine.config.SimpleEnumStateMachineConfiguration; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.statemachine.StateMachine; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = JunctionStateMachineConfiguration.class) public class JunctionStateMachineIntegrationTest { diff --git a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateEnumMachineIntegrationTest.java b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateEnumMachineIntegrationTest.java index 9074ece001..d345cd0dfc 100644 --- a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateEnumMachineIntegrationTest.java +++ b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateEnumMachineIntegrationTest.java @@ -3,19 +3,15 @@ package com.baeldung.spring.statemachine; import com.baeldung.spring.statemachine.applicationreview.ApplicationReviewEvents; import com.baeldung.spring.statemachine.applicationreview.ApplicationReviewStates; import com.baeldung.spring.statemachine.config.SimpleEnumStateMachineConfiguration; -import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.statemachine.StateMachine; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineBuilderIntegrationTest.java b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineBuilderIntegrationTest.java index c1de8b8958..e5431d9d83 100644 --- a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineBuilderIntegrationTest.java +++ b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineBuilderIntegrationTest.java @@ -1,11 +1,11 @@ package com.baeldung.spring.statemachine; -import static org.junit.Assert.assertEquals; - import org.junit.Test; import org.springframework.statemachine.StateMachine; import org.springframework.statemachine.config.StateMachineBuilder; +import static org.junit.Assert.assertEquals; + public class StateMachineBuilderIntegrationTest { @Test diff --git a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineIntegrationTest.java b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineIntegrationTest.java index 25df7c8cd3..aab07225a3 100644 --- a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineIntegrationTest.java +++ b/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineIntegrationTest.java @@ -1,22 +1,17 @@ package com.baeldung.spring.statemachine; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.statemachine.StateMachine; - -import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.junit4.SpringRunner; -import javax.annotation.Resource; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SimpleStateMachineConfiguration.class) @@ -42,7 +37,7 @@ public class StateMachineIntegrationTest { } @Test - public void whenSimpleStringMachineActionState_thenActionExecuted() throws InterruptedException { + public void whenSimpleStringMachineActionState_thenActionExecuted() { stateMachine.sendEvent("E3"); assertEquals("S3", stateMachine.getState().getId()); diff --git a/spring-static-resources/pom.xml b/spring-static-resources/pom.xml index aedf88e384..fc2b3336bc 100644 --- a/spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -20,17 +20,17 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring-security.version} org.springframework.security spring-security-taglibs - ${org.springframework.security.version} + ${spring-security.version} @@ -196,9 +196,6 @@ - - 5.0.6.RELEASE - 1.8.9 2.3.2-b02 diff --git a/tensorflow-java/.gitignore b/tensorflow-java/.gitignore new file mode 100644 index 0000000000..eaea64ae48 --- /dev/null +++ b/tensorflow-java/.gitignore @@ -0,0 +1,6 @@ +/.settings +/model +/target +.classpath +.project +.springBeans \ No newline at end of file diff --git a/tensorflow-java/README.md b/tensorflow-java/README.md new file mode 100644 index 0000000000..aac5b7544c --- /dev/null +++ b/tensorflow-java/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [TensorFlow for Java](https://www.baeldung.com/xxxx) diff --git a/tensorflow-java/pom.xml b/tensorflow-java/pom.xml new file mode 100644 index 0000000000..e9d92157e8 --- /dev/null +++ b/tensorflow-java/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + com.baeldung + tensorflow-java + 1.0-SNAPSHOT + jar + http://maven.apache.org + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 1.8 + 1.12.0 + 5.4.0 + + + + + org.tensorflow + tensorflow + ${tensorflow.version} + + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowGraph.java b/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowGraph.java new file mode 100644 index 0000000000..a44ef4c4ee --- /dev/null +++ b/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowGraph.java @@ -0,0 +1,41 @@ +package org.baeldung.tensorflow; + +import org.tensorflow.DataType; +import org.tensorflow.Graph; +import org.tensorflow.Operation; +import org.tensorflow.Session; +import org.tensorflow.Tensor; + +public class TensorflowGraph { + + public static Graph createGraph() { + Graph graph = new Graph(); + Operation a = graph.opBuilder("Const", "a").setAttr("dtype", DataType.fromClass(Double.class)) + .setAttr("value", Tensor.create(3.0, Double.class)).build(); + Operation b = graph.opBuilder("Const", "b").setAttr("dtype", DataType.fromClass(Double.class)) + .setAttr("value", Tensor.create(2.0, Double.class)).build(); + Operation x = graph.opBuilder("Placeholder", "x").setAttr("dtype", DataType.fromClass(Double.class)).build(); + Operation y = graph.opBuilder("Placeholder", "y").setAttr("dtype", DataType.fromClass(Double.class)).build(); + Operation ax = graph.opBuilder("Mul", "ax").addInput(a.output(0)).addInput(x.output(0)).build(); + Operation by = graph.opBuilder("Mul", "by").addInput(b.output(0)).addInput(y.output(0)).build(); + graph.opBuilder("Add", "z").addInput(ax.output(0)).addInput(by.output(0)).build(); + return graph; + } + + public static Object runGraph(Graph graph, Double x, Double y) { + Object result; + try (Session sess = new Session(graph)) { + result = sess.runner().fetch("z").feed("x", Tensor.create(x, Double.class)) + .feed("y", Tensor.create(y, Double.class)).run().get(0).expect(Double.class) + .doubleValue(); + } + return result; + } + + public static void main(String[] args) { + Graph graph = TensorflowGraph.createGraph(); + Object result = TensorflowGraph.runGraph(graph, 3.0, 6.0); + System.out.println(result); + graph.close(); + } +} \ No newline at end of file diff --git a/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowSavedModel.java b/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowSavedModel.java new file mode 100644 index 0000000000..4259a787e8 --- /dev/null +++ b/tensorflow-java/src/main/java/org/baeldung/tensorflow/TensorflowSavedModel.java @@ -0,0 +1,14 @@ +package org.baeldung.tensorflow; + +import org.tensorflow.SavedModelBundle; +import org.tensorflow.Tensor; + +public class TensorflowSavedModel { + + public static void main(String[] args) { + SavedModelBundle model = SavedModelBundle.load("./model", "serve"); + Tensor tensor = model.session().runner().fetch("z").feed("x", Tensor.create(3, Integer.class)) + .feed("y", Tensor.create(3, Integer.class)).run().get(0).expect(Integer.class); + System.out.println(tensor.intValue()); + } +} \ No newline at end of file diff --git a/tensorflow-java/src/main/python/tensorflowGraph.py b/tensorflow-java/src/main/python/tensorflowGraph.py new file mode 100644 index 0000000000..ab7f8810ac --- /dev/null +++ b/tensorflow-java/src/main/python/tensorflowGraph.py @@ -0,0 +1,16 @@ +import tensorflow as tf +graph = tf.Graph() +builder = tf.saved_model.builder.SavedModelBuilder('./model') +writer = tf.summary.FileWriter('.') +with graph.as_default(): + a = tf.constant(2, name='a') + b = tf.constant(3, name='b') + x = tf.placeholder(tf.int32, name='x') + y = tf.placeholder(tf.int32, name='y') + z = tf.math.add(a*x, b*y, name='z') + writer.add_graph(tf.get_default_graph()) + writer.flush() + sess = tf.Session() + sess.run(z, feed_dict = {x: 2, y: 3}) + builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING]) + builder.save() diff --git a/tensorflow-java/src/test/java/org/baeldung/tensorflow/TensorflowGraphUnitTest.java b/tensorflow-java/src/test/java/org/baeldung/tensorflow/TensorflowGraphUnitTest.java new file mode 100644 index 0000000000..51df6a4322 --- /dev/null +++ b/tensorflow-java/src/test/java/org/baeldung/tensorflow/TensorflowGraphUnitTest.java @@ -0,0 +1,21 @@ +package org.baeldung.tensorflow; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.Test; +import org.tensorflow.Graph; + +public class TensorflowGraphUnitTest { + + @Test + public void givenTensorflowGraphWhenRunInSessionReturnsExpectedResult() { + + Graph graph = TensorflowGraph.createGraph(); + Object result = TensorflowGraph.runGraph(graph, 3.0, 6.0); + assertEquals(21.0, result); + System.out.println(result); + graph.close(); + + } + +} diff --git a/testing-modules/groovy-spock/README.md b/testing-modules/groovy-spock/README.md index 18d26e8fc0..a98df27172 100644 --- a/testing-modules/groovy-spock/README.md +++ b/testing-modules/groovy-spock/README.md @@ -1,3 +1,4 @@ ### Relevant articles - [Introduction to Testing with Spock and Groovy](http://www.baeldung.com/groovy-spock) +- [Difference Between Stub, Mock, and Spy in the Spock Framework](https://www.baeldung.com/spock-stub-mock-spy) diff --git a/testing-modules/junit5-migration/README.md b/testing-modules/junit5-migration/README.md deleted file mode 100644 index 5fe7fc1f16..0000000000 --- a/testing-modules/junit5-migration/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: -- [JUnit4 -> JUnit5 migration guide](http://www.baeldung.com/junit4-junit5-migration-guide) - diff --git a/testing-modules/mocks/README.md b/testing-modules/mocks/README.md index 2b24ed8536..3cb20dcf92 100644 --- a/testing-modules/mocks/README.md +++ b/testing-modules/mocks/README.md @@ -1,8 +1,4 @@ ## Relevant articles: -- [JMockit Advanced Usage](http://www.baeldung.com/jmockit-advanced-usage) -- [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations) -- [JMockit 101](http://www.baeldung.com/jmockit-101) -- [Mockito vs EasyMock vs JMockit](http://www.baeldung.com/mockito-vs-easymock-vs-jmockit) - [EasyMock Argument Matchers](http://www.baeldung.com/easymock-argument-matchers) - [Mock Static Method using JMockit](https://www.baeldung.com/jmockit-static-method) diff --git a/testing-modules/mocks/jmockit/README.md b/testing-modules/mocks/jmockit/README.md index 3063fdc31d..0e44b93d6e 100644 --- a/testing-modules/mocks/jmockit/README.md +++ b/testing-modules/mocks/jmockit/README.md @@ -6,5 +6,4 @@ ### Relevant Articles: - [JMockit 101](http://www.baeldung.com/jmockit-101) - [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations) -- [JMockit Advanced Topics](http://www.baeldung.com/jmockit-advanced-topics) - [JMockit Advanced Usage](http://www.baeldung.com/jmockit-advanced-usage) diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 687a9a2fe4..cd342ccd11 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -8,16 +8,34 @@ com.baeldung - parent-java + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-java + ../../parent-boot-2 + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-json + + + org.springframework.boot + spring-boot-starter-test + test + + + com.google.guava + guava + ${guava.version} + javax.servlet javax.servlet-api - ${javax.servlet-api.version} javax.servlet @@ -27,49 +45,40 @@ org.eclipse.jetty jetty-security - ${jetty.version} org.eclipse.jetty jetty-servlet - ${jetty.version} org.eclipse.jetty jetty-servlets - ${jetty.version} org.eclipse.jetty jetty-io - ${jetty.version} org.eclipse.jetty jetty-http - ${jetty.version} org.eclipse.jetty jetty-server - ${jetty.version} org.eclipse.jetty jetty-util - ${jetty.version} org.apache.httpcomponents httpcore - ${httpcore.version} org.apache.commons commons-lang3 - ${commons-lang3.version} @@ -93,18 +102,15 @@ joda-time joda-time - ${joda-time.version} com.fasterxml.jackson.core jackson-annotations - ${jackson.version} com.fasterxml.jackson.core jackson-databind - ${jackson.version} @@ -128,7 +134,6 @@ org.apache.httpcomponents httpclient - ${httpclient.version} @@ -142,17 +147,6 @@ wiremock ${wiremock.version} - - io.rest-assured - rest-assured - ${rest-assured.version} - test - - - io.rest-assured - json-schema-validator - ${rest-assured-json-schema-validator.version} - com.github.fge json-schema-validator @@ -168,9 +162,27 @@ commons-collections ${commons-collections.version} + + + + io.rest-assured + rest-assured + test + + + io.rest-assured + spring-mock-mvc + test + + + io.rest-assured + json-schema-validator + test + + 18.0 2.9.7 1.8 19.0 diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/Application.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/Application.java new file mode 100644 index 0000000000..8b53a9c63d --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.restassured; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/controller/AppController.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/controller/AppController.java new file mode 100644 index 0000000000..d68ebf4b03 --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/controller/AppController.java @@ -0,0 +1,100 @@ +package com.baeldung.restassured.controller; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.util.Set; +import java.util.UUID; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.InputStreamResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.restassured.model.Movie; +import com.baeldung.restassured.service.AppService; + +@RestController +public class AppController { + + @Autowired + AppService appService; + + @GetMapping("/movies") + public ResponseEntity getMovies() { + + Set result = appService.getAll(); + + return ResponseEntity.ok() + .body(result); + } + + @PostMapping("/movie") + @ResponseStatus(HttpStatus.CREATED) + public Movie addMovie(@RequestBody Movie movie) { + + appService.add(movie); + return movie; + } + + @GetMapping("/movie/{id}") + public ResponseEntity getMovie(@PathVariable int id) { + + Movie movie = appService.findMovie(id); + if (movie == null) { + return ResponseEntity.badRequest() + .body("Invalid movie id"); + } + + return ResponseEntity.ok(movie); + } + + @GetMapping("/welcome") + public ResponseEntity welcome(HttpServletResponse response) { + + HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8"); + headers.add("sessionId", UUID.randomUUID() + .toString()); + + Cookie cookie = new Cookie("token", "some-token"); + cookie.setDomain("localhost"); + + response.addCookie(cookie); + + return ResponseEntity.noContent() + .headers(headers) + .build(); + } + + @GetMapping("/download/{id}") + public ResponseEntity getFile(@PathVariable int id) throws FileNotFoundException { + + File file = appService.getFile(id); + + if (file == null) { + return ResponseEntity.notFound() + .build(); + } + + InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); + + return ResponseEntity.ok() + .contentLength(file.length()) + .contentType(MediaType.parseMediaType("application/octet-stream")) + .body(resource); + } + +} diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/Course.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/Course.java new file mode 100644 index 0000000000..ac958b3239 --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/Course.java @@ -0,0 +1,17 @@ +package com.baeldung.restassured.learner; + +class Course { + + private String code; + + public Course() { + } + + Course(String code) { + this.code = code; + } + + String getCode() { + return code; + } +} diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseController.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseController.java new file mode 100644 index 0000000000..f4a3f56608 --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseController.java @@ -0,0 +1,31 @@ +package com.baeldung.restassured.learner; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Collection; + +import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; + +@RestController +@RequestMapping(path = "/courses") +public class CourseController { + + private final CourseService courseService; + + public CourseController(CourseService courseService) { + this.courseService = courseService; + } + + @GetMapping(produces = APPLICATION_JSON_UTF8_VALUE) + public Collection getCourses() { + return courseService.getCourses(); + } + + @GetMapping(path = "/{code}", produces = APPLICATION_JSON_UTF8_VALUE) + public Course getCourse(@PathVariable String code) { + return courseService.getCourse(code); + } +} diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseControllerExceptionHandler.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseControllerExceptionHandler.java new file mode 100644 index 0000000000..b17e95c31c --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseControllerExceptionHandler.java @@ -0,0 +1,18 @@ +package com.baeldung.restassured.learner; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +@ControllerAdvice(assignableTypes = CourseController.class) +public class CourseControllerExceptionHandler extends ResponseEntityExceptionHandler { + + @ResponseStatus(HttpStatus.NOT_FOUND) + @ExceptionHandler(CourseNotFoundException.class) + @SuppressWarnings("ThrowablePrintedToSystemOut") + public void handleCourseNotFoundException(CourseNotFoundException cnfe) { + System.out.println(cnfe); + } +} diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseNotFoundException.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseNotFoundException.java new file mode 100644 index 0000000000..dc1a3f796d --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseNotFoundException.java @@ -0,0 +1,8 @@ +package com.baeldung.restassured.learner; + +class CourseNotFoundException extends RuntimeException { + + CourseNotFoundException(String code) { + super(code); + } +} diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseService.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseService.java new file mode 100644 index 0000000000..11508ab9ba --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/learner/CourseService.java @@ -0,0 +1,27 @@ +package com.baeldung.restassured.learner; + +import org.springframework.stereotype.Service; + +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +@Service +class CourseService { + + private static final Map COURSE_MAP = new ConcurrentHashMap<>(); + + static { + Course wizardry = new Course("Wizardry"); + COURSE_MAP.put(wizardry.getCode(), wizardry); + } + + Collection getCourses() { + return COURSE_MAP.values(); + } + + Course getCourse(String code) { + return Optional.ofNullable(COURSE_MAP.get(code)).orElseThrow(() -> new CourseNotFoundException(code)); + } +} diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/model/Movie.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/model/Movie.java new file mode 100644 index 0000000000..00a446fc65 --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/model/Movie.java @@ -0,0 +1,58 @@ +package com.baeldung.restassured.model; + +public class Movie { + + private Integer id; + + private String name; + + private String synopsis; + + public Movie() { + } + + public Movie(Integer id, String name, String synopsis) { + super(); + this.id = id; + this.name = name; + this.synopsis = synopsis; + } + + public Integer getId() { + return id; + } + + public String getName() { + return name; + } + + public String getSynopsis() { + return synopsis; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Movie other = (Movie) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + +} diff --git a/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/service/AppService.java b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/service/AppService.java new file mode 100644 index 0000000000..15685f2924 --- /dev/null +++ b/testing-modules/rest-assured/src/main/java/com/baeldung/restassured/service/AppService.java @@ -0,0 +1,45 @@ +package com.baeldung.restassured.service; + +import java.io.File; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Service; + +import com.baeldung.restassured.model.Movie; + +@Service +public class AppService { + + private Set movieSet = new HashSet<>(); + + public Set getAll() { + return movieSet; + } + + public void add(Movie movie) { + movieSet.add(movie); + } + + public Movie findMovie(int id) { + return movieSet.stream() + .filter(movie -> movie.getId() + .equals(id)) + .findFirst() + .orElse(null); + } + + public File getFile(int id) { + File file = null; + try { + file = new ClassPathResource(String.valueOf(id)).getFile(); + } catch (IOException e) { + e.printStackTrace(); + } + + return file; + } + +} diff --git a/testing-modules/rest-assured/src/main/resources/1 b/testing-modules/rest-assured/src/main/resources/1 new file mode 100644 index 0000000000..49351eb5b7 --- /dev/null +++ b/testing-modules/rest-assured/src/main/resources/1 @@ -0,0 +1 @@ +File 1 \ No newline at end of file diff --git a/testing-modules/rest-assured/src/main/resources/2 b/testing-modules/rest-assured/src/main/resources/2 new file mode 100644 index 0000000000..9fbb45ed08 --- /dev/null +++ b/testing-modules/rest-assured/src/main/resources/2 @@ -0,0 +1 @@ +File 2 \ No newline at end of file diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/controller/AppControllerIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/controller/AppControllerIntegrationTest.java new file mode 100644 index 0000000000..a55c0a69e4 --- /dev/null +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/controller/AppControllerIntegrationTest.java @@ -0,0 +1,149 @@ +package com.baeldung.restassured.controller; + +import static io.restassured.RestAssured.get; +import static io.restassured.RestAssured.given; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.annotation.PostConstruct; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.restassured.model.Movie; +import com.baeldung.restassured.service.AppService; + +import io.restassured.response.Response; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class AppControllerIntegrationTest { + + @LocalServerPort + private int port; + + private String uri; + + @PostConstruct + public void init() { + uri = "http://localhost:" + port; + } + + @MockBean + AppService appService; + + @Test + public void givenMovieId_whenMakingGetRequestToMovieEndpoint_thenReturnMovie() { + + Movie testMovie = new Movie(1, "movie1", "summary1"); + when(appService.findMovie(1)).thenReturn(testMovie); + + get(uri + "/movie/" + testMovie.getId()).then() + .assertThat() + .statusCode(HttpStatus.OK.value()) + .body("id", equalTo(testMovie.getId())) + .body("name", equalTo(testMovie.getName())) + .body("synopsis", notNullValue()); + + Movie result = get(uri + "/movie/" + testMovie.getId()).then() + .assertThat() + .statusCode(HttpStatus.OK.value()) + .extract() + .as(Movie.class); + assertThat(result).isEqualTo(testMovie); + + String responseString = get(uri + "/movie/" + testMovie.getId()).then() + .assertThat() + .statusCode(HttpStatus.OK.value()) + .extract() + .asString(); + assertThat(responseString).isNotEmpty(); + } + + @Test + public void whenCallingMoviesEndpoint_thenReturnAllMovies() { + + Set movieSet = new HashSet<>(); + movieSet.add(new Movie(1, "movie1", "summary1")); + movieSet.add(new Movie(2, "movie2", "summary2")); + when(appService.getAll()).thenReturn(movieSet); + + get(uri + "/movies").then() + .statusCode(HttpStatus.OK.value()) + .assertThat() + .body("size()", is(2)); + + Movie[] movies = get(uri + "/movies").then() + .statusCode(200) + .extract() + .as(Movie[].class); + assertThat(movies.length).isEqualTo(2); + } + + @Test + public void givenMovie_whenMakingPostRequestToMovieEndpoint_thenCorrect() { + + Map request = new HashMap<>(); + request.put("id", "11"); + request.put("name", "movie1"); + request.put("synopsis", "summary1"); + + int movieId = given().contentType("application/json") + .body(request) + .when() + .post(uri + "/movie") + .then() + .assertThat() + .statusCode(HttpStatus.CREATED.value()) + .extract() + .path("id"); + assertThat(movieId).isEqualTo(11); + + } + + @Test + public void whenCallingWelcomeEndpoint_thenCorrect() { + + get(uri + "/welcome").then() + .assertThat() + .header("sessionId", notNullValue()) + .cookie("token", notNullValue()); + + Response response = get(uri + "/welcome"); + + String headerName = response.getHeader("sessionId"); + String cookieValue = response.getCookie("token"); + assertThat(headerName).isNotBlank(); + assertThat(cookieValue).isNotBlank(); + } + + @Test + public void givenId_whenCallingDowloadEndpoint_thenCorrect() throws IOException { + + File file = new ClassPathResource("test.txt").getFile(); + long fileSize = file.length(); + when(appService.getFile(1)).thenReturn(file); + + byte[] result = get(uri + "/download/1").asByteArray(); + + assertThat(result.length).isEqualTo(fileSize); + } + +} diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/learner/CourseControllerIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/learner/CourseControllerIntegrationTest.java new file mode 100644 index 0000000000..5e36cd169b --- /dev/null +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/learner/CourseControllerIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.restassured.learner; + +import static io.restassured.module.mockmvc.RestAssuredMockMvc.given; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +import static org.springframework.http.HttpStatus.NOT_FOUND; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.context.WebApplicationContext; + +import io.restassured.module.mockmvc.RestAssuredMockMvc; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = RANDOM_PORT) +public class CourseControllerIntegrationTest { + + @Autowired + private WebApplicationContext webApplicationContext; + + @Before + public void initialiseRestAssuredMockMvcWebApplicationContext() { + RestAssuredMockMvc.webAppContextSetup(webApplicationContext); + } + + @Test + public void givenNoMatchingCourseCodeWhenGetCourseThenRespondWithStatusNotFound() { + String nonMatchingCourseCode = "nonMatchingCourseCode"; + + given() + .when() + .get("/courses/" + nonMatchingCourseCode) + .then() + .log().ifValidationFails() + .statusCode(NOT_FOUND.value()); + } +} diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/learner/CourseControllerUnitTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/learner/CourseControllerUnitTest.java new file mode 100644 index 0000000000..2a795e2b0b --- /dev/null +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/learner/CourseControllerUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.restassured.learner; + +import io.restassured.module.mockmvc.RestAssuredMockMvc; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Collections; + +import static io.restassured.http.ContentType.JSON; +import static io.restassured.module.mockmvc.RestAssuredMockMvc.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.when; +import static org.springframework.http.HttpStatus.NOT_FOUND; +import static org.springframework.http.HttpStatus.OK; + +@RunWith(MockitoJUnitRunner.class) +public class CourseControllerUnitTest { + + @Mock + private CourseService courseService; + @InjectMocks + private CourseController courseController; + @InjectMocks + private CourseControllerExceptionHandler courseControllerExceptionHandler; + + @Before + public void initialiseRestAssuredMockMvcStandalone() { + RestAssuredMockMvc.standaloneSetup(courseController, courseControllerExceptionHandler); + } + + @Test + public void givenNoExistingCoursesWhenGetCoursesThenRespondWithStatusOkAndEmptyArray() { + when(courseService.getCourses()).thenReturn(Collections.emptyList()); + + given() + .when() + .get("/courses") + .then() + .log().ifValidationFails() + .statusCode(OK.value()) + .contentType(JSON) + .body(is(equalTo("[]"))); + } + + @Test + public void givenNoMatchingCoursesWhenGetCoursesThenRespondWithStatusNotFound() { + String nonMatchingCourseCode = "nonMatchingCourseCode"; + + when(courseService.getCourse(nonMatchingCourseCode)).thenThrow(new CourseNotFoundException(nonMatchingCourseCode)); + + given() + .when() + .get("/courses/" + nonMatchingCourseCode) + .then() + .log().ifValidationFails() + .statusCode(NOT_FOUND.value()); + } +} diff --git a/testing-modules/rest-assured/src/test/resources/test.txt b/testing-modules/rest-assured/src/test/resources/test.txt new file mode 100644 index 0000000000..84362ca046 --- /dev/null +++ b/testing-modules/rest-assured/src/test/resources/test.txt @@ -0,0 +1 @@ +Test file \ No newline at end of file diff --git a/xml/README.md b/xml/README.md index fb070100db..9d889ef8e9 100644 --- a/xml/README.md +++ b/xml/README.md @@ -4,3 +4,4 @@ - [XML Libraries Support in Java](http://www.baeldung.com/java-xml-libraries) - [DOM parsing with Xerces](http://www.baeldung.com/java-xerces-dom-parsing) - [Write an org.w3.dom.Document to a File](https://www.baeldung.com/java-write-xml-document-file) +- [Convert XML to HTML](https://www.baeldung.com/) diff --git a/xml/pom.xml b/xml/pom.xml index dfdec4da16..ba6a734dc9 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -30,6 +30,22 @@ ${jdom2.version} + + javax.xml + jaxb-api + 2.1 + + + javax.xml + jaxp-api + 1.4.2 + + + javax.xml.stream + stax-api + 1.0-2 + + commons-io diff --git a/xml/src/main/java/com/baeldung/xmlhtml/Application.java b/xml/src/main/java/com/baeldung/xmlhtml/Application.java new file mode 100644 index 0000000000..063a833810 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/Application.java @@ -0,0 +1,10 @@ +package com.baeldung.xmlhtml; + +import com.baeldung.xmlhtml.helpers.XMLRunner; + +public class Application { + + public static void main(String[] args) { + XMLRunner.doWork(); + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/Constants.java b/xml/src/main/java/com/baeldung/xmlhtml/Constants.java new file mode 100644 index 0000000000..88fc5637df --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/Constants.java @@ -0,0 +1,22 @@ +package com.baeldung.xmlhtml; + +public class Constants { + + public static final String XML_FILE_IN = "src/main/resources/xml/in.xml"; + public static final String JAXB_FILE_OUT = "src/main/resources/xml/jaxb.html"; + public static final String JAXP_FILE_OUT = "src/main/resources/xml/jaxp.html"; + public static final String STAX_FILE_OUT = "src/main/resources/xml/stax.html"; + + public static final String EXCEPTION_ENCOUNTERED = "Generic exception! Error: "; + + public static final String LINE_BREAK = System.getProperty("line.separator"); + public static final String WHITE_SPACE = " "; + + public static final String DOCUMENT_START = "Document parsing has begun!"; + public static final String DOCUMENT_END = "Document parsing has ended!"; + public static final String ELEMENT_START = "Element parsing has begun!"; + public static final String ELEMENT_END = "Element parsing has ended!"; + + public static final String BREAK = "\n"; + public static final String TAB = "\t"; +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/helpers/XMLRunner.java b/xml/src/main/java/com/baeldung/xmlhtml/helpers/XMLRunner.java new file mode 100644 index 0000000000..02b2577795 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/helpers/XMLRunner.java @@ -0,0 +1,16 @@ +package com.baeldung.xmlhtml.helpers; + + +import com.baeldung.xmlhtml.helpers.jaxb.JAXBHelper; +import com.baeldung.xmlhtml.helpers.jaxp.JAXPHelper; +import com.baeldung.xmlhtml.helpers.stax.STAXHelper; + +public class XMLRunner { + + public static void doWork() { + JAXBHelper.example(); + JAXPHelper.saxParser(); + JAXPHelper.documentBuilder(); + STAXHelper.write(STAXHelper.read()); + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxb/JAXBHelper.java b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxb/JAXBHelper.java new file mode 100644 index 0000000000..715f963f2e --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxb/JAXBHelper.java @@ -0,0 +1,77 @@ +package com.baeldung.xmlhtml.helpers.jaxb; + +import com.baeldung.xmlhtml.pojo.jaxb.html.ExampleHTML; +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.Body; +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.CustomElement; +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.Meta; +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.NestedElement; +import com.baeldung.xmlhtml.pojo.jaxb.xml.XMLExample; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; + +import java.io.File; + +import static com.baeldung.xmlhtml.Constants.*; + +public class JAXBHelper { + + private static void print(String xmlContent) { + System.out.println(xmlContent); + } + + private static Unmarshaller getContextUnmarshaller(Class clazz) { + Unmarshaller unmarshaller = null; + try { + JAXBContext context = JAXBContext.newInstance(clazz); + unmarshaller = context.createUnmarshaller(); + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + return unmarshaller; + } + + private static Marshaller getContextMarshaller(Class clazz) { + Marshaller marshaller = null; + try { + JAXBContext context = JAXBContext.newInstance(clazz); + marshaller = context.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + marshaller.setProperty("jaxb.fragment", Boolean.TRUE); + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + return marshaller; + } + + public static void example() { + try { + XMLExample xml = (XMLExample) JAXBHelper.getContextUnmarshaller(XMLExample.class).unmarshal(new File(XML_FILE_IN)); + JAXBHelper.print(xml.toString()); + ExampleHTML html = new ExampleHTML(); + + Body body = new Body(); + CustomElement customElement = new CustomElement(); + NestedElement nested = new NestedElement(); + CustomElement child = new CustomElement(); + + customElement.setValue("descendantOne: " + xml.getAncestor().getDescendantOne().getValue()); + child.setValue("descendantThree: " + xml.getAncestor().getDescendantTwo().getDescendantThree().getValue()); + nested.setCustomElement(child); + + body.setCustomElement(customElement); + body.setNestedElement(nested); + + Meta meta = new Meta(); + meta.setTitle("example"); + html.getHead().add(meta); + html.setBody(body); + + JAXBHelper.getContextMarshaller(ExampleHTML.class).marshal(html, new File(JAXB_FILE_OUT)); + + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + } +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/CustomHandler.java b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/CustomHandler.java new file mode 100644 index 0000000000..e6351c9e22 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/CustomHandler.java @@ -0,0 +1,34 @@ +package com.baeldung.xmlhtml.helpers.jaxp; + +import org.xml.sax.ContentHandler; +import org.xml.sax.Locator; + +import static com.baeldung.xmlhtml.Constants.*; + +public class CustomHandler implements ContentHandler { + + public void startDocument() {} + + public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) { } + + public void endDocument() { + System.out.println(DOCUMENT_END); + } + + public void endElement(String uri, String localName, String qName) { } + + public void startPrefixMapping(String prefix, String uri) { } + + public void endPrefixMapping(String prefix) { } + + public void setDocumentLocator(Locator locator) { } + + public void characters(char[] ch, int start, int length) { } + + public void ignorableWhitespace(char[] ch, int start, int length) { } + + public void processingInstruction(String target, String data) { } + + public void skippedEntity(String name) { } + +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/JAXPHelper.java b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/JAXPHelper.java new file mode 100644 index 0000000000..3196d543da --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/helpers/jaxp/JAXPHelper.java @@ -0,0 +1,90 @@ +package com.baeldung.xmlhtml.helpers.jaxp; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.XMLReader; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.File; + +import static com.baeldung.xmlhtml.Constants.*; + +public class JAXPHelper { + + private static void print(Document document) { + NodeList list = document.getChildNodes(); + try { + for (int i = 0; i < list.getLength(); i++) { + Node node = list.item(i); + String message = + node.getNodeType() + + WHITE_SPACE + + node.getNodeName() + + LINE_BREAK; + System.out.println(message); + } + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + } + + public static void saxParser() { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + try { + SAXParser saxParser = spf.newSAXParser(); + XMLReader xmlReader = saxParser.getXMLReader(); + xmlReader.setContentHandler(new CustomHandler()); + xmlReader.parse(XML_FILE_IN); + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + } + + public static void documentBuilder() { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + try { + DocumentBuilder db = dbf.newDocumentBuilder(); + Document parsed = db.parse(new File(XML_FILE_IN)); + Element xml = parsed.getDocumentElement(); + + Document doc = db.newDocument(); + Element html = doc.createElement("html"); + Element head = doc.createElement("head"); + html.appendChild(head); + + Element body = doc.createElement("body"); + Element descendantOne = doc.createElement("p"); + descendantOne.setTextContent("descendantOne: " + + xml.getElementsByTagName("descendantOne") + .item(0).getTextContent()); + Element descendantThree = doc.createElement("p"); + descendantThree.setTextContent("descendantThree: " + + xml.getElementsByTagName("descendantThree") + .item(0).getTextContent()); + Element nested = doc.createElement("div"); + nested.appendChild(descendantThree); + + body.appendChild(descendantOne); + body.appendChild(nested); + html.appendChild(body); + doc.appendChild(html); + + TransformerFactory tFactory = TransformerFactory.newInstance(); + tFactory + .newTransformer() + .transform(new DOMSource(doc), new StreamResult(new File(JAXP_FILE_OUT))); + + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/helpers/stax/STAXHelper.java b/xml/src/main/java/com/baeldung/xmlhtml/helpers/stax/STAXHelper.java new file mode 100644 index 0000000000..a9b9217b6a --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/helpers/stax/STAXHelper.java @@ -0,0 +1,112 @@ +package com.baeldung.xmlhtml.helpers.stax; + +import com.baeldung.xmlhtml.pojo.stax.Body; +import com.baeldung.xmlhtml.pojo.stax.CustomElement; +import com.baeldung.xmlhtml.pojo.stax.NestedElement; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; +import java.io.FileInputStream; +import java.io.FileWriter; + +import static com.baeldung.xmlhtml.Constants.*; + +public class STAXHelper { + + private static XMLStreamReader reader() { + XMLStreamReader xmlStreamReader = null; + try { + xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(XML_FILE_IN)); + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + return xmlStreamReader; + } + + private static XMLStreamWriter writer() { + XMLStreamWriter xmlStreamWriter = null; + try { + xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter(STAX_FILE_OUT)); + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + return xmlStreamWriter; + } + + public static Body read() { + Body body = new Body(); + try { + XMLStreamReader xmlStreamReader = reader(); + + CustomElement customElement = new CustomElement(); + NestedElement nestedElement = new NestedElement(); + CustomElement child = new CustomElement(); + + while (xmlStreamReader.hasNext()) { + xmlStreamReader.next(); + if (xmlStreamReader.isStartElement()) { + System.out.println(xmlStreamReader.getLocalName()); + if (xmlStreamReader.getLocalName().equals("descendantOne")) { + customElement.setValue(xmlStreamReader.getElementText()); + } + if (xmlStreamReader.getLocalName().equals("descendantThree")) { + child.setValue(xmlStreamReader.getElementText()); + } + } + } + + nestedElement.setCustomElement(child); + body.setCustomElement(customElement); + body.setNestedElement(nestedElement); + + xmlStreamReader.close(); + + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + return body; + } + + public static void write(Body body) { + try { + + XMLStreamWriter xmlStreamWriter = writer(); + xmlStreamWriter.writeStartElement("html"); + xmlStreamWriter.writeCharacters(BREAK + TAB); + xmlStreamWriter.writeStartElement("head"); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB); + xmlStreamWriter.writeStartElement("meta"); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK + TAB); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK + TAB); + xmlStreamWriter.writeStartElement("body"); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB); + xmlStreamWriter.writeStartElement("p"); + xmlStreamWriter.writeCharacters("descendantOne: " + body.getCustomElement().getValue()); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB); + xmlStreamWriter.writeStartElement("div"); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB + TAB); + xmlStreamWriter.writeStartElement("p"); + xmlStreamWriter.writeCharacters(BREAK); + xmlStreamWriter.writeCharacters(TAB + TAB + TAB + TAB + "descendantThree: " + body.getNestedElement().getCustomElement().getValue()); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB + TAB); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK + TAB + TAB); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK + TAB); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeCharacters(BREAK); + xmlStreamWriter.writeEndDocument(); + xmlStreamWriter.flush(); + xmlStreamWriter.close(); + + } catch (Exception ex) { + System.out.println(EXCEPTION_ENCOUNTERED + ex); + } + + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/ExampleHTML.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/ExampleHTML.java new file mode 100644 index 0000000000..d44c81f309 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/ExampleHTML.java @@ -0,0 +1,38 @@ +package com.baeldung.xmlhtml.pojo.jaxb.html; + +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.Body; +import com.baeldung.xmlhtml.pojo.jaxb.html.elements.Meta; + +import javax.xml.bind.annotation.*; +import java.util.ArrayList; +import java.util.List; + +@XmlType(propOrder = {"head", "body"}) +@XmlRootElement(name = "html") +public class ExampleHTML { + + private List head = new ArrayList<>(); + + private Body body; + + public ExampleHTML() { } + + public List getHead() { + return head; + } + + @XmlElementWrapper(name = "head") + @XmlElement(name = "meta") + public void setHead(List head) { + this.head = head; + } + + public Body getBody() { + return body; + } + + @XmlElement(name = "body") + public void setBody(Body body) { + this.body = body; + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Body.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Body.java new file mode 100644 index 0000000000..36c6c13a04 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Body.java @@ -0,0 +1,29 @@ +package com.baeldung.xmlhtml.pojo.jaxb.html.elements; + +import javax.xml.bind.annotation.XmlElement; + +public class Body { + + private CustomElement customElement; + + public CustomElement getCustomElement() { + return customElement; + } + + @XmlElement(name = "p") + public void setCustomElement(CustomElement customElement) { + this.customElement = customElement; + } + + private NestedElement nestedElement; + + public NestedElement getNestedElement() { + return nestedElement; + } + + @XmlElement(name = "div") + public void setNestedElement(NestedElement nestedElement) { + this.nestedElement = nestedElement; + } + +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/CustomElement.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/CustomElement.java new file mode 100644 index 0000000000..832c5e746e --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/CustomElement.java @@ -0,0 +1,18 @@ +package com.baeldung.xmlhtml.pojo.jaxb.html.elements; + +import javax.xml.bind.annotation.XmlValue; + +public class CustomElement { + + private String value; + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Meta.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Meta.java new file mode 100644 index 0000000000..11b6b86c05 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/Meta.java @@ -0,0 +1,30 @@ +package com.baeldung.xmlhtml.pojo.jaxb.html.elements; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlValue; + +public class Meta { + + private String title; + + public String getTitle() { + return title; + } + + @XmlAttribute(name = "title") + public void setTitle(String title) { + this.title = title; + } + + private String value; + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/NestedElement.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/NestedElement.java new file mode 100644 index 0000000000..20557064bb --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/html/elements/NestedElement.java @@ -0,0 +1,17 @@ +package com.baeldung.xmlhtml.pojo.jaxb.html.elements; + +import javax.xml.bind.annotation.XmlElement; + +public class NestedElement { + + private CustomElement customElement; + + public CustomElement getCustomElement() { + return customElement; + } + + @XmlElement(name = "p") + public void setCustomElement(CustomElement customElement) { + this.customElement = customElement; + } +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/XMLExample.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/XMLExample.java new file mode 100644 index 0000000000..587cf69223 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/XMLExample.java @@ -0,0 +1,21 @@ +package com.baeldung.xmlhtml.pojo.jaxb.xml; + +import com.baeldung.xmlhtml.pojo.jaxb.xml.elements.Ancestor; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "xmlexample") +public class XMLExample { + + private Ancestor ancestor; + + @XmlElement(name = "ancestor") + public void setAncestor(Ancestor ancestor) { + this.ancestor = ancestor; + } + + public Ancestor getAncestor() { + return ancestor; + } +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/Ancestor.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/Ancestor.java new file mode 100644 index 0000000000..ff2b928206 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/Ancestor.java @@ -0,0 +1,28 @@ +package com.baeldung.xmlhtml.pojo.jaxb.xml.elements; + +import javax.xml.bind.annotation.XmlElement; + +public class Ancestor { + + private DescendantOne descendantOne; + private DescendantTwo descendantTwo; + + public DescendantOne getDescendantOne() { + return descendantOne; + } + + @XmlElement(name = "descendantOne") + public void setDescendantOne(DescendantOne descendantOne) { + this.descendantOne = descendantOne; + } + + public DescendantTwo getDescendantTwo() { + return descendantTwo; + } + + @XmlElement(name = "descendantTwo") + public void setDescendantTwo(DescendantTwo descendantTwo) { + this.descendantTwo = descendantTwo; + } +} + diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantOne.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantOne.java new file mode 100644 index 0000000000..50624cb9fa --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantOne.java @@ -0,0 +1,19 @@ +package com.baeldung.xmlhtml.pojo.jaxb.xml.elements; + +import javax.xml.bind.annotation.XmlValue; + +public class DescendantOne { + + private String value; + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} + diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantThree.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantThree.java new file mode 100644 index 0000000000..7c3ce9b6f7 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantThree.java @@ -0,0 +1,18 @@ +package com.baeldung.xmlhtml.pojo.jaxb.xml.elements; + +import javax.xml.bind.annotation.XmlValue; + +public class DescendantThree { + + private String value; + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantTwo.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantTwo.java new file mode 100644 index 0000000000..1ca989560b --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/jaxb/xml/elements/DescendantTwo.java @@ -0,0 +1,17 @@ +package com.baeldung.xmlhtml.pojo.jaxb.xml.elements; + +import javax.xml.bind.annotation.XmlElement; + +public class DescendantTwo { + + private DescendantThree descendantThree; + + public DescendantThree getDescendantThree() { + return descendantThree; + } + + @XmlElement(name = "descendantThree") + public void setDescendant(DescendantThree descendantThree) { + this.descendantThree = descendantThree; + } +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/Body.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/Body.java new file mode 100644 index 0000000000..630dfe967f --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/Body.java @@ -0,0 +1,23 @@ +package com.baeldung.xmlhtml.pojo.stax; + +public class Body { + + private CustomElement customElement; + + public CustomElement getCustomElement() { + return customElement; + } + public void setCustomElement(CustomElement customElement) { + this.customElement = customElement; + } + + private NestedElement nestedElement; + + public NestedElement getNestedElement() { + return nestedElement; + } + public void setNestedElement(NestedElement nestedElement) { + this.nestedElement = nestedElement; + } + +} \ No newline at end of file diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/CustomElement.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/CustomElement.java new file mode 100644 index 0000000000..6fc1d7b787 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/CustomElement.java @@ -0,0 +1,13 @@ +package com.baeldung.xmlhtml.pojo.stax; + +public class CustomElement { + + private String value; + + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } +} diff --git a/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/NestedElement.java b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/NestedElement.java new file mode 100644 index 0000000000..146ee068af --- /dev/null +++ b/xml/src/main/java/com/baeldung/xmlhtml/pojo/stax/NestedElement.java @@ -0,0 +1,13 @@ +package com.baeldung.xmlhtml.pojo.stax; + +public class NestedElement { + + private CustomElement customElement; + + public CustomElement getCustomElement() { + return customElement; + } + public void setCustomElement(CustomElement customElement) { + this.customElement = customElement; + } +} diff --git a/xml/src/main/resources/xml/in.xml b/xml/src/main/resources/xml/in.xml new file mode 100644 index 0000000000..6fcb404012 --- /dev/null +++ b/xml/src/main/resources/xml/in.xml @@ -0,0 +1,11 @@ + + + + Yo + + + DustyOrb + + + + \ No newline at end of file diff --git a/xml/src/main/resources/xml/jaxb.html b/xml/src/main/resources/xml/jaxb.html new file mode 100644 index 0000000000..80b894cff7 --- /dev/null +++ b/xml/src/main/resources/xml/jaxb.html @@ -0,0 +1,14 @@ + + + + + + +

descendantOne: Yo

+
+

descendantThree: + DustyOrb +

+
+ + diff --git a/xml/src/main/resources/xml/jaxp.html b/xml/src/main/resources/xml/jaxp.html new file mode 100644 index 0000000000..5392eef509 --- /dev/null +++ b/xml/src/main/resources/xml/jaxp.html @@ -0,0 +1,13 @@ + + + + + +

descendantOne: Yo

+
+

descendantThree: + DustyOrb +

+
+ + diff --git a/xml/src/main/resources/xml/stax.html b/xml/src/main/resources/xml/stax.html new file mode 100644 index 0000000000..01951dc7de --- /dev/null +++ b/xml/src/main/resources/xml/stax.html @@ -0,0 +1,15 @@ + + + + + +

descendantOne: Yo

+
+

+ descendantThree: + DustyOrb + +

+
+ + \ No newline at end of file